repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SeleniumHQ/buck | src/com/facebook/buck/multitenant/collect/GenerationMap.kt | 2 | 5348 | /*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.multitenant.collect
import java.util.*
private data class GenerationValue<VALUE>(val generation: Int, val value: VALUE?)
/**
* A bucket is a pair of:
* - Info that applies to the general bucket.
* - Sequence of values that the bucket has taken over time. Each value is paired with a generation.
*/
private class Bucket<INFO, VALUE : Any>(val info: INFO) {
/**
* If this were C++, we would use folly::small_vector here. If it were Rust, we would use the
* smallvec crate. Because we're on the JVM, perhaps we could approximate either of those with
* a combination of fixed-size array and a MutableList for overflow, but we'll just keep it
* simple.
*/
private val versions: MutableList<GenerationValue<VALUE>> = mutableListOf()
fun addVersion(generation: Int, value: VALUE?) {
val generationValue = GenerationValue(generation, value)
versions.add(generationValue)
}
fun getVersion(generation: Int): VALUE? {
// We expect that the caller is more often interested in recent versions of a bucket rather
// than older versions. To that end, we attempt a reverse linear search rather than a binary
// search.
for (index in (versions.size - 1) downTo 0) {
val version = versions[index]
if (generation >= version.generation) {
return version.value
}
}
return null
}
}
/**
* GenerationList is a glorified append-only list-of-lists.
* This class is not threadsafe: it must be synchronized externally.
*/
private class GenerationList<INFO, VALUE : Any>() {
private val buckets: MutableList<Bucket<INFO, VALUE>> = mutableListOf()
/**
* Note that this will always create a new bucket.
*
* Callers are responsible for holding onto the bucket index that is returned because there
* is no way to get it back later.
*/
fun addBucket(info: INFO): Int {
val bucket = Bucket<INFO, VALUE>(info)
val index = buckets.size
buckets.add(bucket)
return index
}
fun addVersion(bucketIndex: Int, value: VALUE?, generation: Int) {
val bucket = buckets[bucketIndex]
bucket.addVersion(generation, value)
}
fun getVersion(bucketIndex: Int, generation: Int): VALUE? {
val bucket = buckets[bucketIndex]
return bucket.getVersion(generation)
}
fun getAllInfoValuePairsForGeneration(generation: Int): Sequence<Pair<INFO, VALUE>> {
return buckets.asSequence().map {
val value = it.getVersion(generation)
if (value != null) {
Pair(it.info, value)
} else {
null
}
}.filterNotNull()
}
}
/**
* GenerationMap is a glorified append-only multimap.
*
* For convenience, derived info about the key can be stored inline with its versioned values for
* quick retrieval. This may turn out to be a poor API choice: I just happened to have one other
* use case for multitenant stuff where this was convenient.
*
* This class is not threadsafe: it must be synchronized externally.
*/
class GenerationMap<KEY : Any, VALUE : Any, KEY_INFO>(val keyInfoDeriver: (key: KEY) -> KEY_INFO) {
private val generationList = GenerationList<KEY_INFO, VALUE>()
private val keyToBucketIndex = HashMap<KEY, Int>()
fun addVersion(key: KEY, value: VALUE?, generation: Int) {
val bucketIndex = findOrCreateBucketIndex(key)
generationList.addVersion(bucketIndex, value, generation)
}
fun getVersion(key: KEY, generation: Int): VALUE? {
val bucketIndex = findOrCreateBucketIndex(key)
return generationList.getVersion(bucketIndex, generation)
}
fun getAllInfoValuePairsForGeneration(generation: Int): Sequence<Pair<KEY_INFO, VALUE>> {
// One thing that is special about iterating the generationList rather than the
// keyToBucketIndex is that we can ensure we return a parallel Stream. Note that the
// parallelStream() method defined on java.util.Collection (which includes the Set returned
// by Map.entrySet()) is "possibly parallel," so true parallelism is not guaranteed. The
// downside of iterating the generationList is that the key is not readily available, though
// the keyInfo is.
return generationList.getAllInfoValuePairsForGeneration(generation)
}
private fun findOrCreateBucketIndex(key: KEY): Int {
return keyToBucketIndex.getOrPut(key) {
val keyInfo = keyInfoDeriver(key)
val index = generationList.addBucket(keyInfo)
keyToBucketIndex[key] = index
index
}
}
}
| apache-2.0 | f5503909fc9383aa5282190f23624507 | 37.2 | 100 | 0.674084 | 4.365714 | false | false | false | false |
google/taqo-paco | taqo_client/plugins/email/android/src/main/kotlin/com/taqo/survey/taqo_email_plugin/TaqoEmailPlugin.kt | 1 | 3820 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.taqo.survey.taqo_email_plugin
import android.content.Context
import android.content.Intent
import androidx.annotation.NonNull
import de.cketti.mailto.EmailIntentBuilder
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
private const val CHANNEL_NAME : String = "taqo_email_plugin"
private const val SEND_EMAIL : String = "send_email"
private const val TO_ARG : String = "to"
private const val SUBJ_ARG : String = "subject"
/** TaqoEmailPlugin */
class TaqoEmailPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private lateinit var context : Context
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
context = flutterPluginBinding.applicationContext
channel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL_NAME)
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
when (call.method) {
SEND_EMAIL -> {
val to : String?
val subject : String?
try {
to = call.argument<String>(TO_ARG)
subject = call.argument<String>(SUBJ_ARG)
} catch (e : ClassCastException) {
return result.error("Failed", "Must specify 'to' and 'subject' args", "")
}
if (to == null || subject == null) {
return result.error("Failed", "Must specify 'to' and 'subject' args", "")
}
val intent = createEmailIntent(to, subject).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val chooserIntent = Intent.createChooser(intent, "Choose your email client").addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(chooserIntent)
result.success("Success")
}
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
private fun createEmailIntent(to : String, subject : String) : Intent {
return EmailIntentBuilder.from(context)
.sendTo(to)
.subject(subject)
.build()
}
}
/// Because "to" is an operator in the Kotlin stdlib, we need to extend a method to set the "to"
// field. Since that Set in EmailIntentBuilder is private, we need to use reflection to set it :\
private fun EmailIntentBuilder.sendTo(who : String) : EmailIntentBuilder {
EmailIntentBuilder::class.java.getDeclaredField("to").let {
it.isAccessible = true
val toObj = it.get(this)
if (toObj != null && toObj is java.util.LinkedHashSet<*>) {
@Suppress("UNCHECKED_CAST")
val toSet = it.get(this) as java.util.LinkedHashSet<Any>
toSet.add(who)
}
}
return this
}
| apache-2.0 | efd5ba6bffc2c67bf34b393504ca6485 | 37.2 | 102 | 0.713351 | 4.25864 | false | false | false | false |
JimSeker/saveData | sqliteDBDemo_kt/app/src/main/java/edu/cs4730/sqlitedbdemo_kt/myAdapter.kt | 1 | 2828 | package edu.cs4730.sqlitedbdemo_kt
import androidx.recyclerview.widget.RecyclerView
import android.widget.TextView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.view.View
import edu.cs4730.sqlitedbdemo_kt.db.mySQLiteHelper
import android.widget.Toast
/**
* this adapter is very similar to the adapters used for listview, except a ViewHolder is required
* see http://developer.android.com/training/improving-layouts/smooth-scrolling.html
* except instead having to implement a ViewHolder, it is implemented within
* the adapter.
*/
class myAdapter //constructor
(private var mCursor: Cursor?, private val rowLayout: Int, private val mContext: Context) :
RecyclerView.Adapter<myAdapter.ViewHolder>() {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var myName: TextView
var myScore: TextView
init {
myName = itemView.findViewById(R.id.name)
myScore = itemView.findViewById(R.id.score)
}
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(rowLayout, viewGroup, false)
return ViewHolder(v)
}
// Replace the contents of a view (invoked by the layout manager)
@SuppressLint("Range")
override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
//this assumes it's not called with a null mCursor, since i means there is a data.
mCursor!!.moveToPosition(i)
viewHolder.myName.text =
mCursor!!.getString(mCursor!!.getColumnIndex(mySQLiteHelper.KEY_NAME))
viewHolder.myScore.text =
mCursor!!.getInt(mCursor!!.getColumnIndex(mySQLiteHelper.KEY_SCORE)).toString()
//itemView is the whole cardview, so it easy to a click listener.
viewHolder.itemView.setOnClickListener { v ->
val tv =
v.findViewById<TextView>(R.id.name) //view in this case is the itemView, which had other pieces in it.
Toast.makeText(mContext, tv.text, Toast.LENGTH_SHORT).show()
}
}
// Return the size of your data set (invoked by the layout manager)
override fun getItemCount(): Int {
return if (mCursor == null) 0 else mCursor!!.count
}
//change the cursor as needed and have the system redraw the data.
fun setCursor(c: Cursor?) {
mCursor = c
notifyDataSetChanged()
}
} | apache-2.0 | 5781cb7fb5135ac31530f9eb65b77825 | 40 | 118 | 0.699081 | 4.446541 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/tileentities/TileEntityWCEAware.kt | 1 | 1252 | package szewek.mcflux.tileentities
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.ITickable
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import szewek.fl.energy.Battery
import szewek.mcflux.fluxable.FluxableCapabilities
import szewek.mcflux.fluxable.WorldChunkEnergy
open class TileEntityWCEAware : TileEntity(), ITickable {
protected var wce: WorldChunkEnergy? = null
protected var bat: Battery? = null
protected var updateMode = 0
override fun setWorld(w: World) {
if (world == null || world != w)
updateMode = updateMode or 1
super.setWorld(w)
}
override fun setPos(bp: BlockPos) {
if (pos == null || pos != bp)
updateMode = updateMode or 2
super.setPos(bp)
}
override fun update() {
if (wce == null)
updateMode = updateMode or 1
if (bat == null)
updateMode = updateMode or 2
if (updateMode != 0) {
if (updateMode and 1 != 0)
wce = world.getCapability(FluxableCapabilities.CAP_WCE, null)
if (wce == null)
return
if (updateMode and 2 != 0)
bat = wce!!.getEnergyChunk(pos.x, pos.y, pos.z)
if (updateVariables())
updateMode = 0
}
updateTile()
}
protected open fun updateVariables() = true
protected open fun updateTile() {}
}
| mit | 5915f0de6b91c8fa21c0cd51044902e3 | 24.55102 | 65 | 0.709265 | 3.226804 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/download-preplanned-map-area/src/main/java/com/esri/arcgisruntime/sample/downloadpreplannedmaparea/MainActivity.kt | 1 | 18582 | /*
* Copyright 2020 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.arcgisruntime.sample.downloadpreplannedmaparea
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.portal.Portal
import com.esri.arcgisruntime.portal.PortalItem
import com.esri.arcgisruntime.sample.downloadpreplannedmaparea.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.downloadpreplannedmaparea.databinding.DownloadPreplannedMapDialogLayoutBinding
import com.esri.arcgisruntime.security.AuthenticationManager
import com.esri.arcgisruntime.security.DefaultAuthenticationChallengeHandler
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.tasks.offlinemap.DownloadPreplannedOfflineMapJob
import com.esri.arcgisruntime.tasks.offlinemap.OfflineMapTask
import com.esri.arcgisruntime.tasks.offlinemap.PreplannedMapArea
import com.esri.arcgisruntime.tasks.offlinemap.PreplannedUpdateMode
import java.io.File
import java.util.*
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
private val offlineMapDirectory by lazy { File(externalCacheDir?.path + getString(R.string.preplanned_offline_map_dir)) }
private var preplannedMapAreasAdapter: ArrayAdapter<String>? = null
private val downloadedMapAreaNames by lazy { mutableListOf<String>() }
private var downloadedMapAreasAdapter: ArrayAdapter<String>? = null
private val downloadedMapAreas by lazy { mutableListOf<ArcGISMap>() }
private var dialog: AlertDialog? = null
private var selectedPreplannedMapArea: PreplannedMapArea? = null
private var downloadPreplannedOfflineMapJob: DownloadPreplannedOfflineMapJob? = null
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val availableAreasListView: ListView by lazy {
activityMainBinding.include.availableAreasListView
}
private val downloadedMapAreasListView: ListView by lazy {
activityMainBinding.include.downloadedMapAreasListView
}
private val downloadButton: Button by lazy {
activityMainBinding.include.downloadButton
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// delete any previous instances of downloaded maps
externalCacheDir?.deleteRecursively()
// create a temporary directory in the app's cache when required
offlineMapDirectory.also {
when {
it.mkdirs() -> Log.i(TAG, "Created directory for offline map in " + it.path)
it.exists() -> Log.i(TAG, "Offline map directory already exists at " + it.path)
else -> Log.e(TAG, "Error creating offline map directory at: " + it.path)
}
}
// set the authentication manager to handle challenges when accessing the portal
// Note: The sample data is publicly available, so you shouldn't be challenged
AuthenticationManager.setAuthenticationChallengeHandler(
DefaultAuthenticationChallengeHandler(this)
)
// create a portal to ArcGIS Online
val portal = Portal(getString(R.string.arcgis_online_url))
// create a portal item using the portal and the item id of a map service
val portalItem = PortalItem(portal, getString(R.string.naperville_water_network_item_id))
// create an offline map task from the portal item
val offlineMapTask = OfflineMapTask(portalItem)
// create a map with the portal item
val onlineMap = ArcGISMap(portalItem)
// create a red outline to mark the areas of interest of the preplanned map areas
val areaOfInterestRenderer =
SimpleRenderer(SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 5.0f))
// create a graphics overlay to show the preplanned map areas extents (areas of interest)
val areasOfInterestGraphicsOverlay = GraphicsOverlay().apply {
renderer = areaOfInterestRenderer
}
mapView.apply {
// add the online map to the map view
map = onlineMap
// add the area of interest overlay
graphicsOverlays.add(areasOfInterestGraphicsOverlay)
}
createPreplannedAreasListView(onlineMap, offlineMapTask)
createDownloadAreasListView()
// create download button
downloadButton.apply {
isEnabled = false
setOnClickListener { downloadPreplannedArea(offlineMapTask) }
}
}
/**
* Download the selected preplanned map area from the list view to a temporary directory. The
* download job is tracked in another list view.
*
* @param offlineMapTask used to take preplanned map areas offline
*/
private fun downloadPreplannedArea(offlineMapTask: OfflineMapTask) {
if (selectedPreplannedMapArea == null) {
return
}
// create default download parameters from the offline map task
val offlineMapParametersFuture =
offlineMapTask.createDefaultDownloadPreplannedOfflineMapParametersAsync(
selectedPreplannedMapArea
)
offlineMapParametersFuture.addDoneListener {
try {
// get the offline map parameters
val offlineMapParameters = offlineMapParametersFuture.get().apply {
// set the update mode to not receive updates
updateMode = PreplannedUpdateMode.NO_UPDATES
}
// create a job to download the preplanned offline map to a temporary directory
downloadPreplannedOfflineMapJob = offlineMapTask.downloadPreplannedOfflineMap(
offlineMapParameters,
offlineMapDirectory.path + File.separator + selectedPreplannedMapArea?.portalItem?.title
).also {
// create and update a progress dialog for the job
val progressDialogLayoutBinding = DownloadPreplannedMapDialogLayoutBinding.inflate(layoutInflater)
dialog = createProgressDialog(it)
dialog?.setView(progressDialogLayoutBinding.root)
dialog?.show()
it.addProgressChangedListener {
progressDialogLayoutBinding.progressBar.progress = it.progress
progressDialogLayoutBinding.progressTextView.text = "${it.progress}%"
}
// start the job
it.start()
}
// when the job finishes
downloadPreplannedOfflineMapJob?.addJobDoneListener {
// dismiss progress dialog
dialog?.dismiss()
// if there's a result from the download preplanned offline map job
if (downloadPreplannedOfflineMapJob?.status != Job.Status.SUCCEEDED) {
val error =
"Job finished with an error: " + downloadPreplannedOfflineMapJob?.error?.message
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
return@addJobDoneListener
}
downloadPreplannedOfflineMapJob?.result?.let { downloadPreplannedOfflineMapResult ->
if (downloadPreplannedOfflineMapResult.hasErrors()) {
// collect the layer and table errors into a single alert message
val stringBuilder = StringBuilder("Errors: ")
downloadPreplannedOfflineMapResult.layerErrors?.forEach { (key, value) ->
stringBuilder.append("Layer: ${key.name}. Exception: ${value.message}. ")
}
downloadPreplannedOfflineMapResult.tableErrors?.forEach { (key, value) ->
stringBuilder.append("Table: ${key.tableName}. Exception: ${value.message}. ")
}
val error =
"One or more errors occurred with the Offline Map Result: $stringBuilder"
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
return@addJobDoneListener
}
// get the offline map
downloadPreplannedOfflineMapResult.offlineMap?.let { offlineMap ->
mapView.apply {
// add it to the map view
map = offlineMap
// hide the area of interest graphics
graphicsOverlays[0].isVisible = false
}
// add the map name to the list view of downloaded map areas
downloadedMapAreaNames.add(offlineMap.item.title)
// select the downloaded map area
downloadedMapAreasListView.setItemChecked(
downloadedMapAreaNames.size - 1,
true
)
downloadedMapAreasAdapter?.notifyDataSetChanged()
// de-select the area in the preplanned areas list view
availableAreasListView.clearChoices()
preplannedMapAreasAdapter?.notifyDataSetChanged()
// add the offline map to a list of downloaded map areas
downloadedMapAreas.add(offlineMap)
// disable the download button
downloadButton.isEnabled = false
}
}
}
} catch (e: Exception) {
val error =
"Failed to generate default parameters for the download job: " + e.cause?.message
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
}
}
}
/**
* Creates a list view showing available preplanned map areas. Graphics are drawn on the map view
* showing the preplanned map areas available. Tapping on a preplanned map area in the list view
* will set the map view's viewpoint to the area and, if a map has not yet been downloaded for
* this area, the download button will be enabled.
*
* @param onlineMap used as the background for showing available preplanned map areas
* @param offlineMapTask used to take preplanned map areas offline
*/
private fun createPreplannedAreasListView(
onlineMap: ArcGISMap,
offlineMapTask: OfflineMapTask
) {
var preplannedMapAreas: List<PreplannedMapArea>
val preplannedMapAreaNames: MutableList<String> = ArrayList()
preplannedMapAreasAdapter =
ArrayAdapter(this, R.layout.item_map_area, preplannedMapAreaNames)
availableAreasListView.adapter = preplannedMapAreasAdapter
// get the preplanned map areas from the offline map task and show them in the list view
val preplannedMapAreasFuture =
offlineMapTask.preplannedMapAreasAsync
preplannedMapAreasFuture.addDoneListener {
try {
// get the preplanned areas
preplannedMapAreas = preplannedMapAreasFuture.get().onEach { preplannedMapArea ->
// add the preplanned map area name to the list view
preplannedMapAreaNames.add(preplannedMapArea.portalItem.title)
// load each area and show a red border around their area of interest
preplannedMapArea.loadAsync()
preplannedMapArea.addDoneLoadingListener {
if (preplannedMapArea.loadStatus == LoadStatus.LOADED) {
// add the area of interest as a graphic
mapView.graphicsOverlays[0].graphics.add(Graphic(preplannedMapArea.areaOfInterest))
} else {
val error =
"Failed to load preplanned map area: " + preplannedMapArea.loadError.message
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
}
}
}
// notify the adapter that the list of preplanned map area names has changed
preplannedMapAreasAdapter?.notifyDataSetChanged()
// on list view click
availableAreasListView.onItemClickListener =
AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, i: Int, _: Long ->
selectedPreplannedMapArea = preplannedMapAreas[i]
if (selectedPreplannedMapArea == null) {
downloadButton.isEnabled = false
return@OnItemClickListener
}
// clear the download jobs list view selection
downloadedMapAreasListView.clearChoices()
downloadedMapAreasAdapter?.notifyDataSetChanged()
val areaOfInterest =
GeometryEngine.buffer(
selectedPreplannedMapArea?.areaOfInterest,
50.0
).extent
// show the online map with the areas of interest
mapView.apply {
map = onlineMap
graphicsOverlays[0].isVisible = true
// set the viewpoint to the preplanned map area's area of interest
setViewpointAsync(Viewpoint(areaOfInterest), 1.5f)
}
// enable download button only for those map areas which have not been downloaded already
File(
externalCacheDir?.path + getString(R.string.preplanned_offline_map_dir) +
File.separator + selectedPreplannedMapArea?.portalItem?.title
).also {
downloadButton.isEnabled = !it.exists()
}
}
} catch (e: Exception) {
val error = "Failed to get the preplanned map areas from the offline map task."
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(TAG, error)
}
}
}
/**
* Create a list view which holds downloaded map areas.
*
*/
private fun createDownloadAreasListView() {
downloadedMapAreasAdapter =
ArrayAdapter(this, R.layout.item_map_area, downloadedMapAreaNames)
downloadedMapAreasListView.apply {
adapter = downloadedMapAreasAdapter
onItemClickListener =
AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, i: Int, _: Long ->
mapView.apply {
// set the downloaded map to the map view
map = downloadedMapAreas[i]
// hide the graphics overlays
graphicsOverlays[0].isVisible = false
}
// disable the download button
downloadButton.isEnabled = false
// clear the available map areas list view selection
availableAreasListView.clearChoices()
preplannedMapAreasAdapter?.notifyDataSetChanged()
}
}
}
/**
* Create a progress dialog box for tracking the generate geodatabase job.
*
* @param downloadPreplannedOfflineMapJob to be tracked
* @return an AlertDialog set with the dialog layout view
*/
private fun createProgressDialog(downloadPreplannedOfflineMapJob: DownloadPreplannedOfflineMapJob): AlertDialog {
val dialogBuilder = AlertDialog.Builder(this@MainActivity).apply {
setTitle("Download preplanned offline map")
// provide a cancel button on the dialog
setNegativeButton("Cancel") { _, _ ->
downloadPreplannedOfflineMapJob.cancelAsync()
}
setCancelable(false)
val dialogLayoutBinding = DownloadPreplannedMapDialogLayoutBinding.inflate(layoutInflater)
setView(dialogLayoutBinding.root)
}
return dialogBuilder.create()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 08a8c42c973da481049de392d2a7cde0 | 47.139896 | 125 | 0.604564 | 5.541903 | false | false | false | false |
openbase/jul | module/pattern/trigger/src/main/java/org/openbase/jul/pattern/trigger/TriggerPool.kt | 1 | 9093 | package org.openbase.jul.pattern.trigger
import org.openbase.jul.exception.CouldNotPerformException
import org.openbase.jul.exception.InstantiationException
import org.openbase.jul.exception.NotAvailableException
import org.openbase.jul.exception.printer.ExceptionPrinter
import org.openbase.jul.extension.type.processing.TimestampProcessor
import org.openbase.jul.pattern.Observer
import org.openbase.type.domotic.state.ActivationStateType
import org.slf4j.LoggerFactory
/*-
* #%L
* JUL Pattern Trigger
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/ /**
* @author [Timo Michalski](mailto:[email protected])
*/
class TriggerPool: AbstractTrigger() {
enum class TriggerAggregation {
AND, OR
}
private var active: Boolean
private val triggerListAND: MutableList<Trigger>
private val triggerListOR: MutableList<Trigger>
private val triggerAndObserver: Observer<Trigger, ActivationStateType.ActivationState>
private val triggerOrObserver: Observer<Trigger, ActivationStateType.ActivationState>
init {
triggerListAND = ArrayList()
triggerListOR = ArrayList()
active = false
triggerAndObserver =
Observer { source: Trigger?, data: ActivationStateType.ActivationState? -> verifyCondition() }
triggerOrObserver =
Observer { source: Trigger?, data: ActivationStateType.ActivationState? -> verifyCondition() }
try {
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.UNKNOWN
).build()
)
)
} catch (ex: CouldNotPerformException) {
throw InstantiationException("Could not set initial state", ex)
}
}
@Throws(CouldNotPerformException::class)
fun addTrigger(trigger: Trigger, triggerAggregation: TriggerAggregation) {
if (triggerAggregation == TriggerAggregation.AND) {
triggerListAND.add(trigger)
} else {
triggerListOR.add(trigger)
}
if (active) {
when (triggerAggregation) {
TriggerAggregation.OR -> trigger.addObserver(triggerOrObserver)
TriggerAggregation.AND -> trigger.addObserver(triggerAndObserver)
}
try {
trigger.activate()
} catch (ex: InterruptedException) {
throw CouldNotPerformException("Could not activate Trigger.", ex)
}
try {
verifyCondition()
} catch (ex: NotAvailableException) {
//ExceptionPrinter.printHistory("Data not available " + trigger, ex, LoggerFactory.getLogger(getClass()));
}
}
}
fun removeTrigger(trigger: AbstractTrigger) {
if (triggerListAND.contains(trigger)) {
trigger.removeObserver(triggerAndObserver)
triggerListAND.remove(trigger)
} else if (triggerListOR.contains(trigger)) {
trigger.removeObserver(triggerOrObserver)
triggerListOR.remove(trigger)
}
}
@Throws(CouldNotPerformException::class)
private fun verifyCondition() {
if (verifyOrCondition() || verifyAndCondition()) {
if (activationState.value != ActivationStateType.ActivationState.State.ACTIVE) {
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.ACTIVE
).build()
)
)
}
} else {
if (activationState.value != ActivationStateType.ActivationState.State.INACTIVE) {
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.INACTIVE
).build()
)
)
}
}
}
@Throws(CouldNotPerformException::class)
private fun verifyAndCondition(): Boolean {
return if (triggerListAND.isEmpty()) {
false
} else triggerListAND
.stream()
.allMatch { trigger: Trigger ->
try {
return@allMatch trigger.activationState.value == ActivationStateType.ActivationState.State.ACTIVE
} catch (exception: NotAvailableException) {
return@allMatch false
}
}
}
@Throws(CouldNotPerformException::class)
private fun verifyOrCondition(): Boolean {
return triggerListOR
.stream()
.anyMatch { trigger: Trigger ->
try {
return@anyMatch trigger.activationState.value == ActivationStateType.ActivationState.State.ACTIVE
} catch (exception: NotAvailableException) {
return@anyMatch false
}
}
}
/**
* return the total amount of registered triggers.
*
* @return the total amount of trigger.
*/
val size: Int
get() = triggerListAND.size + triggerListOR.size
/**
* Check if pool contains any trigger.
*
* @return true if no trigger are registered.
*/
val isEmpty: Boolean
get() = triggerListAND.isEmpty() && triggerListOR.isEmpty()
@Throws(CouldNotPerformException::class, InterruptedException::class)
override fun activate() {
for (trigger in triggerListAND) {
trigger.addObserver(triggerAndObserver)
trigger.activate()
}
for (trigger in triggerListOR) {
trigger.addObserver(triggerOrObserver)
trigger.activate()
}
verifyCondition()
active = true
}
@Throws(CouldNotPerformException::class, InterruptedException::class)
override fun deactivate() {
for (trigger in triggerListAND) {
trigger.removeObserver(triggerAndObserver)
trigger.deactivate()
}
for (trigger in triggerListOR) {
trigger.removeObserver(triggerOrObserver)
trigger.deactivate()
}
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.UNKNOWN
).build()
)
)
active = false
}
override fun isActive(): Boolean {
return active
}
@Throws(CouldNotPerformException::class)
fun forceNotification() {
try {
if (verifyOrCondition() || verifyAndCondition()) {
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.ACTIVE
).build()
)
)
} else {
notifyChange(
TimestampProcessor.updateTimestampWithCurrentTime(
ActivationStateType.ActivationState.newBuilder().setValue(
ActivationStateType.ActivationState.State.INACTIVE
).build()
)
)
}
} catch (ex: CouldNotPerformException) {
throw CouldNotPerformException("Could not force notify trigger pool!", ex)
}
}
override fun shutdown() {
try {
deactivate()
} catch (ex: InterruptedException) {
Thread.currentThread().interrupt()
} catch (ex: CouldNotPerformException) {
ExceptionPrinter.printHistory("Could not shutdown $this", ex, LoggerFactory.getLogger(javaClass))
}
super.shutdown()
}
companion object {
private val LOGGER = LoggerFactory.getLogger(AbstractTrigger::class.java)
}
}
| lgpl-3.0 | 04ddb94553a93deeeeb9dc8e4bb4ffba | 35.665323 | 122 | 0.606401 | 5.280488 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/episodes/EpisodeWatchedUpToDialog.kt | 1 | 2179 | package com.battlelancer.seriesguide.shows.episodes
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import com.battlelancer.seriesguide.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder
/**
* Asks user to confirm before flagging all episodes
* released up to (== including) the given one as watched,
* excluding those with no release date.
*/
class EpisodeWatchedUpToDialog : AppCompatDialogFragment() {
private var showId: Long = 0
private var episodeReleaseTime: Long = 0
private var episodeNumber: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireArguments().run {
showId = getLong(ARG_SHOW_ID)
episodeReleaseTime = getLong(ARG_EPISODE_RELEASE_TIME)
episodeNumber = getInt(ARG_EPISODE_NUMBER)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.confirmation_watched_up_to)
.setPositiveButton(R.string.action_watched_up_to) { _, _ ->
EpisodeTools.episodeWatchedUpTo(
context, showId, episodeReleaseTime, episodeNumber
)
}
.setNegativeButton(android.R.string.cancel) { _, _ -> dismiss() }
.create()
}
companion object {
private const val ARG_SHOW_ID = "ARG_SHOW_ID"
private const val ARG_EPISODE_RELEASE_TIME = "ARG_EPISODE_RELEASE_TIME"
private const val ARG_EPISODE_NUMBER = "ARG_EPISODE_NUMBER"
@JvmStatic
fun newInstance(
showId: Long,
episodeReleaseTime: Long,
episodeNumber: Int
): EpisodeWatchedUpToDialog {
return EpisodeWatchedUpToDialog().apply {
arguments = Bundle().apply {
putLong(ARG_SHOW_ID, showId)
putLong(ARG_EPISODE_RELEASE_TIME, episodeReleaseTime)
putInt(ARG_EPISODE_NUMBER, episodeNumber)
}
}
}
}
} | apache-2.0 | 4c277fffe34781f4872939d2b5129c63 | 34.16129 | 79 | 0.635613 | 4.853007 | false | false | false | false |
Restioson/kettle-engine | core/src/main/kotlin/io/github/restioson/kettle/script/Batch.kt | 1 | 3123 | package io.github.restioson.kettle.script
import io.github.restioson.kettle.api.Threadsafe
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.suspendCoroutine
/**
* Object for batching functions from coroutines to be run inside the update loop
*
* Example:
*
* ```kotlin
* launch(CommonPool) {
* // Suspends coroutine until run
* // This will run in the update loop, which makes sure that
* // every hardware running the game will have the same speed
* // of updating
* val returnValue = Batch.run { delta -> // delta time
* return updateGamestate(delta)
* }
*
* // Returns a Deffered<T> which deffers the return
* // value of the function.
* // Use this if you need to schedule a func and
* // continue with coroutine, maybe checking back
* // to the Deffered<T> returned
* val defferedReturn = Batch.schedule {
* updateGamestateNoReturn(it) // it is the default
* // param name
* }
*
* }
*
* // Schedule can be called outside of coroutines!
* // Run can only be called in coroutines and suspending
* // functions, as it is a suspending function
* Batch.schedule {
* updateGamestate()
* }
*/
object Batch {
/**
* Represents a function to be run internally
*/
private class BatchedFunc<R>(val func: (Float) -> R, val coro: Continuation<R>) {
/**
* Run the function and optionally resume the coroutine it is from with value
*/
operator fun invoke(delta: Float) {
val returnValue = this.func(delta)
this.coro.resume(returnValue)
}
}
/**
* The internal threadsafe queue used to store batched functions
*/
private val batch: Queue<BatchedFunc<*>> = ConcurrentLinkedQueue()
/**
* Schedules a function to be run
*
* This method is threadsafe
*
* @param func the function to be scheduled
* @return an instance of `Deffered<R>` which can be used to get the return of `func`
*/
@Threadsafe
fun <R> schedule(func: (Float) -> R) = async(CommonPool) {
Batch.run(func)
}
/**
* Schedules a function to be run, suspends the coroutine, and resumes it with the return of the function.
*
* This method is threadsafe
*
* Unsuspends the coroutine with the return of `func` (via [BatchedFunc])
*
* @param func the function to be scheduled
*
*/
@Threadsafe
suspend fun <R> run(func: (Float) -> R): R = suspendCoroutine {
batch.add(BatchedFunc(func, it))
}
/**
* Runs the batched functions
*
* This method is threadsafe
*
* @param delta the time from this tick to last
*/
@Threadsafe
internal fun execute(delta: Float) {
while (!batch.isEmpty()) {
batch.poll().invoke(delta)
}
}
}
| apache-2.0 | e9c89b29aa2247348479a78b5fc3ae59 | 27.916667 | 110 | 0.62472 | 4.130952 | false | false | false | false |
commons-app/apps-android-commons | app/src/androidTest/java/fr/free/nrw/commons/UploadCancelledTest.kt | 3 | 5736 | package fr.free.nrw.commons
import android.app.Activity
import android.app.Instrumentation
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import androidx.test.uiautomator.UiDevice
import fr.free.nrw.commons.LocationPicker.LocationPickerActivity
import fr.free.nrw.commons.UITestHelper.Companion.childAtPosition
import fr.free.nrw.commons.auth.LoginActivity
import org.hamcrest.CoreMatchers
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UploadCancelledTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(LoginActivity::class.java)
@Rule
@JvmField
var mGrantPermissionRule: GrantPermissionRule =
GrantPermissionRule.grant(
"android.permission.WRITE_EXTERNAL_STORAGE"
)
private val device: UiDevice =
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
@Before
fun setup() {
try {
Intents.init()
} catch (ex: IllegalStateException) {
}
device.unfreezeRotation()
device.setOrientationNatural()
device.freezeRotation()
UITestHelper.loginUser()
UITestHelper.skipWelcome()
Intents.intending(CoreMatchers.not(IntentMatchers.isInternal()))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))
}
@After
fun teardown() {
try {
Intents.release()
} catch (ex: IllegalStateException) {
}
}
@Test
fun uploadCancelledAfterLocationPickedTest() {
val bottomNavigationItemView = onView(
allOf(
childAtPosition(
childAtPosition(
withId(R.id.fragment_main_nav_tab_layout),
0
),
1
),
isDisplayed()
)
)
bottomNavigationItemView.perform(click())
UITestHelper.sleep(12000)
val actionMenuItemView = onView(
allOf(
withId(R.id.list_sheet),
childAtPosition(
childAtPosition(
withId(R.id.toolbar),
1
),
0
),
isDisplayed()
)
)
actionMenuItemView.perform(click())
val recyclerView = onView(
allOf(
withId(R.id.rv_nearby_list),
)
)
recyclerView.perform(
RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(
0,
click()
)
)
val linearLayout3 = onView(
allOf(
withId(R.id.cameraButton),
childAtPosition(
allOf(
withId(R.id.nearby_button_layout),
),
0
),
isDisplayed()
)
)
linearLayout3.perform(click())
val pasteSensitiveTextInputEditText = onView(
allOf(
withId(R.id.caption_item_edit_text),
childAtPosition(
childAtPosition(
withId(R.id.caption_item_edit_text_input_layout),
0
),
0
),
isDisplayed()
)
)
pasteSensitiveTextInputEditText.perform(replaceText("test"), closeSoftKeyboard())
val pasteSensitiveTextInputEditText2 = onView(
allOf(
withId(R.id.description_item_edit_text),
childAtPosition(
childAtPosition(
withId(R.id.description_item_edit_text_input_layout),
0
),
0
),
isDisplayed()
)
)
pasteSensitiveTextInputEditText2.perform(replaceText("test"), closeSoftKeyboard())
val appCompatButton2 = onView(
allOf(
withId(R.id.btn_next),
childAtPosition(
childAtPosition(
withId(R.id.ll_container_media_detail),
2
),
1
),
isDisplayed()
)
)
appCompatButton2.perform(click())
val appCompatButton3 = onView(
allOf(
withId(android.R.id.button1),
)
)
appCompatButton3.perform(scrollTo(), click())
Intents.intended(IntentMatchers.hasComponent(LocationPickerActivity::class.java.name))
val floatingActionButton3 = onView(
allOf(
withId(R.id.location_chosen_button),
isDisplayed()
)
)
UITestHelper.sleep(2000)
floatingActionButton3.perform(click())
}
}
| apache-2.0 | c316a1a539a185f01d424eca9cc5bf10 | 28.56701 | 94 | 0.553347 | 5.452471 | false | true | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/source/online/english/Mangasee.kt | 2 | 10670 | package eu.kanade.tachiyomi.source.online.english
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.regex.Pattern
class Mangasee : ParsedHttpSource() {
override val id: Long = 9
override val name = "Mangasee"
override val baseUrl = "http://mangaseeonline.net"
override val lang = "en"
override val supportsLatest = true
private val recentUpdatesPattern = Pattern.compile("(.*?)\\s(\\d+\\.?\\d*)\\s?(Completed)?")
private val indexPattern = Pattern.compile("-index-(.*?)-")
private val catalogHeaders = Headers.Builder().apply {
add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)")
add("Host", "mangaseeonline.us")
}.build()
override fun popularMangaSelector() = "div.requested > div.row"
override fun popularMangaRequest(page: Int): Request {
val (body, requestUrl) = convertQueryToPost(page, "$baseUrl/search/request.php?sortBy=popularity&sortOrder=descending")
return POST(requestUrl, catalogHeaders, body.build())
}
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("a.resultLink").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
return manga
}
override fun popularMangaNextPageSelector() = "button.requestMore"
override fun searchMangaSelector() = "div.requested > div.row"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = HttpUrl.parse("$baseUrl/search/request.php")!!.newBuilder()
if (!query.isEmpty()) url.addQueryParameter("keyword", query)
val genres = mutableListOf<String>()
val genresNo = mutableListOf<String>()
for (filter in if (filters.isEmpty()) getFilterList() else filters) {
when (filter) {
is Sort -> {
if (filter.state?.index != 0)
url.addQueryParameter("sortBy", if (filter.state?.index == 1) "dateUpdated" else "popularity")
if (filter.state?.ascending != true)
url.addQueryParameter("sortOrder", "descending")
}
is SelectField -> if (filter.state != 0) url.addQueryParameter(filter.key, filter.values[filter.state])
is TextField -> if (!filter.state.isEmpty()) url.addQueryParameter(filter.key, filter.state)
is GenreList -> filter.state.forEach { genre ->
when (genre.state) {
Filter.TriState.STATE_INCLUDE -> genres.add(genre.name)
Filter.TriState.STATE_EXCLUDE -> genresNo.add(genre.name)
}
}
}
}
if (genres.isNotEmpty()) url.addQueryParameter("genre", genres.joinToString(","))
if (genresNo.isNotEmpty()) url.addQueryParameter("genreNo", genresNo.joinToString(","))
val (body, requestUrl) = convertQueryToPost(page, url.toString())
return POST(requestUrl, catalogHeaders, body.build())
}
private fun convertQueryToPost(page: Int, url: String): Pair<FormBody.Builder, String> {
val url = HttpUrl.parse(url)!!
val body = FormBody.Builder().add("page", page.toString())
for (i in 0..url.querySize() - 1) {
body.add(url.queryParameterName(i), url.queryParameterValue(i))
}
val requestUrl = url.scheme() + "://" + url.host() + url.encodedPath()
return Pair(body, requestUrl)
}
override fun searchMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("a.resultLink").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
return manga
}
override fun searchMangaNextPageSelector() = "button.requestMore"
override fun mangaDetailsParse(document: Document): SManga {
val detailElement = document.select("div.well > div.row").first()
val manga = SManga.create()
manga.author = detailElement.select("a[href^=/search/?author=]").first()?.text()
manga.genre = detailElement.select("span.details > div.row > div:has(b:contains(Genre(s))) > a").map { it.text() }.joinToString()
manga.description = detailElement.select("strong:contains(Description:) + div").first()?.text()
manga.status = detailElement.select("a[href^=/search/?status=]").first()?.text().orEmpty().let { parseStatus(it) }
manga.thumbnail_url = detailElement.select("div > img").first()?.absUrl("src")
return manga
}
private fun parseStatus(status: String) = when {
status.contains("Ongoing (Scan)") -> SManga.ONGOING
status.contains("Complete (Scan)") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div.chapter-list > a"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a").first()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href"))
chapter.name = element.select("span.chapterLabel").first().text()?.let { it } ?: ""
chapter.date_upload = element.select("time").first()?.attr("datetime")?.let { parseChapterDate(it) } ?: 0
return chapter
}
private fun parseChapterDate(dateAsString: String): Long {
return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(dateAsString).time
}
override fun pageListParse(document: Document): List<Page> {
val fullUrl = document.baseUri()
val url = fullUrl.substringBeforeLast('/')
val pages = mutableListOf<Page>()
val series = document.select("input.IndexName").first().attr("value")
val chapter = document.select("span.CurChapter").first().text()
var index = ""
val m = indexPattern.matcher(fullUrl)
if (m.find()) {
val indexNumber = m.group(1)
index = "-index-$indexNumber"
}
document.select("div.ContainerNav").first().select("select.PageSelect > option").forEach {
pages.add(Page(pages.size, "$url/$series-chapter-$chapter$index-page-${pages.size + 1}.html"))
}
pages.getOrNull(0)?.imageUrl = imageUrlParse(document)
return pages
}
override fun imageUrlParse(document: Document): String = document.select("img.CurImage").attr("src")
override fun latestUpdatesNextPageSelector() = "button.requestMore"
override fun latestUpdatesSelector(): String = "a.latestSeries"
override fun latestUpdatesRequest(page: Int): Request {
val url = "http://mangaseeonline.net/home/latest.request.php"
val (body, requestUrl) = convertQueryToPost(page, url)
return POST(requestUrl, catalogHeaders, body.build())
}
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("a.latestSeries").first().let {
val chapterUrl = it.attr("href")
val indexOfMangaUrl = chapterUrl.indexOf("-chapter-")
val indexOfLastPath = chapterUrl.lastIndexOf("/")
val mangaUrl = chapterUrl.substring(indexOfLastPath, indexOfMangaUrl)
val defaultText = it.select("p.clamp2").text()
val m = recentUpdatesPattern.matcher(defaultText)
val title = if (m.matches()) m.group(1) else defaultText
manga.setUrlWithoutDomain("/manga" + mangaUrl)
manga.title = title
}
return manga
}
private class Sort : Filter.Sort("Sort", arrayOf("Alphabetically", "Date updated", "Popularity"), Filter.Sort.Selection(2, false))
private class Genre(name: String) : Filter.TriState(name)
private class TextField(name: String, val key: String) : Filter.Text(name)
private class SelectField(name: String, val key: String, values: Array<String>, state: Int = 0) : Filter.Select<String>(name, values, state)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres)
override fun getFilterList() = FilterList(
TextField("Years", "year"),
TextField("Author", "author"),
SelectField("Scan Status", "status", arrayOf("Any", "Complete", "Discontinued", "Hiatus", "Incomplete", "Ongoing")),
SelectField("Publish Status", "pstatus", arrayOf("Any", "Cancelled", "Complete", "Discontinued", "Hiatus", "Incomplete", "Ongoing", "Unfinished")),
SelectField("Type", "type", arrayOf("Any", "Doujinshi", "Manga", "Manhua", "Manhwa", "OEL", "One-shot")),
Sort(),
GenreList(getGenreList())
)
// [...document.querySelectorAll("label.triStateCheckBox input")].map(el => `Filter("${el.getAttribute('name')}", "${el.nextSibling.textContent.trim()}")`).join(',\n')
// http://mangasee.co/advanced-search/
private fun getGenreList() = listOf(
Genre("Action"),
Genre("Adult"),
Genre("Adventure"),
Genre("Comedy"),
Genre("Doujinshi"),
Genre("Drama"),
Genre("Ecchi"),
Genre("Fantasy"),
Genre("Gender Bender"),
Genre("Harem"),
Genre("Hentai"),
Genre("Historical"),
Genre("Horror"),
Genre("Josei"),
Genre("Lolicon"),
Genre("Martial Arts"),
Genre("Mature"),
Genre("Mecha"),
Genre("Mystery"),
Genre("Psychological"),
Genre("Romance"),
Genre("School Life"),
Genre("Sci-fi"),
Genre("Seinen"),
Genre("Shotacon"),
Genre("Shoujo"),
Genre("Shoujo Ai"),
Genre("Shounen"),
Genre("Shounen Ai"),
Genre("Slice of Life"),
Genre("Smut"),
Genre("Sports"),
Genre("Supernatural"),
Genre("Tragedy"),
Genre("Yaoi"),
Genre("Yuri")
)
} | apache-2.0 | 6d7d53998b224f9f40ec452b3bd719ac | 40.859438 | 171 | 0.596157 | 4.621048 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandlerSpec.kt | 1 | 16243 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.orca.time.fixedClock
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object CompleteStageHandlerSpec : SubjectSpek<CompleteStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
subject {
CompleteStageHandler(queue, repository, publisher, clock)
}
fun resetMocks() = reset(queue, repository, publisher)
setOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED).forEach { stageStatus ->
describe("when a stage completes with $stageStatus status") {
and("it is the last stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"), stageStatus)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual stageStatus
it.getEndTime() shouldEqual clock.millis()
})
}
it("completes the execution") {
verify(queue).push(CompleteExecution(
pipeline // execution is SUCCEEDED even if stage was FAILED_CONTINUE or SKIPPED
))
}
it("does not emit any commands") {
verify(queue, never()).push(any<RunTask>())
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageComplete> {
it.executionType shouldEqual pipeline.javaClass
it.executionId shouldEqual pipeline.id
it.stageId shouldEqual message.stageId
it.status shouldEqual stageStatus
})
}
}
and("there is a single downstream stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"), stageStatus)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual stageStatus
it.getEndTime() shouldEqual clock.millis()
})
}
it("runs the next stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.last().id
))
}
it("does not run any tasks") {
verify(queue, never()).push(any<RunTask>())
}
}
and("there are multiple downstream stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
stage {
refId = "3"
requisiteStageRefIds = setOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"), stageStatus)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the next stages") {
argumentCaptor<StartStage>().apply {
verify(queue, times(2)).push(capture())
allValues.map { it.stageId }.toSet() shouldEqual pipeline.stages[1..2].map { it.id }.toSet()
}
}
}
and("there are parallel stages still running") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
status = RUNNING
}
stage {
refId = "2"
type = singleTaskStage.type
status = RUNNING
}
}
val message = CompleteStage(pipeline.stageByRef("1"), stageStatus)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("still signals completion of the execution") {
it("completes the execution") {
verify(queue).push(CompleteExecution(
pipeline // execution is SUCCEEDED even if stage was FAILED_CONTINUE or SKIPPED
))
}
}
}
}
}
setOf(TERMINAL, CANCELED).forEach { status ->
describe("when a stage fails with $status status") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = singleTaskStage.type
}
stage {
refId = "2"
requisiteStageRefIds = listOf("1")
type = singleTaskStage.type
}
}
val message = CompleteStage(pipeline.stageByRef("1"), status)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage state") {
verify(repository).storeStage(check {
it.getStatus() shouldEqual status
it.getEndTime() shouldEqual clock.millis()
})
}
it("does not run any downstream stages") {
verify(queue, never()).push(isA<StartStage>())
}
it("fails the execution") {
verify(queue).push(CompleteExecution(
message.executionType,
message.executionId,
"foo"
))
}
it("runs the stage's cancellation routine") {
verify(queue).push(CancelStage(message))
}
it("publishes an event") {
verify(publisher).publishEvent(check<StageComplete> {
it.executionType shouldEqual pipeline.javaClass
it.executionId shouldEqual pipeline.id
it.stageId shouldEqual message.stageId
it.status shouldEqual status
})
}
}
}
describe("synthetic stages") {
context("when a synthetic stage completes successfully") {
context("before a main stage") {
context("that has tasks") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildSyntheticStages(this)
stageWithSyntheticBefore.buildTasks(this)
}
}
context("there are more before stages") {
val message = CompleteStage(pipeline.stageByRef("1<1"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the next synthetic stage") {
verify(queue).push(StartStage(pipeline.stageByRef("1<2")))
}
}
context("it is the last before stage") {
val message = CompleteStage(pipeline.stageByRef("1<2"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the parent stage's first task") {
verify(queue).push(StartTask(pipeline.stageByRef("1"), "1"))
}
}
}
context("that has no tasks") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBeforeAndNoTasks.type
stageWithSyntheticBeforeAndNoTasks.buildSyntheticStages(this)
stageWithSyntheticBeforeAndNoTasks.buildTasks(this)
}
}
context("it is the last before stage") {
val message = CompleteStage(pipeline.stageByRef("1<1"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("completes the stage") {
verify(queue).push(CompleteStage(
message.executionType,
message.executionId,
"foo",
pipeline.stageByRef("1").id,
SUCCEEDED
))
}
}
}
context("that has no tasks but does have after stages") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBeforeAndAfterAndNoTasks.type
stageWithSyntheticBeforeAndAfterAndNoTasks.buildSyntheticStages(this)
stageWithSyntheticBeforeAndAfterAndNoTasks.buildTasks(this)
}
}
context("it is the last before stage") {
val message = CompleteStage(pipeline.stageByRef("1<1"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("starts the first after stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stageByRef("1>1").id
))
}
}
}
}
context("after the main stage") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticAfter.type
stageWithSyntheticAfter.buildSyntheticStages(this)
stageWithSyntheticAfter.buildTasks(this)
}
}
context("there are more after stages") {
val message = CompleteStage(pipeline.stageByRef("1>1"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs the next synthetic stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.last().id
))
}
}
context("it is the last after stage") {
val message = CompleteStage(pipeline.stageByRef("1>2"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("signals the completion of the parent stage") {
verify(queue).push(CompleteStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.first().id,
SUCCEEDED
))
}
}
}
}
setOf(TERMINAL, CANCELED).forEach { status ->
context("when a synthetic stage ends with $status status") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
type = stageWithSyntheticBefore.type
stageWithSyntheticBefore.buildSyntheticStages(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1<1"), status)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
action("the handler receives a message") {
subject.handle(message)
}
afterGroup(::resetMocks)
it("rolls up to the parent stage") {
verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id))
}
it("runs the stage's cancel routine") {
verify(queue).push(CancelStage(message))
}
}
}
}
describe("branching stages") {
context("when one branch completes") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildSyntheticStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1=1"), SUCCEEDED)
beforeGroup {
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("waits for other branches to finish") {
verify(queue, never()).push(any())
}
}
context("when all branches are complete") {
val pipeline = pipeline {
application = "foo"
stage {
refId = "1"
name = "parallel"
type = stageWithParallelBranches.type
stageWithParallelBranches.buildSyntheticStages(this)
stageWithParallelBranches.buildTasks(this)
}
}
val message = CompleteStage(pipeline.stageByRef("1=1"), SUCCEEDED)
beforeGroup {
pipeline.stageByRef("1=2").status = SUCCEEDED
pipeline.stageByRef("1=3").status = SUCCEEDED
whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("runs any post-branch tasks") {
verify(queue).push(isA<StartTask>())
}
}
}
})
| apache-2.0 | 6ff2b991616c54a4ec0f21bf3557b5b6 | 28.640511 | 104 | 0.571692 | 5.194436 | false | false | false | false |
spennihana/HackerDesktop | src/main/kt/com/hnd/RequestServer.kt | 1 | 2556 | package com.hnd
import com.google.gson.Gson
import com.hnd.Handlers.getComments
import com.hnd.Handlers.getStories
import com.hnd.Handlers.reset
import com.hnd.util.Log
import spark.Filter
import spark.Request
import spark.Response
import spark.Spark
class RequestServer(val port: Int) {
fun genericHandler(request:Request, response:Response, h: (request:Request, response:Response) -> String): String {
Log.info("Handling Route: " + request.pathInfo())
return h(request,response)
}
fun registeRoute(route:String, h: (request:Request, response:Response) -> String) {
Spark.get(route, {req,res -> genericHandler(req,res,h)})
}
fun boot() {
Spark.port(port)
Spark.options("/*", {req, res ->
val accessControlReqHeaders = req.headers("Access-Control-Request-Headers")
if( accessControlReqHeaders!=null )
res.header("Access-Control-Allow-Headers", accessControlReqHeaders)
val accessControlRequestMethod = req.headers("Access-Control-Request-Method")
if (accessControlRequestMethod != null)
res.header("Access-Control-Allow-Methods", accessControlRequestMethod)
return@options "OK"
})
Spark.before(Filter { _, res ->
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Request-Method", "GET,POST")
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin")
res.type("application/json")
})
// custom routes
registeRoute("/stories/:story/:n", ::getStories)
registeRoute("/reset", ::reset)
Spark.post("/comments", {req,res -> genericHandler(req,res,::getComments)})
}
}
data class GetComments(val story:String, val pid:Int, val cids:String)
object Handlers {
fun getStory(story:String):String {
if( story=="jobs" ) return "job" // FIXME: this is really a display hack; make everything a job, and display does job -> jobs
return story
}
fun getStories(request:Request, response:Response):String {
return HackerDesktop._storyMap[getStory(request.params("story"))]!!.loadMore(request.params("n").toInt())
}
fun reset(request:Request, response:Response):String {
HackerDesktop.reset()
return ""
}
fun getComments(request:Request, response:Response):String {
val body = Gson().fromJson(request.body(), GetComments::class.java)
val story = getStory(body.story)
val cids = Gson().fromJson(body.cids, IntArray::class.java)
return HackerDesktop._storyMap[story]!!.getComments(body.pid, cids)
}
} | apache-2.0 | 5f08db9dd171c0fd77e3415544b02921 | 34.513889 | 131 | 0.705008 | 3.742313 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/view/ItemDecoration.kt | 1 | 1285 | package com.christian.view
import android.graphics.Rect
import android.os.Build
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.christian.util.ChristianUtil
/**
* author:Administrator on 2017/6/13 22:07
* email:[email protected]
*/
class ItemDecoration(private val left: Int = ChristianUtil.dpToPx(8), private val top: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ChristianUtil.dpToPx(8) else ChristianUtil.dpToPx(4), private val right: Int = ChristianUtil.dpToPx(8), private val bottom: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ChristianUtil.dpToPx(8) else ChristianUtil.dpToPx(4)) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect, view: View,
parent: RecyclerView, state: RecyclerView.State
) {
outRect.left = left
outRect.right = right
outRect.bottom = bottom
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0) outRect.top = top
// if (parent.getChildAdapterPosition(view) == Objects.requireNonNull(parent.getAdapter()).getItemCount() - 1)
// outRect.bottom = ChristianUtil.dpToPx(168);
}
} | gpl-3.0 | 8aa1a9e55910448a99fe061be147a53b | 46.481481 | 428 | 0.720531 | 4.041009 | false | false | false | false |
mcmacker4/PBR-Test | src/main/kotlin/net/upgaming/pbrengine/gameobject/Camera.kt | 1 | 3409 | package net.upgaming.pbrengine.gameobject
import net.upgaming.pbrengine.util.unaryMinus
import net.upgaming.pbrgame.PBRGame
import org.joml.Matrix3f
import org.joml.Matrix4f
import org.joml.Vector3f
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.system.MemoryUtil
import java.nio.FloatBuffer
class Camera(val position: Vector3f = Vector3f(), val rotation: Vector3f = Vector3f(), var fov: Float = 90f) {
private val vMatBuffer = MemoryUtil.memAllocFloat(16)
private val vMatUtBuffer = MemoryUtil.memAllocFloat(16)
private val pMatBuffer = MemoryUtil.memAllocFloat(16)
private val sensitivity = 0.002f
private val speed = 1f
fun update(delta: Float) {
val change = Vector3f()
if(PBRGame.isKeyDown(GLFW_KEY_W)) {
change.add(frontVector())
}
if(PBRGame.isKeyDown(GLFW_KEY_S)) {
change.add(backVector())
}
if(PBRGame.isKeyDown(GLFW_KEY_A)) {
change.add(leftVector())
}
if(PBRGame.isKeyDown(GLFW_KEY_D)) {
change.add(rightVector())
}
if(PBRGame.isKeyDown(GLFW_KEY_SPACE)) {
change.add(Vector3f(0f, 1f, 0f))
}
if(PBRGame.isKeyDown(GLFW_KEY_LEFT_SHIFT)) {
change.add(Vector3f(0f, -1f, 0f))
}
position.add(change.mul(delta * speed))
rotation.add(-PBRGame.getMouseDY().toFloat() * sensitivity, -PBRGame.getMouseDX().toFloat() * sensitivity, 0f)
}
private fun frontVector(): Vector3f {
val mat = Matrix3f().rotateY(rotation.y)
return Vector3f(0f, 0f, -1f).mul(mat).normalize()
}
private fun leftVector(): Vector3f {
val mat = Matrix3f().rotateY(rotation.y + (Math.PI / 2).toFloat())
return Vector3f(0f, 0f, -1f).mul(mat).normalize()
}
private fun rightVector(): Vector3f {
val mat = Matrix3f().rotateY(rotation.y + (-Math.PI / 2).toFloat())
return Vector3f(0f, 0f, -1f).mul(mat).normalize()
}
private fun backVector(): Vector3f {
return -frontVector()
}
fun getViewMatrix(): Matrix4f {
return getViewMatrixUntranslated().translate(-position)
}
fun getViewMatrixUntranslated(): Matrix4f {
return Matrix4f()
.rotate(-rotation.x, 1f, 0f, 0f)
.rotate(-rotation.y, 0f, 1f, 0f)
.rotate(-rotation.z, 0f, 0f, 1f)
}
fun getViewMatrixUntranslatedFB(): FloatBuffer {
vMatUtBuffer.clear()
val matrix = getViewMatrixUntranslated()
matrix.get(vMatUtBuffer)
return vMatUtBuffer
}
fun getViewMatrixFB(): FloatBuffer {
vMatBuffer.clear()
val matrix = getViewMatrix()
matrix.get(vMatBuffer)
return vMatBuffer
}
fun getProjectionMatrix(): Matrix4f {
return Matrix4f().setPerspective(
Math.toRadians(fov.toDouble()).toFloat(),
PBRGame.display.width / PBRGame.display.height.toFloat(),
0.1f, 1000f
)
}
fun getProjectionMatrixFB(): FloatBuffer {
pMatBuffer.clear()
val matrix = getProjectionMatrix()
matrix.get(pMatBuffer)
return pMatBuffer
}
fun delete() {
MemoryUtil.memFree(vMatBuffer)
MemoryUtil.memFree(pMatBuffer)
}
}
| apache-2.0 | 2e8b836a17ffbe40d705ac7148498135 | 28.643478 | 118 | 0.597536 | 3.709467 | false | false | false | false |
mcmacker4/PBR-Test | src/main/kotlin/net/upgaming/pbrgame/PrimaryLayer.kt | 1 | 2440 | package net.upgaming.pbrgame
import net.upgaming.pbrengine.gameobject.Camera
import net.upgaming.pbrengine.gameobject.Entity
import net.upgaming.pbrengine.graphics.GraphicsLayer
import net.upgaming.pbrengine.graphics.EntityRenderer
import net.upgaming.pbrengine.graphics.ShaderProgram
import net.upgaming.pbrengine.graphics.SkyboxRenderer
import net.upgaming.pbrengine.lights.PointLight
import net.upgaming.pbrengine.material.Material
import net.upgaming.pbrengine.models.Model
import net.upgaming.pbrengine.texture.TextureLoader
import net.upgaming.pbrengine.texture.TextureSkybox
import org.joml.Vector3f
class PrimaryLayer : GraphicsLayer {
val entityRenderer: EntityRenderer
val skyboxRenderer: SkyboxRenderer
val sphereModel: Model
val sphereEntities = arrayListOf<Entity>()
val camera: Camera
val skyboxTexYoko: TextureSkybox
val pointLights = arrayListOf<PointLight>()
init {
sphereModel = Model.OBJLoader.load("sphere")
for(x in 0 until 10) {
for(y in 0..1) {
val material = Material(Vector3f(1f, 0f, 0f), x / 10f, y.toFloat())
sphereEntities.add(Entity(
sphereModel,
material,
Vector3f(x.toFloat() - 4.5f, y.toFloat() - 0.5f, 0f),
scale = 0.5f
))
}
}
entityRenderer = EntityRenderer(ShaderProgram.load("simple"))
camera = Camera(Vector3f(0f, 0f, 3f))
skyboxTexYoko = TextureLoader.loadTextureSkybox("yokohama")
skyboxRenderer = SkyboxRenderer()
pointLights.add(PointLight(Vector3f(-4f, -4f, 10f), Vector3f(1f)))
pointLights.add(PointLight(Vector3f(-4f, 4f, 10f), Vector3f(1f)))
pointLights.add(PointLight(Vector3f(4f, 4f, 10f), Vector3f(1f)))
pointLights.add(PointLight(Vector3f(4f, -4f, 10f), Vector3f(1f)))
}
override fun update(delta: Float) {
camera.update(delta)
}
override fun render() {
//skyboxRenderer.render(camera, skyboxTexYoko)
entityRenderer.addPointLights(pointLights)
entityRenderer.pushAll(sphereEntities)
entityRenderer.draw(camera, skyboxTexYoko)
}
override fun cleanUp() {
camera.delete()
sphereEntities.forEach(Entity::delete)
}
} | apache-2.0 | e83ad983f2f6084d301ac758e93e69eb | 32.438356 | 83 | 0.643852 | 3.941842 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/beveled/BeveledBox.kt | 1 | 8026 | package net.dinkla.raytracer.objects.beveled
import net.dinkla.raytracer.math.BBox
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.math.Vector3D
import net.dinkla.raytracer.objects.*
import net.dinkla.raytracer.objects.compound.Compound
class BeveledBox(val p0: Point3D, val p1: Point3D, val rb: Double, isWiredFrame: Boolean) : Compound() {
init {
val top_front_edge = Instance(OpenCylinder(-(p1.x - p0.x - 2 * rb) / 2, (p1.x - p0.x - 2 * rb) / 2, rb)) // top front edge
top_front_edge.rotateZ(90.0)
top_front_edge.translate((p0.x + p1.x) / 2, p1.y - rb, p1.z - rb)
//top_front_edge.transform_texture(false);
objects.add(top_front_edge)
// top back (-ve z)
val top_back_edge = Instance(OpenCylinder(-(p1.x - p0.x - 2 * rb) / 2, (p1.x - p0.x - 2 * rb) / 2, rb)) // top back edge
top_back_edge.rotateZ(90.0)
top_back_edge.translate((p0.x + p1.x) / 2, p1.y - rb, p0.z + rb)
//top_back_edge->transform_texture(false);
objects.add(top_back_edge)
// top right (+ve x)
val top_right_edge = Instance(OpenCylinder(-(p1.z - p0.z - 2 * rb) / 2, (p1.z - p0.z - 2 * rb) / 2, rb)) // top right edge
top_right_edge.rotateX(90.0)
top_right_edge.translate(p1.x - rb, p1.y - rb, (p0.z + p1.z) / 2)
//top_right_edge->transform_texture(false);
objects.add(top_right_edge)
// top left (-ve x)
val top_left_edge = Instance(OpenCylinder(-(p1.z - p0.z - 2 * rb) / 2, (p1.z - p0.z - 2 * rb) / 2, rb)) // top left edge
top_left_edge.rotateX(90.0)
top_left_edge.translate(p0.x + rb, p1.y - rb, (p0.z + p1.z) / 2)
//top_left_edge->transform_texture(false);
objects.add(top_left_edge)
// bottom edges (-ve y)
// bottom front (+ve z)
val bottom_front_edge = Instance(OpenCylinder(-(p1.x - p0.x - 2 * rb) / 2, (p1.x - p0.x - 2 * rb) / 2, rb)) // bottom fromt edge
bottom_front_edge.rotateZ(90.0)
bottom_front_edge.translate((p0.x + p1.x) / 2, p0.y + rb, p1.z - rb)
//bottom_front_edge->transform_texture(false);
objects.add(bottom_front_edge)
// bottom back (-ve z)
val bottom_back_edge = Instance(OpenCylinder(-(p1.x - p0.x - 2 * rb) / 2, (p1.x - p0.x - 2 * rb) / 2, rb)) // bottom back edge
bottom_back_edge.rotateZ(90.0)
bottom_back_edge.translate((p0.x + p1.x) / 2, p0.y + rb, p0.z + rb)
//bottom_back_edge->transform_texture(false);
objects.add(bottom_back_edge)
// bottom right (-ve x, -ve y)
val bottom_right_edge = Instance(OpenCylinder(-(p1.z - p0.z - 2 * rb) / 2, (p1.z - p0.z - 2 * rb) / 2, rb)) // bottom right edge
bottom_right_edge.rotateX(90.0)
bottom_right_edge.translate(p1.x - rb, p0.y + rb, (p0.z + p1.z) / 2)
//bottom_right_edge->transform_texture(false);
objects.add(bottom_right_edge)
// bottom left (-ve x, -ve y)
val bottom_left_edge = Instance(OpenCylinder(-(p1.z - p0.z - 2 * rb) / 2, (p1.z - p0.z - 2 * rb) / 2, rb)) // bottom left edge
bottom_left_edge.rotateX(90.0)
bottom_left_edge.translate(p0.x + rb, p0.y + rb, (p0.z + p1.z) / 2)
//bottom_left_edge->transform_texture(false);
objects.add(bottom_left_edge)
// vertical edges
// vertical right front (+ve x, +ve z)
val vertical_right_front_edge = Instance(OpenCylinder(p0.y + rb, p1.y - rb, rb))
vertical_right_front_edge.translate(p1.x - rb, 0.0, p1.z - rb)
//vertical_right_front_edge->transform_texture(false);
objects.add(vertical_right_front_edge)
// vertical left front (-ve x, +ve z)
val vertical_left_front_edge = Instance(OpenCylinder(p0.y + rb, p1.y - rb, rb))
vertical_left_front_edge.translate(p0.x + rb, 0.0, p1.z - rb)
//vertical_left_front_edge->transform_texture(false);
objects.add(vertical_left_front_edge)
// vertical left back (-ve x, -ve z)
val vertical_left_back_edge = Instance(OpenCylinder(p0.y + rb, p1.y - rb, rb))
vertical_left_back_edge.translate(p0.x + rb, 0.0, p0.z + rb)
//vertical_left_back_edge->transform_texture(false);
objects.add(vertical_left_back_edge)
// vertical right back (+ve x, -ve z)
val vertical_right_back_edge = Instance(OpenCylinder(p0.y + rb, p1.y - rb, rb))
vertical_right_back_edge.translate(p1.x - rb, 0.0, p0.z + rb)
//vertical_right_back_edge->transform_texture(false);
objects.add(vertical_right_back_edge)
// corner spheres
// top right front
val top_right_front_corner = Sphere(Point3D(p1.x - rb, p1.y - rb, p1.z - rb), rb)
objects.add(top_right_front_corner)
// top left front (-ve x)
val top_left_front_corner = Sphere(Point3D(p0.x + rb, p1.y - rb, p1.z - rb), rb)
objects.add(top_left_front_corner)
// top left back
val top_left_back_corner = Sphere(Point3D(p0.x + rb, p1.y - rb, p0.z + rb), rb)
objects.add(top_left_back_corner)
// top right back
val top_right_back_corner = Sphere(Point3D(p1.x - rb, p1.y - rb, p0.z + rb), rb)
objects.add(top_right_back_corner)
// bottom right front
val bottom_right_front_corner = Sphere(Point3D(p1.x - rb, p0.y + rb, p1.z - rb), rb)
objects.add(bottom_right_front_corner)
// bottom left front
val bottom_left_front_corner = Sphere(Point3D(p0.x + rb, p0.y + rb, p1.z - rb), rb)
objects.add(bottom_left_front_corner)
// bottom left back
val bottom_left_back_corner = Sphere(Point3D(p0.x + rb, p0.y + rb, p0.z + rb), rb)
objects.add(bottom_left_back_corner)
// bottom right back
val bottom_right_back_corner = Sphere(Point3D(p1.x - rb, p0.y + rb, p0.z + rb), rb)
objects.add(bottom_right_back_corner)
// the faces
// bottom face: -ve y
if (!isWiredFrame) {
val bottom_face = Rectangle(Point3D(p0.x + rb, p0.y, p0.z + rb),
Vector3D(0.0, 0.0, p1.z - rb - (p0.z + rb)),
Vector3D(p1.x - rb - (p0.x + rb), 0.0, 0.0),
Normal(0.0, -1.0, 0.0))
objects.add(bottom_face)
// bottom face: +ve y
val top_face = Rectangle(Point3D(p0.x + rb, p1.y, p0.z + rb),
Vector3D(0.0, 0.0, p1.z - rb - (p0.z + rb)),
Vector3D(p1.x - rb - (p0.x + rb), 0.0, 0.0),
Normal(0.0, 1.0, 0.0))
objects.add(top_face)
// back face: -ve z
val back_face = Rectangle(Point3D(p0.x + rb, p0.y + rb, p0.z),
Vector3D(p1.x - rb - (p0.x + rb), 0.0, 0.0),
Vector3D(0.0, p1.y - rb - (p0.y + rb), 0.0),
Normal(0.0, 0.0, -1.0))
objects.add(back_face)
// front face: +ve z
val front_face = Rectangle(Point3D(p0.x + rb, p0.y + rb, p1.z),
Vector3D(p1.x - rb - (p0.x + rb), 0.0, 0.0),
Vector3D(0.0, p1.y - rb - (p0.y + rb), 0.0),
Normal(0.0, 0.0, 1.0))
objects.add(front_face)
// left face: -ve x
val left_face = Rectangle(Point3D(p0.x, p0.y + rb, p0.z + rb),
Vector3D(0.0, 0.0, p1.z - rb - (p0.z + rb)),
Vector3D(0.0, p1.y - rb - (p0.y + rb), 0.0),
Normal(-1.0, 0.0, 0.0))
objects.add(left_face)
// right face: +ve x
val right_face = Rectangle(Point3D(p1.x, p0.y + rb, p0.z + rb),
Vector3D(0.0, 0.0, p1.z - rb - (p0.z + rb)),
Vector3D(0.0, p1.y - rb - (p0.y + rb), 0.0),
Normal(1.0, 0.0, 0.0))
objects.add(right_face)
}
}
}
| apache-2.0 | 49f9a164f09667198aecd04ae0b51dc2 | 36.330233 | 139 | 0.537379 | 2.812193 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/scouts/src/main/java/com/supercilex/robotscouter/feature/scouts/viewholder/EditTextViewHolder.kt | 1 | 1598 | package com.supercilex.robotscouter.feature.scouts.viewholder
import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import com.supercilex.robotscouter.core.data.model.update
import com.supercilex.robotscouter.core.model.Metric
import com.supercilex.robotscouter.core.ui.hideKeyboard
import com.supercilex.robotscouter.shared.scouting.MetricViewHolderBase
import kotlinx.android.synthetic.main.scout_notes.*
internal class EditTextViewHolder(
itemView: View
) : MetricViewHolderBase<Metric.Text, String?>(itemView),
View.OnFocusChangeListener {
init {
name.onFocusChangeListener = this
}
/**
* Note: this implementation DOES NOT call super
*/
// We set the text to the value instead of the name because the name goes in the hint
@SuppressLint("MissingSuperCall")
public override fun bind() {
textLayout.isHintAnimationEnabled = false
name.text = metric.value
textLayout.hint = metric.name
textLayout.isHintAnimationEnabled = true
if (
Build.VERSION.SDK_INT >= 26 &&
metric.name.contains(View.AUTOFILL_HINT_NAME, true)
) {
itemView.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_AUTO
name.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
name.setAutofillHints(View.AUTOFILL_HINT_NAME)
}
}
override fun onFocusChange(v: View, hasFocus: Boolean) {
if (!hasFocus) {
metric.update(name.text.toString())
name.hideKeyboard()
}
}
}
| gpl-3.0 | ec28bd1b42ea89df4fae77015551b3e1 | 33 | 89 | 0.692115 | 4.488764 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/language/folding/MdFoldingVisitor.kt | 1 | 12752 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language.folding
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.vladsch.md.nav.language.api.MdFoldingBuilderProvider
import com.vladsch.md.nav.language.api.MdFoldingVisitorHandler
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.MdNodeVisitor
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdVisitHandler
import com.vladsch.md.nav.psi.util.MdVisitor
import com.vladsch.md.nav.util.*
import com.vladsch.md.nav.vcs.GitHubLinkResolver
import com.vladsch.plugin.util.image.ImageUtils
import com.vladsch.plugin.util.maxLimit
import java.util.*
class MdFoldingVisitor(
private val root: PsiElement,
document: Document,
private val descriptors: ArrayList<FoldingDescriptor>,
quick: Boolean,
private val defaultPlaceHolderText: String
) : MdFoldingVisitorHandler {
private val myResolver = GitHubLinkResolver(root)
private val myHeadingRanges = HashMap<MdHeaderElement, TextRange>()
private val myOpenHeadingRanges = Array<TextRange?>(6) { null }
private val myOpenHeadings = Array<MdHeaderElement?>(6) { null }
private val myRootText = document.charsSequence
private val myVisitor: MdNodeVisitor = MdNodeVisitor()
init {
addHandlers(
// // does not do anything in basic
// MdVisitHandler(MdSimToc::class.java, this::fold),
MdVisitHandler(MdJekyllFrontMatterBlock::class.java, this::fold),
MdVisitHandler(MdUnorderedListItem::class.java, this::fold),
MdVisitHandler(MdOrderedListItem::class.java, this::fold),
MdVisitHandler(MdAtxHeader::class.java, this::fold),
MdVisitHandler(MdSetextHeader::class.java, this::fold),
MdVisitHandler(MdBlockComment::class.java, this::fold),
MdVisitHandler(MdInlineComment::class.java, this::fold),
MdVisitHandler(MdVerbatim::class.java, this::fold)
)
if (!quick) {
addHandlers(
MdVisitHandler(MdAutoLinkRef::class.java, this::fold),
MdVisitHandler(MdImageLinkRef::class.java, this::fold),
MdVisitHandler(MdJekyllIncludeLinkRef::class.java, this::fold),
MdVisitHandler(MdLinkRef::class.java, this::fold),
MdVisitHandler(MdReferenceLinkRef::class.java, this::fold),
MdVisitHandler(MdWikiLinkRef::class.java, this::fold)
)
}
// allow extensions to add theirs
MdFoldingBuilderProvider.EXTENSIONS.value.forEach { it.extendFoldingHandler(this, quick) }
}
override fun addHandlers(handlers: MutableCollection<MdVisitHandler<PsiElement>>): MdNodeVisitor = myVisitor.addHandlers(handlers)
override fun addHandlers(vararg handlers: MdVisitHandler<*>): MdNodeVisitor = myVisitor.addHandlers(handlers)
override fun addHandlers(vararg handlers: Array<out MdVisitHandler<PsiElement>>): MdNodeVisitor = myVisitor.addHandlers(*handlers)
override fun addHandler(handler: MdVisitHandler<*>): MdNodeVisitor = myVisitor.addHandler(handler)
override fun visitNodeOnly(element: PsiElement): Unit = myVisitor.visitNodeOnly(element)
override fun visit(element: PsiElement): Unit = myVisitor.visit(element)
override fun visitChildren(element: PsiElement): Unit = myVisitor.visitChildren(element)
override fun getRootText(): CharSequence = myRootText
override fun getDefaultPlaceHolderText(): String = defaultPlaceHolderText
override fun addDescriptor(descriptor: FoldingDescriptor): Boolean = descriptors.add(descriptor)
override fun getFoldingHandler(klass: Class<out PsiElement>): MdVisitor<PsiElement>? = myVisitor.getAction(klass)
override fun <T : PsiElement> delegateFoldingHandler(forClass: Class<T>, toClass: Class<out T>): Boolean {
val handler = myVisitor.getAction(forClass) ?: return false
myVisitor.addHandler(MdVisitHandler(toClass) { handler.visit(it) })
return true
}
fun buildFoldingRegions(root: PsiElement) {
myVisitor.visit(root)
// close any open headings at end of file
closeOpenHeadings()
}
private fun fold(element: MdVerbatim) {
val content = element.contentElement ?: return
val range = content.textRange
if (!range.isEmpty) {
addDescriptor(object : FoldingDescriptor(element.node, TextRange(if (range.startOffset > 0) range.startOffset - 1 else range.startOffset, range.endOffset), null) {
override fun getPlaceholderText(): String? {
return null
}
})
}
}
private fun fold(element: MdLinkRefElement) {
if (!element.textRange.isEmpty) {
val linkRef = MdPsiImplUtil.getLinkRef(element.parent)
if (linkRef != null) {
val filePath = linkRef.filePath
if (ImageUtils.isPossiblyEncodedImage(filePath)) {
val collapsedText = "data:image/$defaultPlaceHolderText"
addDescriptor(object : FoldingDescriptor(element, element.textRange) {
override fun getPlaceholderText(): String? {
return collapsedText
}
})
} else {
if ((linkRef.isURL || linkRef.isFileURI) && !myResolver.isExternalUnchecked(linkRef)) {
val reference = element.reference
if (reference != null) {
val targetElement = reference.resolve()
if (targetElement != null) {
// get the repo relative if available, if not then page relative
var collapsedForm = myResolver.resolve(linkRef, Want.invoke(Local.ABS, Remote.ABS, Links.NONE), null)
if (collapsedForm == null) {
collapsedForm = myResolver.resolve(linkRef, Want.invoke(Local.REL, Remote.REL, Links.NONE), null)
}
if (collapsedForm != null && collapsedForm is LinkRef) {
val collapsedText = collapsedForm.filePath
addDescriptor(object : FoldingDescriptor(element, element.textRange) {
override fun getPlaceholderText(): String? {
return collapsedText
}
})
}
}
}
}
}
}
visitChildren(element)
}
}
private fun trimLastBlankLine(text: CharSequence, range: TextRange): TextRange {
if (range.endOffset > 1 && range.endOffset <= text.length && text[range.endOffset - 1] == '\n') {
val lastEOL = range.endOffset - 1
val prevEOL = text.lastIndexOf('\n', lastEOL - 1)
if (prevEOL >= range.startOffset && prevEOL < lastEOL) {
if (text.subSequence(prevEOL + 1, lastEOL).isBlank()) {
return TextRange(range.startOffset, prevEOL)
}
}
}
return range
}
private fun fold(element: MdHeaderElement) {
val headingRange = element.textRange
val headingIndex = element.headerLevel - 1
// extend range of all headings with lower level and close all equal or lower levels
for (i in 0 until 6) {
val openHeadingRange = myOpenHeadingRanges[i]
val openHeading = myOpenHeadings[i]
if (i < headingIndex) {
// extend its range to include this heading
if (openHeadingRange != null && openHeading != null) {
val textRange = openHeadingRange.union(headingRange)
myOpenHeadingRanges[i] = textRange
}
} else {
// end it before our start
if (openHeadingRange != null && openHeading != null) {
updateHeadingRanges(openHeading, openHeadingRange, headingRange.startOffset)
}
// close this level
myOpenHeadingRanges[i] = null
myOpenHeadings[i] = null
if (i == headingIndex) {
// this is now this heading's spot
myOpenHeadings[i] = element
myOpenHeadingRanges[i] = headingRange
if (element is MdSetextHeader) {
// need to use the end of text node
val headingTextRange = element.headerTextElement?.textRange
if (headingTextRange != null) {
myOpenHeadingRanges[headingIndex] = headingTextRange
}
} else {
myOpenHeadingRanges[headingIndex] = TextRange(headingRange.endOffset - 1, headingRange.endOffset - 1)
}
}
}
}
visitChildren(element)
}
private fun updateHeadingRanges(openHeading: MdHeaderElement, openHeadingRange: TextRange, endOffset: Int) {
val finalOpenHeadingRange = trimLastBlankLine(myRootText, TextRange(openHeadingRange.startOffset, endOffset))
if (!finalOpenHeadingRange.isEmpty && myRootText.subSequence(finalOpenHeadingRange.startOffset, finalOpenHeadingRange.endOffset).contains('\n')) {
myHeadingRanges[openHeading] = finalOpenHeadingRange
}
}
private fun closeOpenHeadings() {
val endOffset = root.textRange.endOffset
for (i in 0 until 6) {
val openHeadingRange = myOpenHeadingRanges[i]
val openHeading = myOpenHeadings[i]
if (openHeadingRange != null && openHeading != null) {
// diagnostic/4985
updateHeadingRanges(openHeading, openHeadingRange, endOffset.maxLimit(myRootText.length))
}
}
for (heading in myHeadingRanges.keys) {
val range = myHeadingRanges[heading]
if (range != null && !range.isEmpty) {
addDescriptor(object : FoldingDescriptor(heading.node, range, null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
}
}
}
private fun fold(element: MdJekyllFrontMatterBlock) {
val range = element.textRange
if (!range.isEmpty && range.startOffset + 3 < range.endOffset) {
val text = element.text
val lastEOL = (text as String).lastIndexOf("\n", text.length - 1) + 1
addDescriptor(object : FoldingDescriptor(element.node, TextRange(range.startOffset + 3, range.startOffset + lastEOL), null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
visitChildren(element)
}
}
private fun fold(element: MdListItem) {
val firstLineEnd = element.text.indexOf("\n")
if (firstLineEnd >= 0) {
val textRange = element.textRange
val range = TextRange.create(textRange.startOffset + firstLineEnd, textRange.endOffset - 1)
if (!range.isEmpty) {
addDescriptor(object : FoldingDescriptor(element.node, TextRange(range.startOffset, range.endOffset), null) {
override fun getPlaceholderText(): String? {
return defaultPlaceHolderText
}
})
}
}
visitChildren(element)
}
private fun fold(comment: MdComment) {
val commentText = comment.commentTextNode ?: return
var text = commentText.text
val pos = text.indexOf('\n')
if (pos > 0) {
text = text.substring(0, pos).trim() + defaultPlaceHolderText
addDescriptor(object : FoldingDescriptor(comment.node, comment.node.textRange, null) {
override fun getPlaceholderText(): String? {
return text
}
})
}
}
}
| apache-2.0 | 3846fa9b33a3d283cfa5bcc39df3abf1 | 44.380783 | 177 | 0.597867 | 5.000784 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/extension/util/ExtensionInstallActivity.kt | 2 | 1832 | package eu.kanade.tachiyomi.extension.util
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.util.toast
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/**
* Activity used to install extensions, because we can only receive the result of the installation
* with [startActivityForResult], which we need to update the UI.
*/
class ExtensionInstallActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE)
.setDataAndType(intent.data, intent.type)
.putExtra(Intent.EXTRA_RETURN_RESULT, true)
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
try {
startActivityForResult(installIntent, INSTALL_REQUEST_CODE)
} catch (error: Exception) {
// Either install package can't be found (probably bots) or there's a security exception
// with the download manager. Nothing we can workaround.
toast(error.message)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == INSTALL_REQUEST_CODE) {
checkInstallationResult(resultCode)
}
finish()
}
private fun checkInstallationResult(resultCode: Int) {
val downloadId = intent.extras.getLong(ExtensionInstaller.EXTRA_DOWNLOAD_ID)
val success = resultCode == RESULT_OK
val extensionManager = Injekt.get<ExtensionManager>()
extensionManager.setInstallationResult(downloadId, success)
}
private companion object {
const val INSTALL_REQUEST_CODE = 500
}
}
| apache-2.0 | 86f30f2197797f7652ee069e85155419 | 34.230769 | 100 | 0.692686 | 4.697436 | false | false | false | false |
http4k/http4k | http4k-serverless/lambda/integration-test/src/test/kotlin/org/http4k/serverless/lambda/LambdaHttpClientTest.kt | 1 | 3151 | package org.http4k.serverless.lambda
import org.http4k.aws.awsCliUserProfiles
import org.http4k.aws.awsClientFor
import org.http4k.client.HttpClientContract
import org.http4k.core.then
import org.http4k.serverless.lambda.testing.NoOpServerConfig
import org.http4k.serverless.lambda.testing.client.ApiGatewayV1LambdaClient
import org.http4k.serverless.lambda.testing.client.ApiGatewayV2LambdaClient
import org.http4k.serverless.lambda.testing.client.ApplicationLoadBalancerLambdaClient
import org.http4k.serverless.lambda.testing.client.InvocationLambdaClient
import org.http4k.serverless.lambda.testing.client.LambdaHttpClient
import org.http4k.serverless.lambda.testing.setup.DeployServerAsLambdaForClientContract.functionName
import org.http4k.serverless.lambda.testing.setup.aws.lambda.Function
import org.http4k.serverless.lambda.testing.setup.aws.lambda.LambdaIntegrationType
import org.http4k.serverless.lambda.testing.setup.aws.lambda.LambdaIntegrationType.ApiGatewayV1
import org.http4k.serverless.lambda.testing.setup.aws.lambda.LambdaIntegrationType.ApiGatewayV2
import org.http4k.serverless.lambda.testing.setup.aws.lambda.LambdaIntegrationType.ApplicationLoadBalancer
import org.http4k.serverless.lambda.testing.setup.aws.lambda.LambdaIntegrationType.Invocation
import org.http4k.serverless.lambda.testing.setup.aws.lambda.Region
import org.junit.jupiter.api.Assumptions.assumeTrue
import org.junit.jupiter.api.Disabled
abstract class LambdaHttpClientTest(type: LambdaIntegrationType,
clientFn: (Function, Region) -> LambdaHttpClient
) :
HttpClientContract({ NoOpServerConfig },
clientFn(functionName(type), Region(awsCliUserProfiles().profile("http4k-integration-test").region))
.then(awsCliUserProfiles().profile("http4k-integration-test").awsClientFor("lambda"))) {
override fun `handles response with custom status message`() = unsupportedFeature()
override fun `connection refused are converted into 503`() = unsupportedFeature()
override fun `unknown host are converted into 503`() = unsupportedFeature()
override fun `send binary data`() = unsupportedFeature()
}
class LambdaV1HttpClientTest : LambdaHttpClientTest(ApiGatewayV1, ::ApiGatewayV1LambdaClient) {
override fun `can send multiple headers with same name`() = unsupportedFeature()
override fun `can receive multiple headers with same name`() = unsupportedFeature()
override fun `can receive multiple cookies`() = unsupportedFeature()
}
class LambdaV2HttpClientTest : LambdaHttpClientTest(ApiGatewayV2, ::ApiGatewayV2LambdaClient)
class LambdaAlbHttpClientTest : LambdaHttpClientTest(ApplicationLoadBalancer, ::ApplicationLoadBalancerLambdaClient) {
override fun `can send multiple headers with same name`() = unsupportedFeature()
override fun `can receive multiple headers with same name`() = unsupportedFeature()
override fun `can receive multiple cookies`() = unsupportedFeature()
}
@Disabled
class InvocationLambdaClientTest : LambdaHttpClientTest(Invocation, ::InvocationLambdaClient)
private fun unsupportedFeature() = assumeTrue(false, "Unsupported feature")
| apache-2.0 | 6af899152426d66f68711044beab99d3 | 57.351852 | 118 | 0.814979 | 4.19016 | false | true | false | false |
milos85vasic/Dispatcher | Tryout/src/main/kotlin/net/milosvasic/try/dispatcher/Main.kt | 1 | 3652 | package net.milosvasic.`try`.dispatcher
import net.milosvasic.dispatcher.Dispatcher
import net.milosvasic.dispatcher.response.Response
import net.milosvasic.dispatcher.response.ResponseAction
import net.milosvasic.dispatcher.response.ResponseFactory
import net.milosvasic.dispatcher.route.*
import net.milosvasic.logger.ConsoleLogger
import java.util.*
private class TryDispatcher
fun main(args: Array<String>) {
val LOG_TAG = TryDispatcher::class
val logger = ConsoleLogger()
val factory = object : ResponseFactory {
override fun getResponse(params: HashMap<String, String>): Response {
return Response("Executed ${Date()} [ ${params.size} ]")
}
}
val action = object : ResponseAction {
override fun onAction() {
logger.v(LOG_TAG, "Action taken!")
}
}
val routeCatalogs = Route.Builder()
.addRouteElement(StaticRouteElement("catalogs"))
.addRouteElement(DynamicRouteElement("catalog"))
.build()
val routeUserRepos = Route.Builder()
.addRouteElement(StaticRouteElement("users"))
.addRouteElement(DynamicRouteElement("username"))
.addRouteElement(StaticRouteElement("repositories"))
.build()
val routeAllRepos = Route.Builder()
.addRouteElement(StaticRouteElement("repositories"))
.build()
val routeAllUsers = Route.Builder()
.addRouteElement(StaticRouteElement("users"))
.build()
val dispatcher = Dispatcher("Dispatcher_Tryout", 2507)
dispatcher.registerRoute(routeUserRepos, factory)
dispatcher.registerRoute(routeAllRepos, factory)
dispatcher.registerRoute(routeAllUsers, factory)
dispatcher.registerRoute(routeAllUsers, action) // We registered action for user route too!
dispatcher.registerRoute(routeCatalogs, factory)
try {
dispatcher.start()
} catch (e: Exception) {
logger.e(LOG_TAG, "Error: " + e)
}
// Register route after we started dispatcher
val routeStop = Route.Builder().addRouteElement(StaticRouteElement("stop")).build()
val stop = object : ResponseAction {
override fun onAction() {
try {
dispatcher.stop()
} catch (e: Exception) {
logger.e(LOG_TAG, "Error: " + e)
}
}
}
dispatcher.registerRoute(routeStop, object : ResponseFactory {
override fun getResponse(params: HashMap<String, String>): Response {
return Response("<h1>Dispatcher stopped</h1>")
}
})
dispatcher.registerRoute(routeStop, stop)
val accountsParams = "accounts"
val userParam = "user"
val attributesParam = "attributes"
val operationParam = "operation"
val routeAccounts = Route.Builder()
.addRouteElement(StaticRouteElement(accountsParams))
.addRouteElement(DynamicRouteElement(userParam))
.addRouteElement(StaticRouteElement(attributesParam))
.addRouteElement(DynamicRouteElement(operationParam))
.build()
val factoryAccounts = object : ResponseFactory {
override fun getResponse(params: HashMap<String, String>): Response {
val builder = StringBuilder("<h1>We have parameters:</h1>")
builder.append("<ul>")
params.forEach {
element, value ->
builder.append("<li>$element -> $value</li>")
}
builder.append("</ul>")
return Response(builder.toString())
}
}
dispatcher.registerRoute(routeAccounts, factoryAccounts)
}
| apache-2.0 | f6c9b462eee97580052c7ad2a4091723 | 33.45283 | 95 | 0.645126 | 4.634518 | false | false | false | false |
msebire/intellij-community | plugins/gradle/java/src/execution/test/runner/TestGradleConfigurationProducerUtil.kt | 1 | 4023 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.test.runner
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import org.jetbrains.plugins.gradle.execution.GradleRunnerUtil
import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestRunConfigurationProducer.findTestsTaskToRun
import java.util.*
fun ExternalSystemTaskExecutionSettings.applyTestConfiguration(
project: Project,
testTasksToRun: List<Map<String, List<String>>>,
vararg containingClasses: PsiClass,
createFilter: (PsiClass) -> String
): Boolean {
return applyTestConfiguration(project, containingClasses.toList(), { it }, { it, _ -> createFilter(it) }) { source ->
testTasksToRun.mapNotNull { it[source.path] }
}
}
fun ExternalSystemTaskExecutionSettings.applyTestConfiguration(
project: Project,
vararg containingClasses: PsiClass,
createFilter: (PsiClass) -> String
): Boolean {
return applyTestConfiguration(project, containingClasses.toList(), { it }) { it, _ ->
createFilter(it)
}
}
fun <T> ExternalSystemTaskExecutionSettings.applyTestConfiguration(
project: Project,
tests: Iterable<T>,
findPsiClass: (T) -> PsiClass?,
createFilter: (PsiClass, T) -> String): Boolean {
return applyTestConfiguration(project, tests, findPsiClass, createFilter) { source ->
listOf(findTestsTaskToRun(source, project))
}
}
fun <T> ExternalSystemTaskExecutionSettings.applyTestConfiguration(
project: Project,
tests: Iterable<T>,
findPsiClass: (T) -> PsiClass?,
createFilter: (PsiClass, T) -> String,
getTestsTaskToRun: (VirtualFile) -> List<List<String>>
): Boolean {
val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
val testRunConfigurations = LinkedHashMap<String, Pair<VirtualFile, MutableList<String>>>()
for (test in tests) {
val psiClass = findPsiClass(test) ?: return false
val psiFile = psiClass.containingFile ?: return false
val virtualFile = psiFile.virtualFile
val module = projectFileIndex.getModuleForFile(virtualFile) ?: return false
externalProjectPath = GradleRunnerUtil.resolveProjectPath(module) ?: return false
if (!GradleRunnerUtil.isGradleModule(module)) return false
val (_, arguments) = testRunConfigurations.getOrPut(module.name) { Pair(virtualFile, ArrayList()) }
arguments.add(createFilter(psiClass, test))
}
val taskSettings = ArrayList<Pair<String, List<String>>>()
val unorderedParameters = ArrayList<String>()
for ((source, arguments) in testRunConfigurations.values) {
for (tasks in getTestsTaskToRun(source)) {
if (tasks.isEmpty()) continue
for (task in tasks.dropLast(1)) {
taskSettings.add(task to emptyList())
}
val last = tasks.last()
taskSettings.add(last to arguments)
}
}
if (testRunConfigurations.size > 1) {
unorderedParameters.add("--continue")
}
val hasTasksAfterTaskWithArguments = taskSettings.dropWhile { it.second.isEmpty() }.size > 1
if (hasTasksAfterTaskWithArguments) {
val joiner = StringJoiner(" ")
for ((task, arguments) in taskSettings) {
joiner.add(task)
for (argument in arguments) {
joiner.add(argument)
}
}
for (argument in unorderedParameters) {
joiner.add(argument)
}
taskNames = emptyList()
scriptParameters = joiner.toString()
}
else {
val arguments = taskSettings.lastOrNull()?.second ?: emptyList()
val joiner = StringJoiner(" ")
for (argument in arguments) {
joiner.add(argument)
}
for (argument in unorderedParameters) {
joiner.add(argument)
}
taskNames = taskSettings.map { it.first }
scriptParameters = joiner.toString()
}
return true
}
| apache-2.0 | ad45a7b011c45c6485d2f2aa92fc9842 | 36.25 | 140 | 0.732041 | 4.391921 | false | true | false | false |
msebire/intellij-community | platform/lang-impl/src/com/intellij/internal/retype/RetypeSession.kt | 1 | 23014 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.retype
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.CodeInsightWorkspaceSettings
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.LiveTemplateLookupElement
import com.intellij.diagnostic.ThreadDumper
import com.intellij.ide.DataManager
import com.intellij.ide.IdeEventQueue
import com.intellij.internal.performance.LatencyDistributionRecordKey
import com.intellij.internal.performance.TypingLatencyReportDialog
import com.intellij.internal.performance.currentLatencyRecordKey
import com.intellij.internal.performance.latencyRecorderProperties
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.actionSystem.LatencyRecorder
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.playback.commands.ActionCommand
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.LightColors
import com.intellij.util.Alarm
import org.intellij.lang.annotations.Language
import java.awt.event.KeyEvent
import java.io.File
import java.util.*
fun String.toReadable() = replace(" ", "<Space>").replace("\n", "<Enter>").replace("\t", "<Tab>")
class RetypeLog {
private val log = arrayListOf<String>()
private var currentTyping: String? = null
private var currentCompletion: String? = null
var typedChars = 0
private set
var completedChars = 0
private set
fun recordTyping(c: Char) {
if (currentTyping == null) {
flushCompletion()
currentTyping = ""
}
currentTyping += c.toString().toReadable()
typedChars++
}
fun recordCompletion(c: Char) {
if (currentCompletion == null) {
flushTyping()
currentCompletion = ""
}
currentCompletion += c.toString().toReadable()
completedChars++
}
fun recordDesync(message: String) {
flush()
log.add("Desync: $message")
}
fun flush() {
flushTyping()
flushCompletion()
}
private fun flushTyping() {
if (currentTyping != null) {
log.add("Type: $currentTyping")
currentTyping = null
}
}
private fun flushCompletion() {
if (currentCompletion != null) {
log.add("Complete: $currentCompletion")
currentCompletion = null
}
}
fun printToStdout() {
for (s in log) {
println(s)
}
}
}
class RetypeSession(
private val project: Project,
private val editor: EditorImpl,
private val delayMillis: Int,
private val scriptBuilder: StringBuilder?,
private val threadDumpDelay: Int,
private val threadDumps: MutableList<String> = mutableListOf(),
private val filesForIndexCount: Int = -1,
private val restoreText: Boolean = !ApplicationManager.getApplication().isUnitTestMode
) : Disposable {
private val document = editor.document
// -- Alarms
private val threadDumpAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this)
private val originalText = document.text
private var pos = 0
private val endPos: Int
private val tailLength: Int
private val log = RetypeLog()
private val oldSelectAutopopup = CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS
private val oldAddUnambiguous = CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY
private val oldOptimize = CodeInsightWorkspaceSettings.getInstance(project).optimizeImportsOnTheFly
var startNextCallback: (() -> Unit)? = null
private val disposeLock = Any()
private var typedRightBefore = false
private var skipLookupSuggestion = false
private var textBeforeLookupSelection: String? = null
@Volatile
private var waitingForTimerInvokeLater: Boolean = false
private var lastTimerTick = -1L
private var threadPoolTimerLag = 0L
private var totalTimerLag = 0L
// This stack will contain autocompletion elements
// E.g. "}", "]", "*/", "* @return"
private val completionStack = ArrayDeque<String>()
private var stopInterfereFileChanger = false
var retypePaused: Boolean = false
private val timerThread = Thread(::runLoop, "RetypeSession loop")
private var stopTimer = false
init {
if (editor.selectionModel.hasSelection()) {
pos = editor.selectionModel.selectionStart
endPos = editor.selectionModel.selectionEnd
}
else {
pos = editor.caretModel.offset
endPos = document.textLength
}
tailLength = document.textLength - endPos
}
fun start() {
editor.putUserData(RETYPE_SESSION_KEY, this)
val vFile = FileDocumentManager.getInstance().getFile(document)
val keyName = "${vFile?.name ?: "Unknown file"} (${document.textLength} chars)"
currentLatencyRecordKey = LatencyDistributionRecordKey(keyName)
latencyRecorderProperties.putAll(mapOf("Delay" to "$delayMillis ms",
"Thread dump delay" to "$threadDumpDelay ms"
))
scriptBuilder?.let {
if (vFile != null) {
val contentRoot = ProjectRootManager.getInstance(project).fileIndex.getContentRootForFile(vFile) ?: return@let
it.append("%openFile ${VfsUtil.getRelativePath(vFile, contentRoot)}\n")
}
it.append(correctText(originalText.substring(0, pos) + originalText.substring(endPos)))
val line = editor.document.getLineNumber(pos)
it.append("%goto ${line + 1} ${pos - editor.document.getLineStartOffset(line) + 1}\n")
}
WriteCommandAction.runWriteCommandAction(project) { document.deleteString(pos, endPos) }
CodeInsightSettings.getInstance().apply {
SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false
ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false
}
CodeInsightWorkspaceSettings.getInstance(project).optimizeImportsOnTheFly = false
EditorNotifications.getInstance(project).updateNotifications(editor.virtualFile)
retypePaused = false
startLargeIndexing()
timerThread.start()
checkStop()
}
private fun correctText(text: String) = "%replaceText ${text.replace('\n', '\u32E1')}\n"
fun stop(startNext: Boolean) {
stopTimer = true
timerThread.join()
for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensions) {
retypeFileAssistant.retypeDone(editor)
}
if (restoreText) {
WriteCommandAction.runWriteCommandAction(project) { document.replaceString(0, document.textLength, originalText) }
}
synchronized(disposeLock) {
Disposer.dispose(this)
}
editor.putUserData(RETYPE_SESSION_KEY, null)
CodeInsightSettings.getInstance().apply {
SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = oldSelectAutopopup
ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = oldAddUnambiguous
}
CodeInsightWorkspaceSettings.getInstance(project).optimizeImportsOnTheFly = oldOptimize
currentLatencyRecordKey?.details = "typed ${log.typedChars} chars, completed ${log.completedChars} chars"
log.flush()
log.printToStdout()
currentLatencyRecordKey = null
if (startNext) {
startNextCallback?.invoke()
}
removeLargeIndexing()
stopInterfereFileChanger = true
EditorNotifications.getInstance(project).updateAllNotifications()
}
override fun dispose() {
}
private fun inFocus(): Boolean =
editor.contentComponent == IdeFocusManager.findInstance().focusOwner && ApplicationManager.getApplication().isActive || ApplicationManager.getApplication().isUnitTestMode
private fun runLoop() {
while (pos != endPos && !stopTimer) {
Thread.sleep(delayMillis.toLong())
if (stopTimer) break
typeNext()
}
}
private fun typeNext() {
if (!ApplicationManager.getApplication().isUnitTestMode) {
threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay)
}
val timerTick = System.currentTimeMillis()
waitingForTimerInvokeLater = true
val expectedTimerTick = if (lastTimerTick != -1L) lastTimerTick + delayMillis else -1L
if (lastTimerTick != -1L) {
threadPoolTimerLag += (timerTick - expectedTimerTick)
}
lastTimerTick = timerTick
ApplicationManager.getApplication().invokeLater {
if (stopTimer) return@invokeLater
typeNextInEDT(timerTick, expectedTimerTick)
}
}
private fun typeNextInEDT(timerTick: Long, expectedTimerTick: Long) {
if (retypePaused) {
if (inFocus()) {
// Resume retyping on editor focus
retypePaused = false
}
else {
checkStop()
return
}
}
if (expectedTimerTick != -1L) {
totalTimerLag += (System.currentTimeMillis() - expectedTimerTick)
}
EditorNotifications.getInstance(project).updateAllNotifications()
waitingForTimerInvokeLater = false
val processNextEvent = handleIdeaIntelligence()
if (processNextEvent) return
if (TemplateManager.getInstance(project).getActiveTemplate(editor) != null) {
TemplateManager.getInstance(project).finishTemplate(editor)
checkStop()
return
}
val lookup = LookupManager.getActiveLookup(editor) as LookupImpl?
if (lookup != null && !skipLookupSuggestion) {
val currentLookupElement = lookup.currentItem
if (currentLookupElement?.shouldAccept(lookup.lookupStart) == true) {
lookup.focusDegree = LookupImpl.FocusDegree.FOCUSED
scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_CHOOSE_LOOKUP_ITEM}\n")
typedRightBefore = false
textBeforeLookupSelection = document.text
executeEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM, timerTick)
checkStop()
return
}
}
// Do not perform typing if editor is not in focus
if (!inFocus()) retypePaused = true
if (retypePaused) {
checkStop()
return
}
// Restore caret position (E.g. user clicks accidentally on another position)
if (editor.caretModel.offset != pos) editor.caretModel.moveToOffset(pos)
val c = originalText[pos++]
log.recordTyping(c)
// Reset lookup related variables
textBeforeLookupSelection = null
if (c == ' ') skipLookupSuggestion = false // We expecting new lookup suggestions
if (c == '\n') {
scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_EDITOR_ENTER}\n")
executeEditorAction(IdeActions.ACTION_EDITOR_ENTER, timerTick)
typedRightBefore = false
}
else {
scriptBuilder?.let {
if (typedRightBefore) {
it.deleteCharAt(it.length - 1)
it.append("$c\n")
}
else {
it.append("%delayType $delayMillis|$c\n")
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
editor.type(c.toString())
}
else {
IdeEventQueue.getInstance().postEvent(
KeyEvent(editor.component, KeyEvent.KEY_PRESSED, timerTick, 0, KeyEvent.VK_UNDEFINED, c))
IdeEventQueue.getInstance().postEvent(
KeyEvent(editor.component, KeyEvent.KEY_TYPED, timerTick, 0, KeyEvent.VK_UNDEFINED, c))
}
typedRightBefore = true
}
checkStop()
}
/**
* @return if next queue event should be processed
*/
private fun handleIdeaIntelligence(): Boolean {
val actualBeforeCaret = document.text.take(pos)
val expectedBeforeCaret = originalText.take(pos)
if (actualBeforeCaret != expectedBeforeCaret) {
// Unexpected changes before current cursor position
// (may be unwanted import)
if (textBeforeLookupSelection != null) {
log.recordDesync("Restoring text before lookup (expected ...${expectedBeforeCaret.takeLast(
5).toReadable()}, actual ...${actualBeforeCaret.takeLast(5).toReadable()} ")
// Unexpected changes was made by lookup.
// Restore previous text state and set flag to skip further suggestions until whitespace will be typed
WriteCommandAction.runWriteCommandAction(project) {
document.replaceText(textBeforeLookupSelection ?: return@runWriteCommandAction, document.modificationStamp + 1)
}
skipLookupSuggestion = true
}
else {
log.recordDesync(
"Restoring text before caret (expected ...${expectedBeforeCaret.takeLast(5).toReadable()}, actual ...${actualBeforeCaret.takeLast(
5).toReadable()} | pos: $pos, caretOffset: ${editor.caretModel.offset}")
// There changes wasn't made by lookup, so we don't know how to handle them
// Restore text before caret as it should be at this point without any intelligence
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(0, editor.caretModel.offset, expectedBeforeCaret)
}
}
}
if (editor.caretModel.offset > pos) {
// Caret movement has been preformed
// Move the caret forward until the characters match
while (pos < document.textLength - tailLength
&& originalText[pos] == document.text[pos]
&& document.text[pos] !in listOf('\n') // Don't count line breakers because we want to enter "enter" explicitly
) {
log.recordCompletion(document.text[pos])
pos++
}
if (editor.caretModel.offset > pos) {
log.recordDesync("Deleting extra characters: ${document.text.substring(pos, editor.caretModel.offset).toReadable()}")
WriteCommandAction.runWriteCommandAction(project) {
// Delete symbols not from original text and move caret
document.deleteString(pos, editor.caretModel.offset)
}
}
editor.caretModel.moveToOffset(pos)
}
if (document.textLength > pos + tailLength) {
updateStack(completionStack)
val firstCompletion = completionStack.peekLast()
if (firstCompletion != null) {
val origIndexOfFirstCompletion = originalText.substring(pos, endPos).trim().indexOf(firstCompletion)
if (origIndexOfFirstCompletion == 0) {
// Next non-whitespace chars from original tests are from completion stack
val origIndexOfFirstComp = originalText.substring(pos, endPos).indexOf(firstCompletion)
val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion)
if (originalText.substring(pos).take(origIndexOfFirstComp) != document.text.substring(pos).take(origIndexOfFirstComp)) {
// We have some unexpected chars before completion. Remove them
WriteCommandAction.runWriteCommandAction(project) {
val replacement = originalText.substring(pos, pos + origIndexOfFirstComp)
log.recordDesync("Replacing extra characters before completion: ${document.text.substring(pos,
pos + docIndexOfFirstComp).toReadable()} -> ${replacement.toReadable()}")
document.replaceString(pos, pos + docIndexOfFirstComp, replacement)
}
}
(pos until pos + origIndexOfFirstComp + firstCompletion.length).forEach { log.recordCompletion(document.text[it]) }
pos += origIndexOfFirstComp + firstCompletion.length
editor.caretModel.moveToOffset(pos)
completionStack.removeLast()
checkStop()
return true
}
else if (origIndexOfFirstCompletion < 0) {
// Completion is wrong and original text doesn't contain it
// Remove this completion
val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion)
log.recordDesync("Removing wrong completion: ${document.text.substring(pos, pos + docIndexOfFirstComp).toReadable()}")
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(pos, pos + docIndexOfFirstComp + firstCompletion.length, "")
}
completionStack.removeLast()
checkStop()
return true
}
}
}
else if (document.textLength == pos + tailLength && completionStack.isNotEmpty()) {
// Text is as expected, but we have some extra completions in stack
completionStack.clear()
}
return false
}
private fun updateStack(completionStack: Deque<String>) {
val unexpectedCharsDoc = document.text.substring(pos, document.textLength - tailLength)
var endPosDoc = unexpectedCharsDoc.length
val completionIterator = completionStack.iterator()
while (completionIterator.hasNext()) {
// Validate all existing completions and add new completions if they are
val completion = completionIterator.next()
val lastIndexOfCompletion = unexpectedCharsDoc.substring(0, endPosDoc).lastIndexOf(completion)
if (lastIndexOfCompletion < 0) {
completionIterator.remove()
continue
}
endPosDoc = lastIndexOfCompletion
}
// Add new completion in stack
unexpectedCharsDoc.substring(0, endPosDoc).trim().split("\\s+".toRegex()).map { it.trim() }.reversed().forEach {
if (it.isNotEmpty()) {
completionStack.add(it)
}
}
}
private fun checkStop() {
if (pos == endPos) {
stop(true)
if (startNextCallback == null && !ApplicationManager.getApplication().isUnitTestMode) {
if (scriptBuilder != null) {
scriptBuilder.append(correctText(originalText))
val file = File.createTempFile("perf", ".test")
val vFile = VfsUtil.findFileByIoFile(file, false)!!
WriteCommandAction.runWriteCommandAction(project) {
VfsUtil.saveText(vFile, scriptBuilder.toString())
}
OpenFileDescriptor(project, vFile).navigate(true)
}
latencyRecorderProperties["Thread pool timer lag"] = "$threadPoolTimerLag ms"
latencyRecorderProperties["Total timer lag"] = "$totalTimerLag ms"
TypingLatencyReportDialog(project, threadDumps).show()
}
}
}
private fun LookupElement.shouldAccept(lookupStartOffset: Int): Boolean {
for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensionList) {
if (!retypeFileAssistant.acceptLookupElement(this)) {
return false
}
}
if (this is LiveTemplateLookupElement) {
return false
}
val lookupString = try {
LookupElementPresentation.renderElement(this).itemText ?: return false
}
catch (e: Exception) {
return false
}
val textAtLookup = originalText.substring(lookupStartOffset)
if (textAtLookup.take(lookupString.length) != lookupString) {
return false
}
return textAtLookup.length == lookupString.length ||
!Character.isJavaIdentifierPart(textAtLookup[lookupString.length] + 1)
}
private fun executeEditorAction(actionId: String, timerTick: Long) {
val actionManager = ActionManagerEx.getInstanceEx()
val action = actionManager.getAction(actionId)
val event = AnActionEvent.createFromAnAction(action, null, "",
DataManager.getInstance().getDataContext(
editor.component))
action.beforeActionPerformedUpdate(event)
actionManager.fireBeforeActionPerformed(action, event.dataContext, event)
LatencyRecorder.getInstance().recordLatencyAwareAction(editor, actionId, timerTick)
action.actionPerformed(event)
actionManager.fireAfterActionPerformed(action, event.dataContext, event)
}
private fun logThreadDump() {
if (editor.isProcessingTypedAction || waitingForTimerInvokeLater) {
threadDumps.add(ThreadDumper.dumpThreadsToString())
if (threadDumps.size > 200) {
threadDumps.subList(0, 100).clear()
}
synchronized(disposeLock) {
if (!threadDumpAlarm.isDisposed) {
threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay)
}
}
}
}
private fun startLargeIndexing() {
if (filesForIndexCount <= 0) return
val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME)
dir.mkdir()
for (i in 0..filesForIndexCount) {
val file = File(dir, "MyClass$i.java")
file.createNewFile()
file.writeText(code.repeat(500))
}
}
private fun removeLargeIndexing() {
if (filesForIndexCount <= 0) return
val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME)
dir.deleteRecursively()
}
@Language("JAVA")
val code = """
class MyClass {
public static void main1(String[] args) {
int x = 5;
}
}
""".trimIndent()
companion object {
val LOG = Logger.getInstance("#com.intellij.internal.retype.RetypeSession")
const val INTERFERE_FILE_NAME = "IdeaRetypeBackgroundChanges.java"
const val LARGE_INDEX_DIR_NAME = "_indexDir_"
}
}
val RETYPE_SESSION_KEY = Key.create<RetypeSession>("com.intellij.internal.retype.RetypeSession")
val RETYPE_SESSION_NOTIFICATION_KEY = Key.create<EditorNotificationPanel>("com.intellij.internal.retype.RetypeSessionNotification")
class RetypeEditorNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
override fun getKey(): Key<EditorNotificationPanel> = RETYPE_SESSION_NOTIFICATION_KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor): EditorNotificationPanel? {
if (fileEditor !is PsiAwareTextEditorImpl) return null
val retypeSession = fileEditor.editor.getUserData(RETYPE_SESSION_KEY)
if (retypeSession == null) return null
val panel: EditorNotificationPanel
if (retypeSession.retypePaused) {
panel = EditorNotificationPanel()
panel.setText("Pause retyping. Click on editor to resume")
}
else {
panel = EditorNotificationPanel(LightColors.SLIGHTLY_GREEN)
panel.setText("Retyping")
}
panel.createActionLabel("Stop without report") {
retypeSession.stop(false)
}
return panel
}
}
| apache-2.0 | 9d39fee6665dbd55f67450e6b7e3a58f | 36.36039 | 177 | 0.70053 | 4.793585 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/html/entities/EntityConverter.kt | 1 | 1844 | package org.intellij.markdown.html.entities
import kotlin.text.Regex
object EntityConverter {
private const val escapeAllowedString = "\\!\"#\\$%&'\\(\\)\\*\\+,\\-.\\/:;<=>\\?@\\[\\\\\\]\\^_`{\\|}\\~"
private val replacements: Map<Char, String> = mapOf(
'"' to """,
'&' to "&",
'<' to "<",
'>' to ">"
)
private val REGEX = Regex("&(?:([a-zA-Z0-9]+)|#([0-9]{1,8})|#[xX]([a-fA-F0-9]{1,8}));|([\"&<>])")
private val REGEX_ESCAPES = Regex("${REGEX.pattern}|\\\\([${escapeAllowedString}])")
fun replaceEntities(text: CharSequence, processEntities: Boolean, processEscapes: Boolean): String {
return (if (processEscapes)
REGEX_ESCAPES
else
REGEX).replace(text) { match ->
val g = match.groups
if (g.size > 5 && g[5] != null) {
val char = g[5]!!.value[0]
replacements[char] ?: char.toString()
} else
if (g[4] != null) {
replacements[g[4]!!.value[0]] ?: match.value
} else {
val code = if (!processEntities) {
null
} else if (g[1] != null) {
Entities.map[match.value]
} else if (g[2] != null) {
g[2]!!.value.toInt()
} else if (g[3] != null) {
g[3]!!.value.toInt(16)
} else {
null
}
val char = code?.toChar()
if (char != null) {
replacements[char] ?: char.toString()
} else {
"&${match.value.substring(1)}"
}
}
}
}
} | apache-2.0 | dd9e60b7e7e0c7af3b6cd1dd949f0dc0 | 34.480769 | 110 | 0.396963 | 4.116071 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/network/NetworkHelper.kt | 1 | 2537 | package eu.kanade.tachiyomi.data.network
import android.content.Context
import okhttp3.*
import rx.Observable
import java.io.File
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.CookieStore
class NetworkHelper(context: Context) {
private val cacheDir = File(context.cacheDir, "network_cache")
private val cacheSize = 5L * 1024 * 1024 // 5 MiB
private val cookieManager = CookieManager().apply {
setCookiePolicy(CookiePolicy.ACCEPT_ALL)
}
private val forceCacheInterceptor = { chain: Interceptor.Chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "max-age=" + 600)
.build()
}
private val client = OkHttpClient.Builder()
.cookieJar(JavaNetCookieJar(cookieManager))
.cache(Cache(cacheDir, cacheSize))
.build()
private val forceCacheClient = client.newBuilder()
.addNetworkInterceptor(forceCacheInterceptor)
.build()
val cookies: CookieStore
get() = cookieManager.cookieStore
@JvmOverloads
fun request(request: Request, forceCache: Boolean = false): Observable<Response> {
return Observable.fromCallable {
val c = if (forceCache) forceCacheClient else client
c.newCall(request).execute().apply { body().close() }
}
}
@JvmOverloads
fun requestBody(request: Request, forceCache: Boolean = false): Observable<String> {
return Observable.fromCallable {
val c = if (forceCache) forceCacheClient else client
c.newCall(request).execute().body().string()
}
}
fun requestBodyProgress(request: Request, listener: ProgressListener): Observable<Response> {
return Observable.fromCallable { requestBodyProgressBlocking(request, listener) }
}
fun requestBodyProgressBlocking(request: Request, listener: ProgressListener): Response {
val progressClient = client.newBuilder()
.cache(null)
.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body(), listener))
.build()
}
.build()
return progressClient.newCall(request).execute()
}
}
| apache-2.0 | 5c2b025ccb3c3754f34a478b03dd0aa3 | 32.381579 | 97 | 0.636184 | 5.114919 | false | false | false | false |
GymDon-P-Q11Info-13-15/game | Game Commons/src/de/gymdon/inf1315/game/Knight.kt | 1 | 331 | package de.gymdon.inf1315.game
class Knight(owner: Player, x: Int, y: Int) : Unit() {
init {
this.owner = owner
this.x = x
this.y = y
speed = 7
range = 1
attack = 70
defense = 50
hp = 100
cost = 200
combined = 0.25
super.reset()
}
}
| gpl-3.0 | b7445f09fd023b9df2523d447ae6e99d | 17.388889 | 54 | 0.459215 | 3.484211 | false | false | false | false |
ze-pequeno/butterknife | butterknife-gradle-plugin/src/test/java/butterknife/plugin/BuildFilesRule.kt | 3 | 1683 | package butterknife.plugin
import com.google.common.truth.Truth.assertThat
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.File
class BuildFilesRule(private val root: File) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
val settingsFile = File(root, "settings.gradle")
val hasSettingsFile = settingsFile.exists()
if (!hasSettingsFile) settingsFile.writeText("")
val buildFile = File(root, "build.gradle")
val hasBuildFile = buildFile.exists()
if (hasBuildFile) {
assertThat(buildFile.readText())
} else {
val buildFileTemplate = File(root, "../../build.gradle").readText()
buildFile.writeText(buildFileTemplate)
}
val manifestFile = File(root, "src/main/AndroidManifest.xml")
val hasManifestFile = manifestFile.exists()
if (!hasManifestFile) {
val manifestFileTemplate = File(root, "../../AndroidManifest.xml").readText()
manifestFile.writeText(manifestFileTemplate)
}
try {
base.evaluate()
} finally {
if (!hasSettingsFile) settingsFile.delete()
if (!hasBuildFile) buildFile.delete()
if (!hasManifestFile) manifestFile.delete()
}
}
}
}
} | apache-2.0 | 3fc36c7f7170a2caf00f64dd9a1b4144 | 39.095238 | 97 | 0.557338 | 5.482085 | false | false | false | false |
JetBrains/anko | anko/library/static/sqlite/src/main/java/SelectQueryBuilder.kt | 4 | 6889 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "NOTHING_TO_INLINE")
package org.jetbrains.anko.db
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import org.jetbrains.anko.AnkoException
import org.jetbrains.anko.internals.AnkoInternals
abstract class SelectQueryBuilder(val tableName: String) {
private val columns = arrayListOf<String>()
private val groupBy = arrayListOf<String>()
private val orderBy = arrayListOf<String>()
private var distinct: Boolean = false
private var havingApplied = false
private var having: String? = null
private var limit: String? = null
private var selectionApplied = false
private var useNativeSelection = false
private var selection: String? = null
private var nativeSelectionArgs: Array<out String>? = null
fun <T> exec(f: Cursor.() -> T): T {
val cursor = doExec()
return AnkoInternals.useCursor(cursor) {
cursor.f()
}
}
inline fun <T: Any> parseSingle(parser: RowParser<T>): T = AnkoInternals.useCursor(doExec()) {
it.parseSingle(parser)
}
inline fun <T: Any> parseOpt(parser: RowParser<T>): T? = AnkoInternals.useCursor(doExec()) {
it.parseOpt(parser)
}
inline fun <T: Any> parseList(parser: RowParser<T>): List<T> = AnkoInternals.useCursor(doExec()) {
it.parseList(parser)
}
inline fun <T: Any> parseSingle(parser: MapRowParser<T>): T = AnkoInternals.useCursor(doExec()) {
it.parseSingle(parser)
}
inline fun <T: Any> parseOpt(parser: MapRowParser<T>): T? = AnkoInternals.useCursor(doExec()) {
it.parseOpt(parser)
}
inline fun <T: Any> parseList(parser: MapRowParser<T>): List<T> = AnkoInternals.useCursor(doExec()) {
it.parseList(parser)
}
@PublishedApi
internal fun doExec(): Cursor {
val finalSelection = if (selectionApplied) selection else null
val finalSelectionArgs = if (selectionApplied && useNativeSelection) nativeSelectionArgs else null
return execQuery(distinct, tableName, columns.toTypedArray(),
finalSelection, finalSelectionArgs,
groupBy.joinToString(", "), having, orderBy.joinToString(", "), limit)
}
protected abstract fun execQuery(
distinct: Boolean,
tableName: String,
columns: Array<String>,
selection: String?,
selectionArgs: Array<out String>?,
groupBy: String,
having: String?,
orderBy: String,
limit: String?
): Cursor
fun distinct(): SelectQueryBuilder {
this.distinct = true
return this
}
fun column(name: String): SelectQueryBuilder {
columns.add(name)
return this
}
fun groupBy(value: String): SelectQueryBuilder {
groupBy.add(value)
return this
}
fun orderBy(value: String, direction: SqlOrderDirection = SqlOrderDirection.ASC): SelectQueryBuilder {
if (direction == SqlOrderDirection.DESC) {
orderBy.add("$value DESC")
} else {
orderBy.add(value)
}
return this
}
fun limit(count: Int): SelectQueryBuilder {
limit = count.toString()
return this
}
fun limit(offset: Int, count: Int): SelectQueryBuilder {
limit = "$offset, $count"
return this
}
fun columns(vararg names: String): SelectQueryBuilder {
columns.addAll(names)
return this
}
fun having(having: String): SelectQueryBuilder {
if (havingApplied) {
throw AnkoException("Query having was already applied.")
}
havingApplied = true
this.having = having
return this
}
fun having(having: String, vararg args: Pair<String, Any>): SelectQueryBuilder {
if (selectionApplied) {
throw AnkoException("Query having was already applied.")
}
havingApplied = true
this.having = applyArguments(having, *args)
return this
}
@Deprecated("Use whereArgs(select, args) instead.", ReplaceWith("whereArgs(select, args)"))
fun where(select: String, vararg args: Pair<String, Any>): SelectQueryBuilder {
return whereArgs(select, *args)
}
fun whereArgs(select: String, vararg args: Pair<String, Any>): SelectQueryBuilder {
if (selectionApplied) {
throw AnkoException("Query selection was already applied.")
}
selectionApplied = true
useNativeSelection = false
selection = applyArguments(select, *args)
return this
}
@Deprecated("Use whereArgs(select) instead.", ReplaceWith("whereArgs(select)"))
fun where(select: String): SelectQueryBuilder {
return whereArgs(select)
}
fun whereArgs(select: String): SelectQueryBuilder {
if (selectionApplied) {
throw AnkoException("Query selection was already applied.")
}
selectionApplied = true
useNativeSelection = false
selection = select
return this
}
fun whereSimple(select: String, vararg args: String): SelectQueryBuilder {
if (selectionApplied) {
throw AnkoException("Query selection was already applied.")
}
selectionApplied = true
useNativeSelection = true
selection = select
nativeSelectionArgs = args
return this
}
@Deprecated("Use whereSimple() instead", replaceWith = ReplaceWith("whereSimple(select, *args)"))
fun whereSupport(select: String, vararg args: String): SelectQueryBuilder {
return whereSimple(select, *args)
}
}
class AndroidSdkDatabaseSelectQueryBuilder(
private val db: SQLiteDatabase,
tableName: String
) : SelectQueryBuilder(tableName) {
override fun execQuery(
distinct: Boolean,
tableName: String,
columns: Array<String>,
selection: String?,
selectionArgs: Array<out String>?,
groupBy: String,
having: String?,
orderBy: String,
limit: String?
): Cursor {
return db.query(distinct, tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
}
}
| apache-2.0 | 5a621b8c9e7342d3f0456d826032d732 | 30.171946 | 112 | 0.639715 | 4.686395 | false | false | false | false |
huhanpan/smart | app/src/main/java/com/etong/smart/Main/Login/LoginActivity.kt | 1 | 7860 | package com.etong.smart.Main.Login
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.Toolbar
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import com.alibaba.fastjson.JSONObject
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.etong.smart.Main.MainActivity
import com.etong.smart.Other.*
import com.etong.smart.R
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_login.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class LoginActivity : BaseActivity(), TextWatcher {
private var keyboaryProvider: KeyboardHeightProvider? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setSupportActionBar(findViewById(R.id.toolbar) as Toolbar)
keyboaryProvider = KeyboardHeightProvider(this)
rootView.post { keyboaryProvider?.start() }
etAccount.setText(Storage.readUsername())
etAccount.addTextChangedListener(this)
etPwd.addTextChangedListener(this)
btnLogin.setOnClickListener {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(it.windowToken, 0)
if (etAccount.text?.length!! < 0) {
Snackbar.make(it, "请输入账号", Snackbar.LENGTH_SHORT).show()
return@setOnClickListener
}
val key = System.currentTimeMillis().toString()
val account = etAccount.text.toString()
Service.login(key, account, etPwd?.text.toString())
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
Snackbar.make(it, t?.message.toString(), Snackbar.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
if (response != null && response.isSuccessful) {
try {
val json = JSONObject.parseObject(response.body())
val responseData = json.getString("data")
if (responseData == null) {
Snackbar.make(it, json.getString("error"), Snackbar.LENGTH_SHORT).show()
} else {
val originalJson = JSONObject.parseObject(AESCrypt.decrypt(key, responseData))
Storage.saveUsername(etAccount?.text.toString())
if (originalJson.getInteger("is_login") == 0) {
val is_admin = originalJson.getInteger("is_admin")
Storage.saveIsAdmin(originalJson.getBoolean("is_admin"))
toRegisterActivity(is_admin)
} else {
for ((key1, value) in originalJson) {
when (key1) {
"token" -> Storage.saveToken(value.toString())
"is_admin" -> Storage.saveIsAdmin(value == 1)
"upload_token" -> Storage.saveQINIU(value.toString())
"push_id" -> bindPush(value.toString())
}
}
Storage.savePwd(etPwd.text.toString())
toMainActivity()
}
}
} catch (e:Exception) {
Snackbar.make(it, "服务器错误,请稍后再试", Snackbar.LENGTH_SHORT).show()
}
} else {
Snackbar.make(it, "服务器错误,请稍后再试", Snackbar.LENGTH_SHORT).show()
}
}
})
}
etAccount?.setOnFocusChangeListener { view, b ->
if (b) {
println("获得焦点")
} else {
RxServie.getUserIcon((view as EditText).text.toString()) {
Picasso.with(this).load(Service.QiniuUrl + it).placeholder(R.drawable.user_place).into(roundedImageView)
}
}
}
//点击空白处退出键盘
backView.setOnClickListener {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(it.windowToken, 0)
}
btnRetrieve.setOnClickListener { startActivity(Intent(this@LoginActivity, ForgetPwdActivity::class.java)) }
}
//绑定推送
private fun bindPush(account: String) {
val pushService = PushServiceFactory.getCloudPushService()
pushService.bindAccount(account, object : CommonCallback {
override fun onSuccess(p0: String?) {
println("bind success")
}
override fun onFailed(p0: String?, p1: String?) {
Snackbar.make(btnLogin, "绑定推送失败($p1)", Snackbar.LENGTH_SHORT).show()
}
})
}
override fun onResume() {
super.onResume()
keyboaryProvider?.setKeyboardHeightObserver { height, orientation ->
val move = (backView.height - btnLogin.height - btnLogin.y) - height
if (height > 100) {
ObjectAnimator.ofFloat(backView, "y", move + toolbar.height.toFloat() - 10 * resources.displayMetrics.density).start()
} else {
ObjectAnimator.ofFloat(backView, "y", toolbar.height.toFloat()).start()
}
}
}
override fun onDestroy() {
super.onDestroy()
keyboaryProvider?.close()
}
override fun onPause() {
super.onPause()
keyboaryProvider?.setKeyboardHeightObserver(null)
}
///////////////////////////////////////////////////////////////////////////
// textChangeWatcher
///////////////////////////////////////////////////////////////////////////
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun afterTextChanged(s: Editable?) {
btnLogin.isEnabled = etAccount?.text!!.isNotEmpty()
}
///////////////////////////////////////////////////////////////////////////
// 跳转
///////////////////////////////////////////////////////////////////////////
private fun toMainActivity() {
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
finish()
}
private fun toRegisterActivity(is_admin: Int) {
val intent = Intent(this@LoginActivity, RegisterActivity::class.java)
intent.putExtra("account", etAccount?.text.toString())
intent.putExtra("is_admin", is_admin)
startActivity(intent)
}
}
| gpl-2.0 | e0259e4465ce18586a3b2a6aee744f10 | 40.945946 | 134 | 0.522809 | 5.307798 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/MainActivity.kt | 1 | 4776 | package org.fossasia.openevent.general
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI.setupWithNavController
import kotlinx.android.synthetic.main.activity_main.mainFragmentCoordinatorLayout
import kotlinx.android.synthetic.main.activity_main.navigation
import org.fossasia.openevent.general.auth.AuthFragment
import org.fossasia.openevent.general.auth.RC_CREDENTIALS_READ
import org.fossasia.openevent.general.auth.SmartAuthUtil
import org.fossasia.openevent.general.auth.SmartAuthViewModel
import org.fossasia.openevent.general.utils.AppLinkUtils
import org.fossasia.openevent.general.utils.Utils.navAnimGone
import org.fossasia.openevent.general.utils.Utils.navAnimVisible
import org.jetbrains.anko.design.snackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
const val PLAY_STORE_BUILD_FLAVOR = "playStore"
const val FDROID_BUILD_FLAVOR = "fdroid"
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
private var currentFragmentId: Int = 0
private val smartAuthViewModel by viewModel<SmartAuthViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer)
if (hostFragment is NavHostFragment)
navController = hostFragment.navController
setupBottomNavigationMenu(navController)
navController.addOnDestinationChangedListener { _, destination, _ ->
currentFragmentId = destination.id
handleNavigationVisibility(currentFragmentId)
}
AppLinkUtils.handleIntent(intent, navController)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
AppLinkUtils.handleIntent(intent, navController)
}
private fun setupBottomNavigationMenu(navController: NavController) {
setupWithNavController(navigation, navController)
navigation.setOnNavigationItemReselectedListener {
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer)
if (hostFragment is NavHostFragment) {
val currentFragment = hostFragment.childFragmentManager.fragments.first()
if (currentFragment is BottomIconDoubleClick) currentFragment.doubleClick()
}
}
}
private fun handleNavigationVisibility(id: Int) {
when (id) {
R.id.eventsFragment,
R.id.searchFragment,
R.id.profileFragment,
R.id.orderUnderUserFragment,
R.id.favoriteFragment -> navAnimVisible(navigation, this@MainActivity)
else -> navAnimGone(navigation, this@MainActivity)
}
}
override fun onBackPressed() {
val hostFragment = supportFragmentManager.findFragmentById(R.id.frameContainer)
if (hostFragment is NavHostFragment) {
val currentFragment = hostFragment.childFragmentManager.fragments.first()
if (currentFragment is ComplexBackPressFragment) {
currentFragment.handleBackPress()
if (currentFragment is AuthFragment)
mainFragmentCoordinatorLayout.snackbar(R.string.sign_in_canceled)
return
}
}
when (currentFragmentId) {
R.id.orderCompletedFragment -> navController.popBackStack(R.id.eventDetailsFragment, false)
R.id.welcomeFragment -> finish()
else -> super.onBackPressed()
}
}
/**
* Called by EditProfileFragment to go to previous fragment
*/
fun onSuperBackPressed() {
super.onBackPressed()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (BuildConfig.FLAVOR == PLAY_STORE_BUILD_FLAVOR && requestCode == RC_CREDENTIALS_READ) {
if (resultCode == Activity.RESULT_OK) {
// Fill in the email field in LoginFragment
val email = SmartAuthUtil.getEmailAddressFromIntent(data)
if (email != null) {
smartAuthViewModel.apply {
mutableId.value = email
}
}
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
interface BottomIconDoubleClick {
fun doubleClick()
}
interface ComplexBackPressFragment {
fun handleBackPress()
}
| apache-2.0 | 052e251631d3c5508a64099ecf541639 | 37.829268 | 103 | 0.69598 | 5.124464 | false | false | false | false |
dri94/AllStorj | app/src/main/java/tech/devezin/allstorj/buckets/create/CreateBucketBottomSheet.kt | 1 | 4018 | package tech.devezin.allstorj.buckets.create
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.android.synthetic.main.dialog_create_bucket.*
import tech.devezin.allstorj.R
import tech.devezin.allstorj.utils.expandHeight
import tech.devezin.allstorj.utils.observeEvent
import tech.devezin.allstorj.utils.text
import tech.devezin.allstorj.utils.viewModels
class CreateBucketBottomSheet : BottomSheetDialogFragment() {
private val viewModel: CreateBucketViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.dialog_create_bucket, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.viewState.observe(viewLifecycleOwner, Observer {
setAdvancedOptionsVisibility(it.showAdvancedOptions)
createBucketError.text = it.error
})
viewModel.events.observeEvent(viewLifecycleOwner) {
return@observeEvent when (it) {
is CreateBucketViewModel.Events.GoToBucketsList -> {
LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(Intent(BROADCAST_BUCKET_CREATED))
dismiss()
true
}
}
}
createBucketAdvancedOptionsLabel.setOnClickListener {
viewModel.onAdvancedOptionsClicked()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
expandHeight()
createBucketConfirm.setOnClickListener {
viewModel.onCreateGroupClicked(
bucketName = createBucketInput.text(),
encryptionChipId = createBucketEncryptionCipherChipGroup.checkedChipId,
blockSizeString = createBucketEncryptionBlockSizeInput.text(),
cipherChipId = createBucketPathCipherChipGroup.checkedChipId,
segmentSizeString = createBucketSegmentSizeInput.text(),
repairSharesString = createBucketRedundancyRepairSharesInput.text(),
requiredSharesString = createBucketRedundancyRequiredSharesInput.text(),
shareSizeString = createBucketRedundancyShareSizeInput.text(),
successSharesString = createBucketRedundancySuccessSharesInput.text(),
totalSharesString = createBucketRedundancyTotalSharesInput.text()
)
}
}
private fun setAdvancedOptionsVisibility(isVisible: Boolean) {
createBucketAdvancedOptionsLabel.setCompoundDrawablesRelativeWithIntrinsicBounds(
0,
0,
if (isVisible) R.drawable.ic_expand_less else R.drawable.ic_expand_more,
0
)
val visibility = if (isVisible) View.VISIBLE else View.GONE
createBucketEncryptionParametersLabel.visibility = visibility
createBucketEncryptionCipherChipGroup.visibility = visibility
createBucketEncryptionBlockSizeLayout.visibility = visibility
createBucketPathCipherLabel.visibility = visibility
createBucketPathCipherChipGroup.visibility = visibility
createBucketSegmentSizeLabel.visibility = visibility
createBucketSegmentSizeLayout.visibility = visibility
createBucketRedundancyLabel.visibility = visibility
createBucketRedundancyShares1Layout.visibility = visibility
createBucketRedundancyShares2Layout.visibility = visibility
}
companion object {
const val BROADCAST_BUCKET_CREATED = "bucket_created"
}
}
| gpl-3.0 | a7b1e269b487239bdbf048dad940beeb | 42.673913 | 119 | 0.71777 | 5.300792 | false | false | false | false |
deianvn/misc | vfu/course_3/android/CurrencyConverter/app/src/main/java/bg/vfu/rizov/currencyconverter/main/MainActivity.kt | 1 | 1999 | package bg.vfu.rizov.currencyconverter.main
import android.arch.lifecycle.Observer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import bg.vfu.rizov.currencyconverter.R
import bg.vfu.rizov.currencyconverter.main.converter.ConverterFragment
import kotlinx.android.synthetic.main.activity_main.*
import org.koin.android.viewmodel.ext.android.viewModel
class MainActivity : AppCompatActivity() {
private val mainViewModel by viewModel<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel.status.observe(this, Observer {
if (it != null) {
when (it.code) {
MainViewModel.StatusCode.LOADING -> showLoading()
MainViewModel.StatusCode.COMPLETED -> showContent()
MainViewModel.StatusCode.ERROR -> showError { it.retryCallback?.invoke() }
}
}
})
mainViewModel.currencies.observe(this, Observer {
if (it != null) {
showFragment(ConverterFragment())
}
})
mainViewModel.init()
}
private fun showLoading() {
retryButton.setOnClickListener(null)
errorLayout.visibility = View.GONE
fragmentLayout.visibility = View.GONE
progress.visibility = View.VISIBLE
}
private fun showContent() {
retryButton.setOnClickListener(null)
errorLayout.visibility = View.GONE
fragmentLayout.visibility = View.VISIBLE
progress.visibility = View.GONE
}
private fun showError(callback: RetryCallback) {
retryButton.setOnClickListener { callback() }
errorLayout.visibility = View.VISIBLE
fragmentLayout.visibility = View.GONE
progress.visibility = View.GONE
}
private fun showFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragmentLayout, fragment)
transaction.commit()
}
}
| apache-2.0 | 77673f20e7fe7ab5563f1eed3337f3a8 | 29.287879 | 84 | 0.733367 | 4.563927 | false | false | false | false |
panpanini/KotlinWithDatabinding | app/src/main/java/nz/co/panpanini/kotlindatabinding/ui/repo/RepoActivity.kt | 1 | 2454 | package nz.co.panpanini.kotlindatabinding.ui.repo
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.Toast
import nz.co.panpanini.kotlindatabinding.R
import nz.co.panpanini.kotlindatabinding.api.GitHub
import nz.co.panpanini.kotlindatabinding.model.Repo
import nz.co.panpanini.kotlindatabinding.repository.RepoRepository
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import rx.schedulers.Schedulers
class RepoActivity : AppCompatActivity(), RepoView {
val recyclerView by lazy {
findViewById(R.id.activity_repo) as RecyclerView
}
val adapter = RepoAdapter()
val presenter by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
val retroUser = retrofit.create(GitHub::class.java) // this is how you say GitHub.class
// similar to Ruby - if we create this object on the last line of the lambda, it will return it
// we don't have to specify return
RepoPresenter(this, RepoRepository(retroUser))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_repo)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
presenter.fetchRepos(intent.getStringExtra(USERNAME))
}
override fun addRepo(repo: Repo) = adapter.add(repo)
override fun networkError(message: String) = Toast.makeText(this, "Network Error: $message", Toast.LENGTH_LONG).show()
companion object {
private val USERNAME = "USERNAME"
fun createIntent(context: Context, username: String): Intent {
val intent = Intent(context, RepoActivity::class.java)
intent.putExtra(USERNAME, username)
return intent
}
}
}
| unlicense | 64b93b50e9038539cffa7ec883aa8849 | 35.626866 | 122 | 0.731866 | 4.604128 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/main/MainFragment.kt | 1 | 8347 | package org.illegaller.ratabb.hishoot2i.ui.main
import android.graphics.Bitmap
import android.graphics.Point
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import common.ext.graphics.sizes
import common.ext.preventMultipleClick
import core.Preview
import core.Save
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.illegaller.ratabb.hishoot2i.HiShootActivity
import org.illegaller.ratabb.hishoot2i.R
import org.illegaller.ratabb.hishoot2i.data.pref.SettingPref
import org.illegaller.ratabb.hishoot2i.databinding.FragmentMainBinding
import org.illegaller.ratabb.hishoot2i.ui.ARG_BACKGROUND_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_CROP_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_PIPETTE_COLOR
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN1_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN2_PATH
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_BACKGROUND
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_CROP
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_PIPETTE
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SAVE
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SCREEN_1
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SCREEN_2
import org.illegaller.ratabb.hishoot2i.ui.common.clearFragmentResultListeners
import org.illegaller.ratabb.hishoot2i.ui.common.setFragmentResultListeners
import org.illegaller.ratabb.hishoot2i.ui.common.showSnackBar
import org.illegaller.ratabb.hishoot2i.ui.common.viewObserve
import org.illegaller.ratabb.hishoot2i.ui.main.MainFragmentDirections.Companion.actionMainToToolsBackground
import org.illegaller.ratabb.hishoot2i.ui.main.MainFragmentDirections.Companion.actionMainToToolsBadge
import org.illegaller.ratabb.hishoot2i.ui.main.MainFragmentDirections.Companion.actionMainToToolsScreen
import org.illegaller.ratabb.hishoot2i.ui.main.MainFragmentDirections.Companion.actionMainToToolsTemplate
import timber.log.Timber
import javax.inject.Inject
@ExperimentalCoroutinesApi
@AndroidEntryPoint
class MainFragment : Fragment(R.layout.fragment_main) {
@Inject
lateinit var saveNotification: SaveNotification
@Inject
lateinit var settingPref: SettingPref
private val viewModel: MainViewModel by viewModels()
private val requestKeys = arrayOf(
KEY_REQ_CROP, KEY_REQ_BACKGROUND,
KEY_REQ_SCREEN_1, KEY_REQ_SCREEN_2,
KEY_REQ_PIPETTE, KEY_REQ_SAVE
)
private val args: MainFragmentArgs by navArgs()
private var ratioCrop = Point()
private var isOnPipette: Boolean = false
private var isOnProgress: Boolean = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FragmentMainBinding.bind(view).apply {
setViewListener()
viewObserve(viewModel.uiState) { observer(it) }
setFragmentResultListeners(*requestKeys) { requestKey, result ->
handleResult(requestKey, result)
}
}
if (!handleReceiver()) viewModel.render()
}
override fun onDestroyView() {
clearFragmentResultListeners(*requestKeys)
super.onDestroyView()
}
override fun onResume() {
super.onResume()
viewModel.resume()
}
private fun FragmentMainBinding.handleResult(
requestKey: String,
result: Bundle
): Unit = when (requestKey) {
KEY_REQ_CROP -> viewModel.changeBackground(result.getString(ARG_CROP_PATH))
KEY_REQ_BACKGROUND -> viewModel.changeBackground(result.getString(ARG_BACKGROUND_PATH))
KEY_REQ_SCREEN_1 -> viewModel.changeScreen1(result.getString(ARG_SCREEN1_PATH))
KEY_REQ_SCREEN_2 -> viewModel.changeScreen2(result.getString(ARG_SCREEN2_PATH))
KEY_REQ_PIPETTE -> startingPipette(result.getInt(ARG_PIPETTE_COLOR))
KEY_REQ_SAVE -> viewModel.save()
else -> {
}
}
private fun FragmentMainBinding.observer(view: MainView): Unit = when (view) {
is Loading -> {
if (view.isFromSave) saveNotification.start()
showProgress()
}
is Fail -> {
hideProgress()
if (view.isFromSave) saveNotification.error(view.cause)
val msg = view.cause.localizedMessage ?: "Oops"
Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show()
Timber.e(view.cause)
}
is Success -> {
hideProgress()
when (view.result) {
is Preview -> {
ratioCrop = view.result.bitmap.sizes.run { Point(x, y) }
mainImage.setImageBitmap(view.result.bitmap)
}
is Save -> {
val (bitmap: Bitmap, uri: Uri, name: String) = view.result
saveNotification.complete(bitmap, name, uri)
}
}
}
}
private fun FragmentMainBinding.setViewListener() {
mainFab.setOnClickListener {
it.preventMultipleClick {
if (isOnPipette) stopPipette()
else {
if (settingPref.saveConfirmEnable) {
findNavController().navigate(R.id.action_main_to_saveConfirm)
} else viewModel.save()
}
}
}
mainBottomAppBar.setOnMenuItemClickListener {
it.preventMultipleClick { bottomMenuClick(it) }
}
mainBottomAppBar.setNavigationOnClickListener {
it.preventMultipleClick {
if (isOnPipette) stopPipette(isCancel = true)
(activity as? HiShootActivity)?.openDrawer()
}
}
}
private fun FragmentMainBinding.showProgress() {
isOnProgress = true
mainFab.setImageResource(R.drawable.ic_dot) // TODO: use AVD here!
mainFab.isEnabled = false
mainProgress.show()
}
private fun FragmentMainBinding.hideProgress() {
isOnProgress = false
mainFab.setImageResource(R.drawable.ic_save)
mainFab.isEnabled = true
mainProgress.hide()
}
private fun FragmentMainBinding.startingPipette(srcColor: Int) {
isOnPipette = true
mainImage.startPipette(srcColor)
mainFab.setImageResource(R.drawable.ic_pipette_done)
}
private fun FragmentMainBinding.stopPipette(isCancel: Boolean = false) {
if (isCancel) {
mainImage.stopPipette()
mainFab.setImageResource(R.drawable.ic_save)
} else {
mainImage.stopPipette(viewModel::backgroundColorPipette)
}
isOnPipette = false
}
private fun FragmentMainBinding.bottomMenuClick(item: MenuItem): Boolean = when {
isOnProgress -> false.also {
showSnackBar(
view = root,
resId = R.string.on_progress,
anchorViewId = R.id.mainFab
)
}
isOnPipette -> false.also {
showSnackBar(
view = root,
resId = R.string.on_pipette,
anchorViewId = R.id.mainFab,
action = {
setAction(R.string.cancel) { stopPipette(isCancel = true) }
}
)
}
else -> {
when (item.itemId) {
R.id.action_background -> actionMainToToolsBackground(ratioCrop)
R.id.action_badge -> actionMainToToolsBadge()
R.id.action_screen -> actionMainToToolsScreen()
R.id.action_template -> actionMainToToolsTemplate()
else -> null
}?.let { findNavController().navigate(it) } != null
}
}
private fun handleReceiver(): Boolean = with(args) {
val rawUri = path ?: return false
return when (kind) {
R.string.background -> true.also { viewModel.changeBackground(rawUri) }
R.string.screen -> true.also { viewModel.changeScreen1(rawUri) }
else -> false
}
}
}
| apache-2.0 | 9c89a844f3e96681ac5d74a3acf0341e | 37.288991 | 107 | 0.660237 | 4.365586 | false | false | false | false |
SixCan/SixDaily | app/src/test/java/ca/six/daily/utils/DataUtilsTest.kt | 1 | 2887 |
package ca.six.daily.utils
import android.os.Build
import ca.six.daily.BuildConfig
import ca.six.daily.core.BaseApp
import ca.six.daily.utils.isCacheFileExist
import ca.six.daily.utils.writeToCacheFile
import io.reactivex.observers.TestObserver
import io.reactivex.subscribers.TestSubscriber
import org.junit.After
import org.junit.Assert
import org.junit.Test
import org.junit.Assert.*
import org.junit.runner.RunWith
import org.mockito.Mockito.*
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowEnvironment
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP)
,application = BaseApp::class)
class DataUtilsTest {
val fileName = "news_latest.json"
@Test
fun testIsExisting_returnFalse_whenAtFirst(){
assertFalse(isCacheFileExist(fileName))
}
@Test
fun testCacheFile_whenSuccess() {
writeToCacheFile("test", fileName)
assertTrue(isCacheFileExist(fileName))
assertEquals("test", readCacheFile(fileName))
}
@Test
fun testReadCachedLatestNews_whenNoCache_shouldObserveComplete(){
val test = TestObserver<String>()
readCachedLatestNews().subscribe(test)
test.assertComplete()
}
@Test
fun testReadCachedLatestNews_whenCacheIsOld_shouldObserveComplete(){
prepareCacheFile(20160202) // a day that is prior to today
val test = TestObserver<String>()
readCachedLatestNews().subscribe(test)
test.assertComplete()
}
@Test
fun testReadCachedLatestNews_whenLatestCache_shouldObserveNext(){
val dateFormatter = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
dateFormatter.timeZone = TimeZone.getTimeZone("GMT+8:00")
val nowTimeCn = dateFormatter.format(Date())
prepareCacheFile(nowTimeCn.toInt())
val test = TestObserver<String>()
readCachedLatestNews().subscribe(test)
test.assertValue("{ date: \"${nowTimeCn}\", stories: [] }")
}
private fun prepareCacheFile(date : Int){
var fileContent = "{ date: \"${date}\", stories: [] }"
writeToCacheFile(fileContent, fileName)
}
// delete the file, so the test is stateless
@After
fun cleanUp(){
// dir.path = "/var/folders/4w/1qcx1th56px_3vvfmbcy2zdh0000gp/T/robolectric695337270918799239/cache"
val dir = BaseApp.app.cacheDir
val file = File(dir, fileName)
file.delete()
}
}
/*
1. use Robolectric to avoid error:
"Property 'app' should be initialzied before get" : BaseApp.app
2. Robolectric + AndroidStudio3.x : NPE Error
: to fix it, add "android.enableAapt2=false" in gradle.properties
*/
| mpl-2.0 | 0dac70fed56fae18dc40b73c8087e4a1 | 29.072917 | 108 | 0.714583 | 4.124286 | false | true | false | false |
RahulChidurala/SimonSays | app/src/main/java/com/chidurala/rahul/simonsays/Service/GameLeveler.kt | 1 | 1872 | package com.chidurala.rahul.simonsays.Service
import android.app.AlertDialog
import android.util.Log
import com.chidurala.rahul.simonsays.Delegate.DisplayInfoDelegate
import com.chidurala.rahul.simonsays.Delegate.GameOverDelegate
/**
* Created by Rahul Chidurala on 10/7/2017.
*
*/
class GameLeveler(private var gameSequenceGenerator: GameSequenceGenerator, private var gameSequencePlayer: GameSequencePlayer, private val gameOverDelegate: GameOverDelegate? = null, private val totalLives: Int = 3) {
private var _lives: Int = totalLives
var lives: Int
get() = _lives
set(value) {
_lives = value
displayLives?.showInfo(value.toString())
}
private val livesPerGame: Int = lives
private var sequence: Sequence
// TODO: Remove display lives delegate from here
var displayLives: DisplayInfoDelegate? = null
init {
this.lives = lives
sequence = gameSequenceGenerator.getNewSequence()
}
fun startGame() {
lives = livesPerGame
gameSequenceGenerator.resetSequence()
sequence = gameSequenceGenerator.getCurrentSequence()
gameSequencePlayer.playSequence(sequence)
}
/**
* Level cleared. Reset lives, increment sequence and play new sequence.
*/
fun levelCleared() {
sequence = gameSequenceGenerator.getNewSequence()
playLevel(sequence)
}
/**
* Level failed. Implement later...
*/
fun levelFailed() {
lives--
if(lives <= 0) {
Log.d("GAME", "Game over!")
gameOver()
} else {
playLevel(sequence = sequence)
}
}
private fun gameOver() {
gameOverDelegate?.gameOver()
}
private fun playLevel(sequence: Sequence) {
gameSequencePlayer.playSequence(sequence)
}
} | mit | ea8367dc86070ecc71a34edb03df9fc1 | 22.708861 | 218 | 0.645833 | 4.404706 | false | false | false | false |
hea3ven/DulceDeLeche | src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/client/gui/CraftingMachineScreen.kt | 1 | 2107 | package com.hea3ven.dulcedeleche.modules.redstone.client.gui
import com.hea3ven.tools.commonutils.container.GenericContainer
import com.mojang.blaze3d.platform.GlStateManager
import net.minecraft.client.gui.ContainerScreen
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.text.TextComponent
import net.minecraft.util.Identifier
open class CraftingMachineScreen<T : GenericContainer>(container: T, playerInv: PlayerInventory, name: TextComponent,
private val bgTex: Identifier) : ContainerScreen<T>(container, playerInv, name) {
init {
containerHeight = 215
}
override fun drawForeground(int_1: Int, int_2: Int) {
val name = title.formattedText
font.draw(name, (containerWidth / 2 - font.getStringWidth(name) / 2).toFloat(),
6.0F, 4210752)
font.draw(playerInventory.displayName.formattedText, 8.0F,
(containerHeight - 96 + 2).toFloat(), 4210752)
}
override fun drawBackground(var1: Float, var2: Int, var3: Int) {
GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F)
minecraft!!.textureManager.bindTexture(bgTex)
val x = left
val y = (height - containerHeight) / 2
blit(x, y, 0, 0, containerWidth, containerHeight)
}
override fun render(int_1: Int, int_2: Int, float_1: Float) {
super.render(int_1, int_2, float_1)
val x = left
val y = (height - containerHeight) / 2
for (i in 0..8) {
val slot = container.getSlot(i)
if (!slot.stack.isEmpty) {
drawGhostItem(x + slot.xPosition, y + slot.yPosition)
}
}
}
private fun drawGhostItem(xPos: Int, yPos: Int) {
GlStateManager.disableLighting()
GlStateManager.disableDepthTest()
GlStateManager.colorMask(true, true, true, false)
blit(xPos, yPos, xPos + 16, yPos + 16, -2130706433, -2130706433)
GlStateManager.colorMask(true, true, true, true)
GlStateManager.enableDepthTest()
GlStateManager.enableLighting()
}
}
| mit | ac955afc4db79b1d3e520a7bc7484c3f | 37.309091 | 117 | 0.646891 | 3.810127 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/view/EmptyLoadingStateView.kt | 1 | 5483 | /*
* ************************************************************************
* EmptyLoadingStateView.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.vlc.gui.view
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.StringRes
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.transition.TransitionManager
import kotlinx.android.synthetic.main.view_empty_loading.view.*
import org.videolan.resources.ACTIVITY_RESULT_PREFERENCES
import org.videolan.vlc.R
import org.videolan.vlc.gui.SecondaryActivity
class EmptyLoadingStateView : FrameLayout {
private val normalConstraintSet = ConstraintSet()
private val compactConstraintSet = ConstraintSet()
lateinit var container: ConstraintLayout
var showNoMedia: Boolean = true
private var compactMode: Boolean = false
set(value) {
field = value
applyCompactMode()
}
var state = EmptyLoadingState.LOADING
set(value) {
loadingFlipper.visibility = if (value == EmptyLoadingState.LOADING) View.VISIBLE else View.GONE
loadingTitle.visibility = if (value == EmptyLoadingState.LOADING) View.VISIBLE else View.GONE
emptyTextView.visibility = if (value == EmptyLoadingState.EMPTY) View.VISIBLE else View.GONE
emptyImageView.visibility = if (value == EmptyLoadingState.EMPTY) View.VISIBLE else View.GONE
noMediaButton.visibility = if (showNoMedia && value == EmptyLoadingState.EMPTY) View.VISIBLE else View.GONE
field = value
}
@StringRes
var emptyText: Int = R.string.nomedia
set(value) {
emptyTextView.text = context.getString(value)
field = emptyText
}
@StringRes
var loadingText: Int = R.string.loading
set(value) {
loadingTitle.text = context.getString(value)
field = emptyText
}
private var noMediaClickListener: (() -> Unit)? = null
fun setOnNoMediaClickListener(l: () -> Unit) {
noMediaClickListener = l
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initialize()
initAttributes(attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
initialize()
initAttributes(attrs, defStyle)
}
private fun initAttributes(attrs: AttributeSet, defStyle: Int) {
attrs.let {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.EmptyLoadingStateView, 0, defStyle)
try {
emptyTextView.text = a.getString(R.styleable.EmptyLoadingStateView_empty_text)
showNoMedia = a.getBoolean(R.styleable.EmptyLoadingStateView_show_no_media, true)
compactMode = a.getBoolean(R.styleable.EmptyLoadingStateView_compact_mode, true)
} catch (e: Exception) {
Log.w("", e.message, e)
} finally {
a.recycle()
}
}
state = EmptyLoadingState.LOADING
noMediaButton.setOnClickListener {
val intent = Intent(context.applicationContext, SecondaryActivity::class.java)
intent.putExtra("fragment", SecondaryActivity.STORAGE_BROWSER)
(context as Activity).startActivityForResult(intent, ACTIVITY_RESULT_PREFERENCES)
noMediaClickListener?.invoke()
}
container = findViewById(R.id.container)
normalConstraintSet.clone(container)
compactConstraintSet.clone(context, R.layout.view_empty_loading_compact)
if (compactMode) {
applyCompactMode()
}
}
private fun applyCompactMode() {
if (!::container.isInitialized) return
TransitionManager.beginDelayedTransition(container)
if (compactMode) compactConstraintSet.applyTo(container) else normalConstraintSet.applyTo(container)
emptyTextView.gravity = if (compactMode) Gravity.START else Gravity.CENTER
}
private fun initialize() {
LayoutInflater.from(context).inflate(R.layout.view_empty_loading, this, true)
}
}
enum class EmptyLoadingState {
LOADING, EMPTY, NONE
} | gpl-2.0 | ab7f479cb72b3e45ab446a0b8e6d64ab | 36.813793 | 119 | 0.664721 | 4.885918 | false | false | false | false |
NextFaze/dev-fun | devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/StringPreprocessor.kt | 1 | 2150 | package com.nextfaze.devfun.compiler
import javax.inject.Inject
import javax.inject.Singleton
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.element.VariableElement
private typealias TypeVar = String.(TypeElement) -> String
private typealias ExeVar = String.(ExecutableElement) -> String
private typealias VarVar = String.(VariableElement) -> String
@Singleton
internal class StringPreprocessor @Inject constructor() {
private val typeVars = listOf<TypeVar>(
{ it -> replace("%CLASS_SN%", it.simpleName.toString()) },
{ it -> replace("%CLASS_QN%", it.qualifiedName.toString()) }
)
private val exeVars = listOf<ExeVar>(
{ it -> replace("%FUN_SN%", it.simpleName.toString()) },
{ it -> replace("%FUN_QN%", it.toString()) }
)
private val varVars = listOf<VarVar>(
{ it -> replace("%VAR_SN%", it.simpleName.toString()) },
{ it -> replace("%VAR_QN%", it.toString()) }
)
fun run(input: String, element: Element?): String {
if (element == null || !input.contains('%')) return input
val executableElement = element as? ExecutableElement
val varElement = element as? VariableElement
val typeElement = element as? TypeElement
?: executableElement?.enclosingElement as? TypeElement
?: varElement?.enclosingElement as? TypeElement
var str = input
if (typeElement != null) {
typeVars.forEach { replace ->
if (!str.contains('%')) return@forEach
str = replace(str, typeElement)
}
}
if (executableElement != null) {
exeVars.forEach { replace ->
if (!str.contains('%')) return@forEach
str = replace(str, executableElement)
}
}
if (varElement != null) {
varVars.forEach { replace ->
if (!str.contains('%')) return@forEach
str = replace(str, varElement)
}
}
return str
}
}
| apache-2.0 | a4b40884ed4d9a4b600c4db00ce39be1 | 33.677419 | 70 | 0.601395 | 4.623656 | false | false | false | false |
dafi/photoshelf | imageviewer/src/main/java/com/ternaryop/photoshelf/imageviewer/util/ImageViewerUtil.kt | 1 | 5007 | package com.ternaryop.photoshelf.imageviewer.util
import android.annotation.TargetApi
import android.app.DownloadManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import androidx.annotation.StringRes
import com.ternaryop.utils.dialog.showErrorDialog
import com.ternaryop.utils.intent.ShareChooserParams
import com.ternaryop.utils.intent.ShareUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
/**
* Created by dave on 20/03/18.
* Functions used by the image viewer to download and share image urls
* Errors and successes are shown using UI elements (eg. dialogs and toasts)
*/
object ImageViewerUtil {
/**
* Download [url] and save the content into the Pictures directory inside the [relativePath].
* [relativePath] can contain subdirectories and must contain the file name
*/
suspend fun download(context: Context, url: String, relativePath: File) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
downloadQ(context, url, relativePath)
} else {
downloadLegacy(context, url, relativePath)
}
}
private fun downloadLegacy(context: Context, url: String, relativePath: File) {
val fileUri = Uri.fromFile(File(getPicturesDirectory(checkNotNull(relativePath.parentFile)), relativePath.name))
val request = DownloadManager.Request(Uri.parse(url))
.setDestinationUri(fileUri)
(context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).enqueue(request)
}
@TargetApi(Build.VERSION_CODES.Q)
private suspend fun downloadQ(context: Context, url: String, relativePath: File) = withContext(Dispatchers.IO) {
val pictureRelativePath = File(Environment.DIRECTORY_PICTURES, relativePath.path)
val values = ContentValues().apply {
put(MediaStore.Images.ImageColumns.DISPLAY_NAME, pictureRelativePath.name)
put(MediaStore.Images.ImageColumns.IS_PENDING, 1)
put(MediaStore.Images.ImageColumns.RELATIVE_PATH, pictureRelativePath.parent)
}
val resolver = context.contentResolver
val destUri = checkNotNull(resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values))
downloadImageUrl(context.contentResolver, URL(url), destUri)
values.clear()
values.put(MediaStore.Downloads.IS_PENDING, 0)
resolver.update(destUri, values, null, null)
}
fun copyToClipboard(context: Context, text: String, label: String, @StringRes resultMessage: Int) {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText(label, text))
Toast.makeText(context, resultMessage, Toast.LENGTH_SHORT).show()
}
suspend fun shareImage(context: Context, imageUrl: URL, shareChooserParams: ShareChooserParams) {
try {
downloadImageUrl(context.contentResolver, imageUrl, shareChooserParams.destFileUri)
ShareUtils.showShareChooser(context, shareChooserParams)
} catch (e: Exception) {
e.showErrorDialog(context)
}
}
fun buildSharePath(context: Context, url: String, subDirectory: String): File {
val cacheDir = File(context.cacheDir, subDirectory).apply { mkdirs() }
return File(cacheDir, buildFileName(url))
}
private suspend fun downloadImageUrl(
contentResolver: ContentResolver,
imageUrl: URL,
uri: Uri
) = withContext(Dispatchers.IO) {
val connection = imageUrl.openConnection() as HttpURLConnection
connection.inputStream.use { stream -> contentResolver.openOutputStream(uri)?.use { os -> stream.copyTo(os) } }
}
fun buildFileName(imageUrl: String, fileName: String? = null): String {
if (fileName == null) {
var nameFromUrl = URI(imageUrl).path
val index = nameFromUrl.lastIndexOf('/')
if (index != -1) {
nameFromUrl = nameFromUrl.substring(index + 1)
}
return nameFromUrl
}
val index = imageUrl.lastIndexOf(".")
// append extension with "."
return if (index != -1) {
fileName + imageUrl.substring(index)
} else fileName
}
private fun getPicturesDirectory(relativePath: File): File {
val fullDirPath = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
relativePath.path
)
if (!fullDirPath.exists()) {
fullDirPath.mkdirs()
}
return fullDirPath
}
}
| mit | e0cd3d8737b793bc4f13e6ac3d866259 | 40.040984 | 120 | 0.699021 | 4.670709 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/playback/external/BasePlaybackActivity.kt | 1 | 3957 | package org.tvheadend.tvhclient.ui.features.playback.external
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.PlayActivityBinding
import org.tvheadend.tvhclient.ui.common.onAttach
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.getThemeId
import timber.log.Timber
abstract class BasePlaybackActivity : AppCompatActivity() {
lateinit var binding: PlayActivityBinding
lateinit var viewModel: ExternalPlayerViewModel
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(getThemeId(this))
super.onCreate(savedInstanceState)
binding = PlayActivityBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.status.setText(R.string.connecting_to_server)
viewModel = ViewModelProvider(this)[ExternalPlayerViewModel::class.java]
viewModel.isConnected.observe(this, { isConnected ->
if (isConnected) {
Timber.d("Received live data, connected to server, requesting ticket")
binding.status.setText(R.string.requesting_playback_information)
viewModel.requestTicketFromServer(intent.extras)
} else {
Timber.d("Received live data, not connected to server")
binding.progressBar.gone()
binding.status.setText(R.string.connection_failed)
}
})
viewModel.isTicketReceived.observe(this, { isTicketReceived ->
Timber.d("Received ticket $isTicketReceived")
if (isTicketReceived) {
binding.progressBar.gone()
binding.status.text = getString(R.string.connected_to_server)
onTicketReceived()
}
})
}
override fun attachBaseContext(context: Context) {
super.attachBaseContext(onAttach(context))
}
protected abstract fun onTicketReceived()
internal fun startExternalPlayer(intent: Intent) {
Timber.d("Starting external player for given intent")
// Start playing the video in the UI thread
this.runOnUiThread {
Timber.d("Getting list of activities that can play the intent")
try {
Timber.d("Found activities, starting external player")
startActivity(intent)
finish()
} catch (ex: ActivityNotFoundException) {
Timber.d("List of available activities is empty, can't start external media player")
binding.status.setText(R.string.no_media_player)
// Show a confirmation dialog before deleting the recording
MaterialDialog(this@BasePlaybackActivity).show {
title(R.string.no_media_player)
message(R.string.show_play_store)
positiveButton(android.R.string.ok) {
try {
Timber.d("Opening play store to download external players")
val installIntent = Intent(Intent.ACTION_VIEW)
installIntent.data = Uri.parse("market://search?q=free%20video%20player&c=apps")
startActivity(installIntent)
} catch (t2: Throwable) {
Timber.d("Could not startPlayback google play store")
} finally {
finish()
}
}
negativeButton(android.R.string.cancel) { finish() }
}
}
}
}
}
| gpl-3.0 | 478d560748c0ea44d7ca5cc23e688bc4 | 40.21875 | 108 | 0.622947 | 5.227213 | false | false | false | false |
masahide318/Croudia-for-Android | app/src/main/kotlin/t/masahide/android/croudia/presenter/TimeLineFragmentPresenter.kt | 1 | 6087 | package t.masahide.android.croudia.presenter
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.ArrayAdapter
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import t.masahide.android.croudia.R
import t.masahide.android.croudia.adapter.TimeLineAdapter
import t.masahide.android.croudia.api.CroudiaAPIService
import t.masahide.android.croudia.api.ServiceCreatable
import t.masahide.android.croudia.api.ServiceCreator
import t.masahide.android.croudia.entitiy.AccessToken
import t.masahide.android.croudia.entitiy.Status
import t.masahide.android.croudia.extensions.onNext
import t.masahide.android.croudia.service.AccessTokenService
import t.masahide.android.croudia.service.IAccessTokenService
import t.masahide.android.croudia.ui.fragment.*
open class TimeLineFragmentPresenter(val fragment: ITimeLineFragmentBase, croudiaAPI: CroudiaAPIService = ServiceCreator.build(), accessTokenService: IAccessTokenService = AccessTokenService()) : APIExecutePresenterBase(croudiaAPI, accessTokenService) {
var nowLoading = false
var sinceId = "0"
var maxId = "0"
fun requestTimeline(sinceId: String = "", maxId: String = "", count: Int = 30, refresh: Boolean = false, pagingRequest: Boolean = false) {
if (nowLoading && !refresh) return
nowLoading = true
refreshToken().subscribe {
timeLineAPI(sinceId, maxId, count)
.compose(fragment.bindToLifecycle<List<Status>>())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onNext {
onNextRequestedTimeLine(it, pagingRequest, refresh)
}
.onError {
onErrorRequestedTimeLine()
}.subscribe()
}
}
fun onErrorRequestedTimeLine() {
nowLoading = false
fragment.finishRefresh()
}
fun onNextRequestedTimeLine(statusList: List<Status>, pagingRequest: Boolean, refresh: Boolean) {
nowLoading = false
if (statusList.first().id.toInt() > sinceId.toInt()) {
sinceId = statusList.first().id
}
if (maxId == "0" || statusList.last().id.toInt() < maxId.toInt()) {
maxId = statusList.last().id
}
if (refresh) {
fragment.finishRefresh()
}
if (pagingRequest) {
fragment.loadedPagignStatus(statusList)
} else {
fragment.loadedStatus(statusList)
}
}
fun loadTimeLineSince() {
requestTimeline(sinceId = sinceId, pagingRequest = true)
}
fun timeLineAPI(sinceId: String, maxId: String, count: Int): Observable<MutableList<Status>> {
when (fragment) {
is PublicTimeLineFragment -> return croudiaAPI.publicTimeLine(accessToken, sinceId, maxId, count)
is HomeTimeLineFragment -> return croudiaAPI.homeTimeLine(accessToken, sinceId, maxId, count)
is ReplyTimeLineFragment -> return croudiaAPI.mentionsTimeLine(accessToken, sinceId, maxId, count)
is FavoriteTimeLineFragment -> return croudiaAPI.favoriteTimeLine(accessToken, sinceId, maxId, count)
else -> throw RuntimeException("unknown fragment")
}
}
fun onScrollChanged(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int, adapter: TimeLineAdapter) {
if ( (visibleItemCount + firstVisibleItem == totalItemCount) && !nowLoading && adapter.count > 0) {
requestTimeline(maxId = maxId, count = 100)
}
}
fun selectListItem(position: Int, id: Long, adapter: TimeLineAdapter, callback: TimelineFragmentBase.Callback) {
val selectedStatus = adapter.getItem(position)
when (id) {
R.id.txtShare.toLong() -> clickShare(selectedStatus)
R.id.favorite.toLong() -> clickFavorite(selectedStatus)
R.id.imgReply.toLong() -> callback.onClickReply(selectedStatus)
R.id.imgDelete.toLong() -> {
clickDelete(selectedStatus)
adapter.remove(selectedStatus)
adapter.notifyDataSetChanged()
}
else -> {
}
}
}
fun refresh() {
sinceId = "0"
maxId = "0"
requestTimeline(refresh = true)
}
fun clickShare(item: Status) {
refreshToken().subscribe {
croudiaAPI.spreadStatus(accessToken, item.id)
.compose(fragment.bindToLifecycle<Status>())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onNext {
fragment.onSuccessShare()
}
.onError {
fragment.onErrorShare()
}.subscribe()
}
}
fun clickFavorite(item: Status) {
refreshToken().subscribe {
croudiaAPI.favoriteCreate(accessToken, item.id)
.compose(fragment.bindToLifecycle<Status>())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onNext {
fragment.onSuccessFavorite()
}
.onError {
fragment.onErrorFavorite()
Log.d("hoge", "favorite")
}.subscribe()
}
}
fun clickDelete(status: Status) {
refreshToken().subscribe {
croudiaAPI.destroyStatus(accessToken, status.id)
.compose(fragment.bindToLifecycle<Status>())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onNext {
}
.onError {
}.subscribe()
}
}
} | apache-2.0 | 6f00eed442aa60066352f8ebecd94e5d | 38.277419 | 253 | 0.605717 | 4.920776 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/sponge/inspection/suppress/SpongeGetterParamOptionalInspectionSuppressor.kt | 1 | 1445 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.inspection.suppress
import com.demonwav.mcdev.platform.sponge.util.SpongeConstants
import com.demonwav.mcdev.platform.sponge.util.isValidSpongeListener
import com.demonwav.mcdev.util.findContainingMethod
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiParameter
import com.intellij.psi.PsiTypeElement
import com.intellij.psi.util.parentOfTypes
class SpongeGetterParamOptionalInspectionSuppressor : InspectionSuppressor {
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId != INSPECTION || element !is PsiTypeElement) {
return false
}
val param = element.parentOfTypes(PsiParameter::class) ?: return false
val method = param.findContainingMethod() ?: return false
if (!method.isValidSpongeListener()) {
return false
}
return param.hasAnnotation(SpongeConstants.GETTER_ANNOTATION)
}
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<out SuppressQuickFix> =
SuppressQuickFix.EMPTY_ARRAY
companion object {
const val INSPECTION = "OptionalUsedAsFieldOrParameterType"
}
}
| mit | 55812f3e6827c1f138bf943a2f057da4 | 31.111111 | 104 | 0.748789 | 4.784768 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/settings/AemSettings.kt | 1 | 719 | package co.nums.intellij.aem.settings
import co.nums.intellij.aem.extensions.getService
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.XmlSerializerUtil
@State(name = "AemSettings")
class AemSettings : PersistentStateComponent<AemSettings> {
var aemSupportEnabled: Boolean = true
var aemVersion: String = AemVersion.values().last().aem
var htlVersion: String = AemVersion.values().last().htl
var manualVersionsEnabled: Boolean = false
override fun getState() = this
override fun loadState(state: AemSettings) = XmlSerializerUtil.copyBean(state, this)
}
val Project.aemSettings: AemSettings?
get() = getService(this)
| gpl-3.0 | 88a3964458f3de550e8d04cc5dabd0de | 30.26087 | 88 | 0.769124 | 4.180233 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/reviewer/ActionButtons.kt | 1 | 3644 | /*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.reviewer
import android.content.SharedPreferences
import android.view.Menu
import android.view.MenuItem
import androidx.annotation.IdRes
import com.ichi2.anki.R
import com.ichi2.ui.ActionBarOverflow
import timber.log.Timber
class ActionButtons(reviewerUi: ReviewerUi) {
// DEFECT: This should be private - it breaks the law of demeter, but it'll be a large refactoring to get
// to this point
val status: ActionButtonStatus
private var mMenu: Menu? = null
fun setup(preferences: SharedPreferences) {
status.setup(preferences)
}
/** Sets the order of the Action Buttons in the action bar */
fun setCustomButtonsStatus(menu: Menu) {
status.setCustomButtons(menu)
mMenu = menu
}
fun isShownInActionBar(@IdRes resId: Int): Boolean? {
val menuItem = findMenuItem(resId) ?: return null
// firstly, see if we can definitively determine whether the action is visible.
val isActionButton = ActionBarOverflow.isActionButton(menuItem)
return isActionButton ?: isLikelyActionButton(resId)
// If not, use heuristics based on preferences.
}
private fun findMenuItem(@IdRes resId: Int): MenuItem? {
return if (mMenu == null) {
null
} else mMenu!!.findItem(resId)
}
private fun isLikelyActionButton(@IdRes resourceId: Int): Boolean {
/*
https://github.com/ankidroid/Anki-Android/pull/5918#issuecomment-609484093
Heuristic approach: Show the item in the top bar unless the corresponding menu item is set to "always" show.
There are two scenarios where the heuristic fails:
1. An item is set to 'if room' but is actually visible in the toolbar
2. An item is set to 'always' but is actually not visible in the toolbar
Failure scenario one is totally acceptable IMO as it just falls back to the current behavior.
Failure scenario two is not ideal, but it should only happen in the pathological case where the user has gone
and explicitly changed the preferences to set more items to 'always' than there is room for in the toolbar.
In any case, both failure scenarios only happen if the user deviated from the default settings in strange ways.
*/
val status = status.getByMenuResourceId(resourceId)
if (status == null) {
Timber.w("Failed to get status for resource: %d", resourceId)
// If we return "true", we may hide the flag/mark status completely. False is safer.
return false
}
return status == ActionButtonStatus.SHOW_AS_ACTION_ALWAYS
}
companion object {
@JvmField
@IdRes
val RES_FLAG = R.id.action_flag
@JvmField
@IdRes
val RES_MARK = R.id.action_mark_card
}
init {
status = ActionButtonStatus(reviewerUi)
}
}
| gpl-3.0 | ee0ddb3c4f6e2649e40c26c8e60793cb | 38.182796 | 119 | 0.689078 | 4.42233 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/MenuTab.kt | 1 | 1639 | package com.pennapps.labs.pennmobile
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ExpandableListView
import androidx.fragment.app.Fragment
import com.pennapps.labs.pennmobile.adapters.MenuAdapter
import kotlinx.android.synthetic.main.fragment_menu_tab.view.*
import java.util.*
class MenuTab : Fragment() {
var meal: String? = null
var stationInfo = HashMap<String, List<String>?>() // {station name: foods}
private lateinit var stations: ArrayList<String>
private lateinit var name: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments
name = args?.getString(getString(R.string.menu_arg_name), "Dining Hall") ?: "Dining Hall"
meal = args?.getString(getString(R.string.menu_arg_meal), "Meal")
stations = args?.getStringArrayList(getString(R.string.menu_arg_stations)) ?: ArrayList()
for (station in stations) {
stationInfo[station] = args?.getStringArrayList(station)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_menu_tab, container, false)
val elv : ExpandableListView = v.station_list
elv.setFooterDividersEnabled(true)
elv.addFooterView(View(elv.context))
elv.setAdapter(activity?.let { MenuAdapter(it, stations, stationInfo) })
v.setBackgroundColor(Color.WHITE)
return v
}
} | mit | f0e0e18e413832175403f892bffe076f | 39 | 116 | 0.717511 | 4.224227 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/AlipayPaymentNativeActivity.kt | 1 | 4686 | package com.stripe.example.activity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.alipay.sdk.app.PayTask
import com.stripe.android.ApiResultCallback
import com.stripe.android.PaymentConfiguration
import com.stripe.android.PaymentIntentResult
import com.stripe.android.Stripe
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.MandateDataParams
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.model.StripeIntent
import com.stripe.example.R
import com.stripe.example.databinding.PaymentExampleActivityBinding
import org.json.JSONObject
class AlipayPaymentNativeActivity : StripeIntentActivity() {
private val viewBinding: PaymentExampleActivityBinding by lazy {
PaymentExampleActivityBinding.inflate(layoutInflater)
}
private val stripe: Stripe by lazy {
Stripe(
applicationContext,
PaymentConfiguration.getInstance(applicationContext).publishableKey
)
}
private var clientSecret: String? = null
private var confirmed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
viewBinding.confirmWithPaymentButton.text =
resources.getString(R.string.confirm_alipay_button)
viewBinding.paymentExampleIntro.text =
resources.getString(R.string.alipay_example_intro)
viewModel.inProgress.observe(this) { enableUi(!it) }
viewModel.status.observe(this, Observer(viewBinding.status::setText))
viewBinding.confirmWithPaymentButton.setOnClickListener {
clientSecret?.let {
// If we already loaded the Payment Intent and haven't confirmed, try again
if (!confirmed) {
updateStatus("\n\nPayment Intent already created, trying to confirm")
confirmPayment(it)
}
} ?: run {
createAndConfirmPaymentIntent(
country = "US",
paymentMethodCreateParams = PaymentMethodCreateParams.createAlipay(),
supportedPaymentMethods = "alipay"
)
}
}
}
override fun handleCreatePaymentIntentResponse(
responseData: JSONObject,
params: PaymentMethodCreateParams?,
shippingDetails: ConfirmPaymentIntentParams.Shipping?,
stripeAccountId: String?,
existingPaymentMethodId: String?,
mandateDataParams: MandateDataParams?,
onPaymentIntentCreated: (String) -> Unit
) {
viewModel.status.value +=
"\n\nStarting PaymentIntent confirmation" +
(
stripeAccountId?.let {
" for $it"
} ?: ""
)
clientSecret = responseData.getString("secret").also {
confirmPayment(it)
}
}
private fun confirmPayment(clientSecret: String) {
stripe.confirmAlipayPayment(
confirmPaymentIntentParams = ConfirmPaymentIntentParams.createAlipay(clientSecret),
authenticator = { data ->
PayTask(this).payV2(data, true)
},
callback = object : ApiResultCallback<PaymentIntentResult> {
override fun onSuccess(result: PaymentIntentResult) {
val paymentIntent = result.intent
when (paymentIntent.status) {
StripeIntent.Status.Succeeded -> {
confirmed = true
updateStatus("\n\nPayment succeeded")
}
StripeIntent.Status.RequiresAction ->
updateStatus("\n\nUser canceled confirmation")
else ->
updateStatus(
"\n\nPayment failed or canceled." +
"\nStatus: ${paymentIntent.status}"
)
}
}
override fun onError(e: Exception) {
updateStatus("\n\nError: ${e.message}")
}
}
)
}
private fun updateStatus(appendMessage: String) {
viewModel.status.value += appendMessage
viewModel.inProgress.postValue(false)
}
private fun enableUi(enable: Boolean) {
viewBinding.progressBar.visibility = if (enable) View.INVISIBLE else View.VISIBLE
viewBinding.confirmWithPaymentButton.isEnabled = enable
}
}
| mit | e154a1e1dd43feff01d45428f02fa551 | 36.190476 | 95 | 0.609902 | 5.70073 | false | false | false | false |
smrehan6/WeatherForecast | app/src/main/java/me/smr/weatherforecast/api/WeatherAPI.kt | 1 | 1346 | package me.smr.weatherforecast.api
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
interface WeatherAPI {
@GET("find?type=like&APPID=$APP_ID")
suspend fun searchCity(@Query("q") name: String): SearchResponse
@GET("group?units=metric&APPID=$APP_ID")
suspend fun getWeatherData(@Query("id") id: String): WeatherResponse
@GET("forecast/daily?cnt=16&units=metric&APPID=$APP_ID")
suspend fun fetchForecast(@Query("id") id: String): ForecastResponse
companion object {
private const val APP_ID = "e1ec7985dbbd4af7f73ae7d3bb99453a"
const val BASE_URL = "https://api.openweathermap.org/data/2.5/"
operator fun invoke(): WeatherAPI {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().addInterceptor(logger).build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(WeatherAPI::class.java)
}
}
} | apache-2.0 | 22ff6ff7fc7d0b983257c252915aa546 | 33.538462 | 78 | 0.682764 | 4.20625 | false | false | false | false |
AndroidX/androidx | wear/watchface/watchface-client/src/main/java/androidx/wear/watchface/client/WatchFaceMetadataClient.kt | 3 | 21858 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.client
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.graphics.RectF
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.annotation.RestrictTo
import androidx.wear.watchface.BoundingArc
import androidx.wear.watchface.complications.ComplicationSlotBounds
import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.utility.AsyncTraceEvent
import androidx.wear.watchface.utility.TraceEvent
import androidx.wear.watchface.client.WatchFaceControlClient.Companion.createWatchFaceControlClient
import androidx.wear.watchface.control.IWatchFaceControlService
import androidx.wear.watchface.control.WatchFaceControlService
import androidx.wear.watchface.control.data.GetComplicationSlotMetadataParams
import androidx.wear.watchface.control.data.GetUserStyleSchemaParams
import androidx.wear.watchface.control.data.HeadlessWatchFaceInstanceParams
import androidx.wear.watchface.ComplicationSlotBoundsType
import androidx.wear.watchface.WatchFaceService
import androidx.wear.watchface.XmlSchemaAndComplicationSlotsDefinition
import androidx.wear.watchface.complications.data.ComplicationExperimental
import androidx.wear.watchface.control.data.GetUserStyleFlavorsParams
import androidx.wear.watchface.style.UserStyleFlavors
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting
import androidx.wear.watchface.style.UserStyleSetting.ComplicationSlotsUserStyleSetting.ComplicationSlotOverlay
import kotlinx.coroutines.CompletableDeferred
/**
* Interface for fetching watch face metadata. E.g. the [UserStyleSchema] and
* [ComplicationSlotMetadata]. This must be [close]d after use to release resources.
*/
public interface WatchFaceMetadataClient : AutoCloseable {
public companion object {
/** @hide */
private const val TAG = "WatchFaceMetadataClient"
/**
* Constructs a [WatchFaceMetadataClient] for fetching metadata for the specified watch
* face.
*
* @param context Calling application's [Context].
* @param watchFaceName The [ComponentName] of the watch face to fetch meta data from.
* @return The [WatchFaceMetadataClient] if there is one.
* @throws [ServiceNotBoundException] if the underlying watch face control service can not
* be bound or a [ServiceStartFailureException] if the watch face dies during startup. If
* the service's manifest contains an
* androidx.wear.watchface.XmlSchemaAndComplicationSlotsDefinition meta data node then
* [PackageManager.NameNotFoundException] is thrown if [watchFaceName] is invalid.
*/
@Throws(
ServiceNotBoundException::class,
ServiceStartFailureException::class,
PackageManager.NameNotFoundException::class
)
@SuppressWarnings("MissingJvmstatic") // Can't really call a suspend fun from java.
public suspend fun create(
context: Context,
watchFaceName: ComponentName
): WatchFaceMetadataClient {
// Fallback to binding the service (slow).
return createImpl(
context,
Intent(WatchFaceControlService.ACTION_WATCHFACE_CONTROL_SERVICE).apply {
setPackage(watchFaceName.packageName)
},
watchFaceName,
ParserProvider()
)
}
/** @hide */
private const val ANDROIDX_WATCHFACE_XML_VERSION = "androidx.wear.watchface.xml_version"
/** @hide */
private const val ANDROIDX_WATCHFACE_CONTROL_SERVICE =
"androidx.wear.watchface.control.WatchFaceControlService"
@Suppress("DEPRECATION") // getServiceInfo
internal fun isXmlVersionCompatible(
context: Context,
resources: Resources,
controlServicePackage: String,
controlServiceName: String = ANDROIDX_WATCHFACE_CONTROL_SERVICE
): Boolean {
val controlServiceComponentName = ComponentName(
controlServicePackage,
controlServiceName)
val version = try {
context.packageManager.getServiceInfo(
controlServiceComponentName,
PackageManager.GET_META_DATA or PackageManager.MATCH_DISABLED_COMPONENTS
).metaData.getInt(ANDROIDX_WATCHFACE_XML_VERSION, 0)
} catch (exception: PackageManager.NameNotFoundException) {
// WatchFaceControlService may be missing in case WF is built with
// pre-androidx watchface library.
return false
}
val ourVersion = resources.getInteger(
androidx.wear.watchface.R.integer.watch_face_xml_version)
if (version > ourVersion) {
Log.w(TAG, "WatchFaceControlService version ($version) " +
"of $controlServiceComponentName is higher than $ourVersion")
return false
}
return true
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@Suppress("DEPRECATION")
open class ParserProvider {
// Open to allow testing without having to install the sample app.
open fun getParser(context: Context, watchFaceName: ComponentName): XmlResourceParser? {
if (!isXmlVersionCompatible(context, context.resources, watchFaceName.packageName))
return null
return context.packageManager.getServiceInfo(
watchFaceName,
PackageManager.GET_META_DATA
).loadXmlMetaData(
context.packageManager,
WatchFaceService.XML_WATCH_FACE_METADATA
)
}
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@Suppress("ShowingMemberInHiddenClass") // Spurious warning about exposing the
// 'hidden' companion object, which _isn't_ hidden.
public suspend fun createImpl(
context: Context,
intent: Intent,
watchFaceName: ComponentName,
parserProvider: ParserProvider
): WatchFaceMetadataClient {
// Check if there's static metadata we can read (fast).
parserProvider.getParser(context, watchFaceName)?.let {
return XmlWatchFaceMetadataClientImpl(
XmlSchemaAndComplicationSlotsDefinition.inflate(
context.packageManager.getResourcesForApplication(
watchFaceName.packageName
),
it
)
)
}
val deferredService = CompletableDeferred<IWatchFaceControlService>()
val traceEvent = AsyncTraceEvent("WatchFaceMetadataClientImpl.bindService")
val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
traceEvent.close()
deferredService.complete(IWatchFaceControlService.Stub.asInterface(binder))
}
override fun onServiceDisconnected(name: ComponentName?) {
// Note if onServiceConnected is called first completeExceptionally will do
// nothing because the CompletableDeferred is already completed.
traceEvent.close()
deferredService.completeExceptionally(ServiceStartFailureException())
}
}
if (!BindHelper.bindService(context, intent, serviceConnection)) {
traceEvent.close()
throw ServiceNotBoundException()
}
return WatchFaceMetadataClientImpl(
context,
deferredService.await(),
serviceConnection,
watchFaceName
)
}
}
/**
* Exception thrown by [createWatchFaceControlClient] if the remote service can't be bound.
*/
public class ServiceNotBoundException : Exception()
/** Exception thrown by [WatchFaceControlClient] methods if the service dies during start up. */
public class ServiceStartFailureException(message: String = "") : Exception(message)
/**
* Returns the watch face's [UserStyleSchema].
*
* @throws [RuntimeException] if the watch face threw an exception while trying to service the
* request or there was a communication problem with watch face process.
*/
public fun getUserStyleSchema(): UserStyleSchema
/**
* Whether or not the [UserStyleSchema] is static and won't change unless the APK is updated.
*/
@Suppress("INAPPLICABLE_JVM_NAME")
@get:JvmName("isUserStyleSchemaStatic")
public val isUserStyleSchemaStatic: Boolean
/**
* Returns a map of [androidx.wear.watchface.ComplicationSlot] ID to [ComplicationSlotMetadata]
* for each slot in the watch face's [androidx.wear.watchface.ComplicationSlotsManager].
*
* @throws [RuntimeException] if the watch face threw an exception while trying to service the
* request or there was a communication problem with watch face process.
*/
public fun getComplicationSlotMetadataMap(): Map<Int, ComplicationSlotMetadata>
/**
* Returns the watch face's [UserStyleFlavors].
*
* @throws [RuntimeException] if the watch face threw an exception while trying to service the
* request or there was a communication problem with watch face process.
*/
public fun getUserStyleFlavors(): UserStyleFlavors
}
/**
* Static metadata for a [androidx.wear.watchface.ComplicationSlot].
*
* @property bounds The complication slot's [ComplicationSlotBounds]. Only non `null` for watch
* faces with a new enough [androidx.wear.watchface.control.WatchFaceControlService].
* @property boundsType The [ComplicationSlotBoundsType] of the complication slot.
* @property supportedTypes The list of [ComplicationType]s accepted by this complication slot. Used
* during complication data source selection, this list should be non-empty.
* @property defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] which controls the
* initial complication data source when the watch face is first installed.
* @property isInitiallyEnabled At creation a complication slot is either enabled or disabled. This
* can be overridden by a [ComplicationSlotsUserStyleSetting] (see
* [ComplicationSlotOverlay.enabled]).
* Editors need to know the initial state of a complication slot to predict the effects of making a
* style change.
* @property fixedComplicationDataSource Whether or not the complication slot's complication data
* source is fixed (i.e. can't be changed by the user). This is useful for watch faces built
* around specific complication complication data sources.
* @property complicationConfigExtras Extras to be merged into the Intent sent when invoking the
* complication data source chooser activity.
*/
public class ComplicationSlotMetadata
@ComplicationExperimental constructor(
public val bounds: ComplicationSlotBounds?,
@ComplicationSlotBoundsType public val boundsType: Int,
public val supportedTypes: List<ComplicationType>,
public val defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy,
@get:JvmName("isInitiallyEnabled")
public val isInitiallyEnabled: Boolean,
public val fixedComplicationDataSource: Boolean,
public val complicationConfigExtras: Bundle,
private val boundingArc: BoundingArc?
) {
/**
* The optional [BoundingArc] for an edge complication if specified, or `null` otherwise.
*/
// TODO(b/230364881): Make this a normal primary constructor property when BoundingArc is no
// longer experimental.
@ComplicationExperimental
public fun getBoundingArc(): BoundingArc? = boundingArc
/**
* Constructs a [ComplicationSlotMetadata].
*
* @param bounds The complication slot's [ComplicationSlotBounds]. Only non `null` for watch faces
* with a new enough [androidx.wear.watchface.control.WatchFaceControlService].
* @param boundsType The [ComplicationSlotBoundsType] of the complication slot.
* @param supportedTypes The list of [ComplicationType]s accepted by this complication slot. Used
* during complication data source selection, this list should be non-empty.
* @param defaultDataSourcePolicy The [DefaultComplicationDataSourcePolicy] which controls the
* initial complication data source when the watch face is first installed.
* @param isInitiallyEnabled At creation a complication slot is either enabled or disabled. This
* can be overridden by a [ComplicationSlotsUserStyleSetting] (see
* [ComplicationSlotOverlay.enabled]).
* Editors need to know the initial state of a complication slot to predict the effects of making a
* style change.
* @param fixedComplicationDataSource Whether or not the complication slot's complication data
* source is fixed (i.e. can't be changed by the user). This is useful for watch faces built
* around specific complication complication data sources.
* @param complicationConfigExtras Extras to be merged into the Intent sent when invoking the
* complication data source chooser activity.
*/
// TODO(b/230364881): Deprecate when BoundingArc is no longer experimental.
@OptIn(ComplicationExperimental::class)
constructor(
bounds: ComplicationSlotBounds?,
@ComplicationSlotBoundsType boundsType: Int,
supportedTypes: List<ComplicationType>,
defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy,
isInitiallyEnabled: Boolean,
fixedComplicationDataSource: Boolean,
complicationConfigExtras: Bundle
) : this(
bounds,
boundsType,
supportedTypes,
defaultDataSourcePolicy,
isInitiallyEnabled,
fixedComplicationDataSource,
complicationConfigExtras,
null
)
}
internal class WatchFaceMetadataClientImpl internal constructor(
private val context: Context,
private val service: IWatchFaceControlService,
private val serviceConnection: ServiceConnection,
private val watchFaceName: ComponentName
) : WatchFaceMetadataClient {
private var closed = false
private val headlessClientDelegate = lazy {
createHeadlessWatchFaceClient(
watchFaceName
) ?: throw WatchFaceMetadataClient.ServiceStartFailureException(
"Could not open headless client for ${watchFaceName.flattenToString()}"
)
}
private val headlessClient by headlessClientDelegate
private fun createHeadlessWatchFaceClient(
watchFaceName: ComponentName
): HeadlessWatchFaceClient? = TraceEvent(
"WatchFaceMetadataClientImpl.createHeadlessWatchFaceClient"
).use {
requireNotClosed()
return service.createHeadlessWatchFaceInstance(
HeadlessWatchFaceInstanceParams(
watchFaceName,
androidx.wear.watchface.data.DeviceConfig(false, false, 0, 0),
1,
1,
null
)
)?.let {
HeadlessWatchFaceClientImpl(it)
}
}
private fun requireNotClosed() {
require(!closed) {
"WatchFaceMetadataClient method called after close"
}
}
override fun getUserStyleSchema(): UserStyleSchema =
callRemote {
if (service.apiVersion >= 3) {
UserStyleSchema(service.getUserStyleSchema(GetUserStyleSchemaParams(watchFaceName)))
} else {
headlessClient.userStyleSchema
}
}
override val isUserStyleSchemaStatic: Boolean
get() = false
@OptIn(ComplicationExperimental::class)
override fun getComplicationSlotMetadataMap(): Map<Int, ComplicationSlotMetadata> {
requireNotClosed()
return callRemote {
if (service.apiVersion >= 3) {
val wireFormat = service.getComplicationSlotMetadata(
GetComplicationSlotMetadataParams(watchFaceName)
)
wireFormat.associateBy(
{ it.id },
{
val perSlotBounds = HashMap<ComplicationType, RectF>()
val perSlotMargins = HashMap<ComplicationType, RectF>()
for (i in it.complicationBoundsType.indices) {
val type = ComplicationType.fromWireType(it.complicationBoundsType[i])
perSlotBounds[type] = it.complicationBounds[i] ?: RectF()
perSlotMargins[type] = it.complicationMargins?.get(i) ?: RectF()
}
ComplicationSlotMetadata(
ComplicationSlotBounds.createFromPartialMap(
perSlotBounds,
perSlotMargins
),
it.boundsType,
it.supportedTypes.map { ComplicationType.fromWireType(it) },
DefaultComplicationDataSourcePolicy(
it.defaultDataSourcesToTry ?: emptyList(),
it.fallbackSystemDataSource,
ComplicationType.fromWireType(
it.primaryDataSourceDefaultType
),
ComplicationType.fromWireType(
it.secondaryDataSourceDefaultType
),
ComplicationType.fromWireType(it.defaultDataSourceType)
),
it.isInitiallyEnabled,
it.isFixedComplicationDataSource,
it.complicationConfigExtras,
it.boundingArc?.let { arc ->
BoundingArc(arc.arcStartAngle, arc.totalArcAngle, arc.arcThickness)
}
)
}
)
} else {
headlessClient.complicationSlotsState.mapValues {
ComplicationSlotMetadata(
null,
it.value.boundsType,
it.value.supportedTypes,
it.value.defaultDataSourcePolicy,
it.value.isInitiallyEnabled,
it.value.fixedComplicationDataSource,
it.value.complicationConfigExtras,
null
)
}
}
}
}
override fun getUserStyleFlavors(): UserStyleFlavors = callRemote {
if (service.apiVersion >= 5) {
UserStyleFlavors(
service.getUserStyleFlavors(
GetUserStyleFlavorsParams(watchFaceName)
)
)
} else {
UserStyleFlavors()
}
}
override fun close() = TraceEvent("WatchFaceMetadataClientImpl.close").use {
closed = true
if (headlessClientDelegate.isInitialized()) {
headlessClient.close()
}
context.unbindService(serviceConnection)
}
}
internal class XmlWatchFaceMetadataClientImpl(
private val xmlSchemaAndComplicationSlotsDefinition: XmlSchemaAndComplicationSlotsDefinition
) : WatchFaceMetadataClient {
override fun getUserStyleSchema() =
xmlSchemaAndComplicationSlotsDefinition.schema ?: UserStyleSchema(emptyList())
override val isUserStyleSchemaStatic: Boolean
get() = true
@OptIn(ComplicationExperimental::class)
override fun getComplicationSlotMetadataMap() =
xmlSchemaAndComplicationSlotsDefinition.complicationSlots.associateBy(
{ it.slotId },
{
ComplicationSlotMetadata(
it.bounds,
it.boundsType,
it.supportedTypes,
it.defaultDataSourcePolicy,
it.initiallyEnabled,
it.fixedComplicationDataSource,
Bundle(),
it.boundingArc
)
}
)
override fun getUserStyleFlavors() =
xmlSchemaAndComplicationSlotsDefinition.flavors ?: UserStyleFlavors()
override fun close() {}
}
| apache-2.0 | cac1d3f3546c1ca2d209562363c7d450 | 42.891566 | 111 | 0.651478 | 5.670039 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/items/strategies/SingleDropStrategy.kt | 1 | 12850 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2020 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.items.strategies
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGenerationReason
import com.tealcube.minecraft.bukkit.mythicdrops.events.CustomItemGenerationEvent
import com.tealcube.minecraft.bukkit.mythicdrops.identification.IdentityTome
import com.tealcube.minecraft.bukkit.mythicdrops.identification.UnidentifiedItem
import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicDropTracker
import com.tealcube.minecraft.bukkit.mythicdrops.items.builders.MythicDropBuilder
import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketExtender
import com.tealcube.minecraft.bukkit.mythicdrops.socketing.SocketItem
import com.tealcube.minecraft.bukkit.mythicdrops.utils.GemUtil
import io.pixeloutlaw.minecraft.spigot.mythicdrops.getMaterials
import io.pixeloutlaw.minecraft.spigot.mythicdrops.getTier
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.entity.LivingEntity
import org.bukkit.event.entity.CreatureSpawnEvent
import org.bukkit.event.entity.EntityDeathEvent
import org.bukkit.inventory.ItemStack
import kotlin.random.Random
// Default drop strategy for MythicDrops
class SingleDropStrategy(
private val mythicDrops: MythicDrops
) : AbstractDropStrategy() {
companion object {
private const val ONE_HUNDRED_PERCENT = 1.0
private const val ONE_HUNDRED_TEN_PERCENT = 1.1
}
override val name: String = "single"
override val itemChance: Double
get() =
mythicDrops.settingsManager.configSettings.drops.itemChance
override val tieredItemChance: Double
get() =
itemChance * mythicDrops.settingsManager.configSettings.drops.tieredItemChance
override val customItemChance: Double
get() =
itemChance *
(1.0 - mythicDrops.settingsManager.configSettings.drops.tieredItemChance) *
mythicDrops.settingsManager.configSettings.drops.customItemChance
override val socketGemChance: Double
get() =
itemChance *
(1.0 - mythicDrops.settingsManager.configSettings.drops.tieredItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.customItemChance) *
mythicDrops.settingsManager.configSettings.drops.socketGemChance
override val unidentifiedItemChance: Double
get() =
itemChance *
(1.0 - mythicDrops.settingsManager.configSettings.drops.tieredItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.customItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.socketGemChance) *
mythicDrops.settingsManager.configSettings.drops.unidentifiedItemChance
override val identityTomeChance: Double
get() =
itemChance *
(1.0 - mythicDrops.settingsManager.configSettings.drops.tieredItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.customItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.socketGemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.unidentifiedItemChance) *
mythicDrops.settingsManager.configSettings.drops.identityTomeChance
override val socketExtenderChance: Double
get() =
itemChance *
(1.0 - mythicDrops.settingsManager.configSettings.drops.tieredItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.customItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.socketGemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.unidentifiedItemChance) *
(1.0 - mythicDrops.settingsManager.configSettings.drops.identityTomeChance) *
mythicDrops.settingsManager.configSettings.drops.socketExtenderChance
override fun getDropsForCreatureSpawnEvent(event: CreatureSpawnEvent): List<Pair<ItemStack, Double>> {
val entity = event.entity
val location = event.location
return getDropsForEntityAndLocation(entity, location)
}
override fun getDropsForEntityDeathEvent(event: EntityDeathEvent): List<Pair<ItemStack, Double>> {
val entity = event.entity
val location = entity.location
return getDropsForEntityAndLocation(entity, location)
}
@Suppress("detekt.ComplexMethod", "detekt.LongMethod")
private fun getDropsForEntityAndLocation(
entity: LivingEntity,
location: Location
): List<Pair<ItemStack, Double>> {
val itemChance = mythicDrops.settingsManager.configSettings.drops.itemChance
val creatureSpawningMultiplier = mythicDrops
.settingsManager
.creatureSpawningSettings
.dropMultipliers[entity.type] ?: 0.0
val itemChanceMultiplied = itemChance * creatureSpawningMultiplier
val itemRoll = Random.nextDouble(0.0, 1.0)
if (itemRoll > itemChanceMultiplied) {
return emptyList()
}
MythicDropTracker.item()
val (
tieredItemChance,
customItemChance,
socketGemChance,
unidentifiedItemChance,
identityTomeChance,
socketExtenderChance
) = getDropChances(
mythicDrops.settingsManager.configSettings.drops
)
val socketingEnabled = mythicDrops.settingsManager.configSettings.components.isSocketingEnabled
val identifyingEnabled = mythicDrops.settingsManager.configSettings.components.isIdentifyingEnabled
val tieredItemRoll = Random.nextDouble(0.0, 1.0)
val customItemRoll = Random.nextDouble(0.0, 1.0)
val socketGemRoll = Random.nextDouble(0.0, 1.0)
val unidentifiedItemRoll = Random.nextDouble(0.0, 1.0)
val identityTomeRoll = Random.nextDouble(0.0, 1.0)
val socketExtenderRoll = Random.nextDouble(0.0, 1.0)
// this is here to maintain previous behavior
val tieredItemChanceMultiplied = tieredItemChance * creatureSpawningMultiplier
var itemStack: ItemStack? = null
// due to the way that spigot/minecraft handles drop chances, it won't drop items with a 100% drop chance
// if a player isn't the one that killed it.
var dropChance = if (mythicDrops.settingsManager.configSettings.options.isRequirePlayerKillForDrops) {
ONE_HUNDRED_PERCENT
} else {
ONE_HUNDRED_TEN_PERCENT
}
// check WorldGuard flags
val (
tieredAllowedAtLocation,
customItemAllowedAtLocation,
socketGemAllowedAtLocation,
unidentifiedItemAllowedAtLocation,
identityTomeAllowedAtLocation,
socketExtenderAllowedAtLocation
) = getWorldGuardFlags(location)
if (tieredItemRoll <= tieredItemChanceMultiplied && tieredAllowedAtLocation) {
MythicDropTracker.tieredItem()
val pair = getTieredDrop(entity, itemStack, dropChance)
dropChance = pair.first
itemStack = pair.second
} else if (customItemRoll < customItemChance && customItemAllowedAtLocation) {
MythicDropTracker.customItem()
val pair = getCustomItemDrop(itemStack, dropChance)
dropChance = pair.first
itemStack = pair.second
} else if (socketingEnabled && socketGemRoll <= socketGemChance && socketGemAllowedAtLocation) {
MythicDropTracker.socketGem()
itemStack = getSocketGemDrop(entity, itemStack)
} else if (
identifyingEnabled && unidentifiedItemRoll <= unidentifiedItemChance &&
unidentifiedItemAllowedAtLocation
) {
MythicDropTracker.unidentifiedItem()
itemStack = getUnidentifiedItemDrop(itemStack, entity)
} else if (identifyingEnabled && identityTomeRoll <= identityTomeChance && identityTomeAllowedAtLocation) {
MythicDropTracker.identityTome()
itemStack = IdentityTome(mythicDrops.settingsManager.identifyingSettings.items.identityTome)
} else if (socketingEnabled && socketExtenderRoll <= socketExtenderChance && socketExtenderAllowedAtLocation) {
mythicDrops.settingsManager.socketingSettings.options.socketExtenderMaterialIds.randomOrNull()?.let {
MythicDropTracker.socketExtender()
itemStack = SocketExtender(it, mythicDrops.settingsManager.socketingSettings.items.socketExtender)
}
}
return itemStack?.let { listOf(it to dropChance) } ?: emptyList()
}
private fun getUnidentifiedItemDrop(
itemStack: ItemStack?,
entity: LivingEntity
): ItemStack? {
val allowableTiersForEntity =
mythicDrops.settingsManager.creatureSpawningSettings.tierDrops[entity.type] ?: emptyList()
return mythicDrops.tierManager.randomByIdentityWeight { allowableTiersForEntity.contains(it.name) }
?.let { randomizedTier ->
randomizedTier.getMaterials().randomOrNull()?.let { material ->
UnidentifiedItem.build(
mythicDrops.settingsManager.creatureSpawningSettings,
mythicDrops.settingsManager.languageSettings.displayNames,
material,
mythicDrops.tierManager,
mythicDrops.settingsManager.identifyingSettings.items.unidentifiedItem,
entity.type,
randomizedTier
)
}
} ?: itemStack
}
private fun getSocketGemDrop(
entity: LivingEntity,
itemStack: ItemStack?
): ItemStack? {
var itemStack1 = itemStack
val socketGem = GemUtil.getRandomSocketGemByWeight(entity.type)
val material = GemUtil.getRandomSocketGemMaterial()
if (socketGem != null && material != null) {
itemStack1 =
SocketItem(material, socketGem, mythicDrops.settingsManager.socketingSettings.items.socketGem)
}
return itemStack1
}
private fun getCustomItemDrop(
itemStack: ItemStack?,
dropChance: Double
): Pair<Double, ItemStack?> {
var customItemItemStack = itemStack
var customItemDropChance = dropChance
mythicDrops.customItemManager.randomByWeight()?.let {
val customItemGenerationEvent =
CustomItemGenerationEvent(it, it.toItemStack(mythicDrops.customEnchantmentRegistry))
Bukkit.getPluginManager().callEvent(customItemGenerationEvent)
if (!customItemGenerationEvent.isCancelled) {
customItemItemStack = customItemGenerationEvent.result
customItemDropChance = it.chanceToDropOnDeath
}
}
return Pair(customItemDropChance, customItemItemStack)
}
private fun getTieredDrop(
entity: LivingEntity,
itemStack: ItemStack?,
dropChance: Double
): Pair<Double, ItemStack?> {
return entity.getTier(
mythicDrops.settingsManager.creatureSpawningSettings,
mythicDrops.tierManager
)?.let {
it.chanceToDropOnMonsterDeath to MythicDropBuilder(mythicDrops).withItemGenerationReason(
ItemGenerationReason.MONSTER_SPAWN
).useDurability(false).withTier(it).build()
} ?: dropChance to itemStack
}
}
| mit | a128b9ec61945d2244154f13e5621ea1 | 45.389892 | 119 | 0.691907 | 4.869269 | false | true | false | false |
AndroidX/androidx | compose/foundation/foundation/src/desktopMain/kotlin/androidx/compose/foundation/text/TextFieldKeyInput.desktop.kt | 3 | 1133 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text
import androidx.compose.ui.input.key.KeyEvent
private fun Char.isPrintable(): Boolean {
val block = Character.UnicodeBlock.of(this)
return (!Character.isISOControl(this)) &&
this != java.awt.event.KeyEvent.CHAR_UNDEFINED &&
block != null &&
block != Character.UnicodeBlock.SPECIALS
}
actual val KeyEvent.isTypedEvent: Boolean
get() = nativeKeyEvent.id == java.awt.event.KeyEvent.KEY_TYPED &&
nativeKeyEvent.keyChar.isPrintable() | apache-2.0 | e6861d99f760d9fe075d0d075dccf167 | 35.580645 | 75 | 0.727273 | 4.105072 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/structure/RsVisibilitySorter.kt | 3 | 1778 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.structure
import com.intellij.ide.util.treeView.smartTree.ActionPresentation
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData
import com.intellij.ide.util.treeView.smartTree.Sorter
import org.rust.RsBundle
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.ext.RsVisibility
import org.rust.lang.core.psi.ext.RsVisible
class RsVisibilitySorter : Sorter {
private enum class Order {
Public,
Restricted,
Private,
Unknown;
companion object {
fun fromVisibility(vis: RsVisibility): Order {
return when (vis) {
RsVisibility.Public -> Public
RsVisibility.Private -> Private
is RsVisibility.Restricted -> Restricted
}
}
}
}
private fun getOrdering(x: Any?): Order {
val psi = (x as? RsStructureViewElement)?.value
val visibility = (psi as? RsVisible)?.visibility
return if (visibility != null) Order.fromVisibility(visibility) else Order.Unknown
}
override fun getPresentation(): ActionPresentation = ActionPresentationData(
RsBundle.message("structure.view.sort.visibility"),
null,
RsIcons.VISIBILITY_SORT,
)
override fun getName(): String = ID
override fun getComparator(): java.util.Comparator<*> = Comparator<Any> { p0, p1 ->
val ord0 = getOrdering(p0)
val ord1 = getOrdering(p1)
ord0.compareTo(ord1)
}
override fun isVisible(): Boolean = true
companion object {
const val ID = "STRUCTURE_VIEW_VISIBILITY_SORTER"
}
}
| mit | cc8d7776d33c12ec4df3b7fe4803c616 | 29.135593 | 90 | 0.647919 | 4.37931 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/dialogs/QuestCompletedDialogContent.kt | 1 | 4530 | package com.habitrpg.android.habitica.ui.views.dialogs
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.DialogCompletedQuestContentBinding
import com.habitrpg.android.habitica.extensions.fromHtml
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.inventory.QuestDropItem
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class QuestCompletedDialogContent : LinearLayout {
private lateinit var binding: DialogCompletedQuestContentBinding
constructor(context: Context) : super(context) {
setupView()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
setupView()
}
private fun setupView() {
orientation = VERTICAL
gravity = Gravity.CENTER
binding = DialogCompletedQuestContentBinding.inflate(context.layoutInflater, this)
}
fun setQuestContent(questContent: QuestContent) {
binding.titleTextView.setText(questContent.text.fromHtml(), TextView.BufferType.SPANNABLE)
binding.notesTextView.setText(questContent.completion.fromHtml(), TextView.BufferType.SPANNABLE)
DataBindingUtils.loadImage(binding.imageView, "quest_" + questContent.key)
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
if (questContent.drop != null && questContent.drop?.items != null) {
questContent.drop?.items
?.filterNot { it.onlyOwner }
?.forEach { addRewardsRow(inflater, it, binding.rewardsList) }
var hasOwnerRewards = false
for (item in questContent.drop?.items ?: emptyList<QuestDropItem>()) {
if (item.onlyOwner) {
addRewardsRow(inflater, item, binding.ownerRewardsList)
hasOwnerRewards = true
}
}
if (!hasOwnerRewards) {
binding.ownerRewardsTitle.visibility = View.GONE
binding.ownerRewardsList.visibility = View.GONE
}
if (questContent.drop?.exp ?: 0 > 0) {
val view = inflater?.inflate(R.layout.row_quest_reward_imageview, binding.rewardsList, false) as? ViewGroup
val imageView = view?.findViewById<ImageView>(R.id.imageView)
imageView?.scaleType = ImageView.ScaleType.CENTER
imageView?.setImageBitmap(HabiticaIconsHelper.imageOfExperienceReward())
val titleTextView = view?.findViewById<TextView>(R.id.titleTextView)
titleTextView?.text = context.getString(R.string.experience_reward, questContent.drop?.exp)
binding.rewardsList.addView(view)
}
if (questContent.drop?.gp ?: 0 > 0) {
val view = inflater?.inflate(R.layout.row_quest_reward_imageview, binding.rewardsList, false) as? ViewGroup
val imageView = view?.findViewById<ImageView>(R.id.imageView)
imageView?.scaleType = ImageView.ScaleType.CENTER
imageView?.setImageBitmap(HabiticaIconsHelper.imageOfGoldReward())
val titleTextView = view?.findViewById<TextView>(R.id.titleTextView)
titleTextView?.text = context.getString(R.string.gold_reward, questContent.drop?.gp)
binding.rewardsList.addView(view)
}
}
}
private fun addRewardsRow(inflater: LayoutInflater?, item: QuestDropItem, containerView: ViewGroup?) {
val view = inflater?.inflate(R.layout.row_quest_reward, containerView, false) as? ViewGroup
val imageView = view?.findViewById(R.id.imageView) as? ImageView
val titleTextView = view?.findViewById(R.id.titleTextView) as? TextView
DataBindingUtils.loadImage(imageView, item.imageName)
if (item.count > 1) {
titleTextView?.text = context.getString(R.string.quest_reward_count, item.text, item.count)
} else {
titleTextView?.text = item.text
}
containerView?.addView(view)
}
}
| gpl-3.0 | 9017f91131bb893dc8c7cecdccf0838d | 45.22449 | 123 | 0.686755 | 4.773446 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/kml/KmlReader.kt | 1 | 14296 | package nl.rsdt.japp.jotial.maps.kml
import android.util.Xml
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.data.structures.area348.MetaInfo
import nl.rsdt.japp.jotial.net.apis.MetaApi
import okhttp3.OkHttpClient
import okhttp3.Request
import org.acra.ktx.sendWithAcra
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
import java.io.InputStream
/**
* Created by Mattijn on 11/10/2015.
*/
class KmlReader : Callback<MetaInfo> {
override fun onResponse(call: Call<MetaInfo>, response: Response<MetaInfo>) {
assert(response.body() != null)
}
override fun onFailure(call: Call<MetaInfo>, t: Throwable) {
t.sendWithAcra()
}
interface Callback {
fun onException(e: Throwable)
fun onSucces(kml: KmlFile)
}
companion object {
fun parseFromMeta(callback: KmlReader.Callback) {
val metaApi = Japp.getApi(MetaApi::class.java)
metaApi.getMetaInfo(JappPreferences.accountKey).enqueue(object : retrofit2.Callback<MetaInfo> {
override fun onResponse(call: Call<MetaInfo>, response: Response<MetaInfo>) {
assert(response.body() != null)
if (response.isSuccessful) {
val req = Request.Builder().url(response.body()!!.KML_URL!!).build()
val client = OkHttpClient.Builder()
.build()
client.newCall(req).enqueue(object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call, e: IOException) {
e.sendWithAcra()
callback.onException(e)
}
@Throws(IOException::class)
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
if (response.isSuccessful) {
try {
assert(response.body() != null)
val file = parse(response.body()!!.byteStream())
callback.onSucces(file)
} catch (e: XmlPullParserException) {
e.printStackTrace()
e.sendWithAcra()
callback.onException(e)
} catch (e: IOException) {
e.printStackTrace()
e.sendWithAcra()
callback.onException(e)
}
} else {
callback.onException(Exception(response.body()!!.string()))
}
}
})
} else {
try {
callback.onException(Exception(response.errorBody()!!.string()))
} catch (e: IOException) {
e.sendWithAcra()
callback.onException(e)
}
}
}
override fun onFailure(call: Call<MetaInfo>, t: Throwable) {
t.sendWithAcra()
}
})
}
@Throws(XmlPullParserException::class, IOException::class)
fun parse(`in`: InputStream): KmlFile {
val kmlFile: KmlFile
try {
val parser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
parser.setInput(`in`, null)
parser.nextTag()
kmlFile = readKml(parser)
} finally {
`in`.close()
}
return kmlFile
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readKml(parser: XmlPullParser): KmlFile {
var document = KmlDocument()
val ns: String? = null
parser.require(XmlPullParser.START_TAG, ns, "kml")
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "Document") {
document = readDocument(parser)
}
}
return document.toKmlFile()
}
@Throws(XmlPullParserException::class, IOException::class)
private fun readDocument(parser: XmlPullParser): KmlDocument {
val document = KmlDocument()
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "name") {
document.setName(getTextAndGoToCloseTag(parser))
}
if (tagName == "Folder") {
document.addFolder(readFolder(parser))
}
if (tagName == "Style") {
document.addStyle(readStyle(parser))
}
}
return document
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readFolder(parser: XmlPullParser): KmlFolder {
val folder = KmlFolder()
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "name") {
folder.type = KmlFolder.Type.parse(getTextAndGoToCloseTag(parser))
}
if (tagName == "Placemark") {
folder.addPlacemark(readPlaceMark(parser))
}
}
return folder
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readStyle(parser: XmlPullParser): KmlStyle {
val kmlStyle = KmlStyle()
kmlStyle.setId(parser.getAttributeValue(0))
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "IconStyle") {
readIconStyle(parser, kmlStyle)
}
if (tagName == "BalloonStyle") {
readBalloonStyle(parser, kmlStyle)
}
if (tagName == "LineStyle") {
readLineStyle(parser, kmlStyle)
}
if (tagName == "PolyStyle") {
readPolyStyle(parser, kmlStyle)
}
}
return kmlStyle
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readIconStyle(parser: XmlPullParser, kmlStyle: KmlStyle) {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "color") {
kmlStyle.setIconColor(getTextAndGoToCloseTag(parser))
}
if (tagName == "scale") {
val scale = getTextAndGoToCloseTag(parser)
kmlStyle.setIconScale(java.lang.Double.valueOf(scale))
}
if (tagName == "Icon") {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
if (parser.name == "href") {
kmlStyle.setIconUrl(getTextAndGoToCloseTag(parser))
}
}
}
}
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readBalloonStyle(parser: XmlPullParser, kmlStyle: KmlStyle) {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "bgColor") {
kmlStyle.setBalloonBgColor(getTextAndGoToCloseTag(parser))
}
if (tagName == "text") {
kmlStyle.setBalloonText(getTextAndGoToCloseTag(parser))
}
}
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readLineStyle(parser: XmlPullParser, kmlStyle: KmlStyle) {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "color") {
kmlStyle.setLineColor(getTextAndGoToCloseTag(parser))
}
if (tagName == "width") {
val lineWidth = getTextAndGoToCloseTag(parser)
kmlStyle.setLineWidth(java.lang.Double.valueOf(lineWidth))
}
}
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readPolyStyle(parser: XmlPullParser, kmlStyle: KmlStyle) {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "color") {
kmlStyle.setPolyLineColor(getTextAndGoToCloseTag(parser))
}
if (tagName == "fill") {
val polylineFill = getTextAndGoToCloseTag(parser)
kmlStyle.setPolyLineFill(Integer.valueOf(polylineFill))
}
if (tagName == "outline") {
val polyLineOutline = getTextAndGoToCloseTag(parser)
kmlStyle.setPolyLineOutline(Integer.valueOf(polyLineOutline))
}
}
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readPlaceMark(parser: XmlPullParser): KmlPlaceMark {
val placeMark = KmlPlaceMark()
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "name") {
placeMark.name = getTextAndGoToCloseTag(parser)
}
if (tagName == "styleUrl") {
placeMark.setStyleUrl(getTextAndGoToCloseTag(parser))
}
if (tagName == "Point") {
placeMark.setCoordinates(readPoint(parser))
}
if (tagName == "Polygon") {
placeMark.setCoordinates(readPolygon(parser))
}
}
return placeMark
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readPolygon(parser: XmlPullParser): List<KmlLocation> {
var coordinates = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "outerBoundaryIs") {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagNameinner = parser.name
if (tagNameinner == "LinearRing") {
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagNameinner2 = parser.name
if (tagNameinner2 == "coordinates") {
coordinates = getTextAndGoToCloseTag(parser)
}
}
}
}
}
}
return KmlLocation.readCoordinates(coordinates)
}
@Throws(IOException::class, XmlPullParserException::class)
private fun readPoint(parser: XmlPullParser): List<KmlLocation> {
var coordinates = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType != XmlPullParser.START_TAG) {
continue
}
val tagName = parser.name
if (tagName == "coordinates") {
coordinates = getTextAndGoToCloseTag(parser)
}
}
return KmlLocation.readCoordinates(coordinates)
}
@Throws(IOException::class, XmlPullParserException::class)
private fun getTextAndGoToCloseTag(parser: XmlPullParser): String {
var text = ""
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.eventType == XmlPullParser.TEXT) {
text = parser.text
}
}
return text
}
}
}
| apache-2.0 | 830493a65768457f6fe074179a52bf98 | 38.932961 | 107 | 0.478246 | 5.448171 | false | false | false | false |
oleksiyp/mockk | agent/android/src/main/kotlin/io/mockk/proxy/android/OnjenesisInstantiator.kt | 1 | 1546 | package io.mockk.proxy.android
import com.android.dx.stock.ProxyBuilder
import io.mockk.proxy.MockKAgentLogger
import io.mockk.proxy.MockKInstantiatior
import org.objenesis.ObjenesisStd
import org.objenesis.instantiator.ObjectInstantiator
import java.lang.reflect.Modifier
import java.util.*
internal class OnjenesisInstantiator(val log: MockKAgentLogger) : MockKInstantiatior {
private val objenesis = ObjenesisStd(false)
private val instantiators = Collections.synchronizedMap(WeakHashMap<Class<*>, ObjectInstantiator<*>>())
override fun <T> instance(cls: Class<T>): T {
val clazz = proxyInterface(cls)
log.trace("Creating new empty instance of $clazz")
val inst = synchronized(instantiators) {
instantiators.getOrPut(clazz) {
objenesis.getInstantiatorOf(clazz)
}
}
val newInstance = inst.newInstance()
return clazz.cast(newInstance) as T
}
@Suppress("UNCHECKED_CAST")
private fun <T> proxyInterface(clazz: Class<T>) =
if (Modifier.isAbstract(clazz.modifiers)) {
if (clazz.isInterface) {
ProxyBuilder.forClass(Any::class.java)
.parentClassLoader(clazz.classLoader)
.implementing(clazz)
.buildProxyClass()
} else {
ProxyBuilder.forClass(clazz)
.parentClassLoader(clazz.classLoader)
.buildProxyClass()
}
} else {
clazz
}
}
| apache-2.0 | 9ae6439464d65345c7d293124bf82431 | 32.608696 | 107 | 0.6326 | 4.520468 | false | false | false | false |
vitorsalgado/android-boilerplate | analytics/src/main/kotlin/br/com/vitorsalgado/example/analytics/FirebaseAnalyticsAdapter.kt | 1 | 1406 | package br.com.vitorsalgado.example.analytics
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import com.google.firebase.analytics.FirebaseAnalytics
class FirebaseAnalyticsAdapter(private val activityProvider: ActivityProvider) : AnalyticsAdapter {
private val TAG: String = this.javaClass.simpleName
override fun trackAction(context: Context, args: TraceActionArgs) {
val bundle = Bundle()
args.params.forEach {
when (it.value) {
is String -> bundle.putString(it.key, it.value as String)
is Int -> bundle.putInt(it.key, it.value as Int)
is Double -> bundle.putDouble(it.key, it.value as Double)
is Parcelable -> bundle.putParcelable(it.key, it.value as Parcelable)
else -> bundle.putString(it.key, it.value.toString())
}
}
FirebaseAnalytics.getInstance(context).logEvent(args.action, bundle)
}
override fun trackView(context: Context, args: TraceScreenArgs) {
FirebaseAnalytics.getInstance(context)
.setCurrentScreen(activityProvider.currentActivity(), args.screen, null)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FirebaseAnalyticsAdapter
if (TAG != other.TAG) return false
return true
}
override fun hashCode(): Int {
return TAG.hashCode()
}
}
| apache-2.0 | 6f280994ff7b1f81e10d16666c8d4a7e | 30.244444 | 99 | 0.714083 | 4.273556 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/seven/MyConcernActivity.kt | 1 | 8057 | package com.intfocus.template.subject.seven
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.intfocus.template.R
import com.intfocus.template.constant.Params.BANNER_NAME
import com.intfocus.template.constant.Params.GROUP_ID
import com.intfocus.template.constant.Params.OBJECT_ID
import com.intfocus.template.constant.Params.OBJECT_TYPE
import com.intfocus.template.constant.Params.TEMPLATE_ID
import com.intfocus.template.constant.Params.USER_NUM
import com.intfocus.template.filter.FilterDialogFragment
import com.intfocus.template.model.entity.Report
import com.intfocus.template.model.response.filter.MenuItem
import com.intfocus.template.subject.nine.CollectionModelImpl.Companion.uuid
import com.intfocus.template.subject.one.entity.Filter
import com.intfocus.template.subject.one.module.banner.BannerFragment
import com.intfocus.template.subject.seven.concernlist.ConcernListActivity
import com.intfocus.template.subject.seven.indicatorgroup.IndicatorGroupFragment
import com.intfocus.template.subject.seven.indicatorlist.IndicatorListFragment
import com.intfocus.template.subject.seven.indicatorlist.IndicatorListModelImpl
import com.intfocus.template.subject.seven.indicatorlist.IndicatorListPresenter
import com.intfocus.template.ui.BaseActivity
import com.intfocus.template.util.LogUtil
import kotlinx.android.synthetic.main.actvity_my_attention.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import java.util.*
/**
* ****************************************************
* @author jameswong
* created on: 17/12/18 上午11:14
* e-mail: [email protected]
* name: 模板七
* desc: 我的关注,提供筛选和关注功能
* ****************************************************
*/
class MyConcernActivity : BaseActivity(), MyConcernContract.View, FilterDialogFragment.FilterListener {
companion object {
val REQUEST_CODE = 2
val FRAGMENT_TAG = "filterFragment"
}
private lateinit var mUserNum: String
private var filterDisplay: String = ""
private var currentFilterId: String = ""
lateinit var groupId: String
lateinit var reportId: String
lateinit var objectType: String
lateinit var bannerName: String
lateinit var templateId: String
/**
* 地址选择
*/
private var filterDataList: ArrayList<MenuItem> = arrayListOf()
override lateinit var presenter: MyConcernContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.actvity_my_attention)
MyConcernPresenter(MyConcernModelImpl.getInstance(), this)
initData()
initView()
}
fun initData() {
mUserNum = mUserSP.getString(USER_NUM, "")
val intent = intent
groupId = intent.getStringExtra(GROUP_ID)
reportId = intent.getStringExtra(OBJECT_ID)
objectType = intent.getStringExtra(OBJECT_TYPE)
bannerName = intent.getStringExtra(BANNER_NAME)
templateId = intent.getStringExtra(TEMPLATE_ID)
uuid = reportId + templateId + groupId
presenter.loadData(this, groupId, templateId, reportId)
}
private fun initView() {
tv_banner_title.text = bannerName
}
override fun initFilterView(filter: Filter) {
if (null != filter.data) {
initFilter(filter)
}
}
override fun generateReportItemView(reports: List<Report>) {
Observable.from(reports)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
when (it.type) {
//标题栏
"banner" -> {
addItemView(BannerFragment.newInstance(0, it.index))
}
// 横向滑动单值组件列表
"concern_group"->{
addItemView(IndicatorGroupFragment().newInstance(it.config))
}
// 可拓展的关注单品列表,拓展内容为 横向滑动单值组件列表
"concern_list"->{
val indicatorListFragment = IndicatorListFragment().newInstance()
addItemView(indicatorListFragment)
IndicatorListPresenter(IndicatorListModelImpl.getInstance(),indicatorListFragment)
}
}
}
}
private fun addItemView(fragment: Fragment) {
val layout = FrameLayout(this)
val params = AppBarLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
layout.layoutParams = params
val id = Random().nextInt(Integer.MAX_VALUE)
layout.id = id
ll_my_attention_container.addView(layout)
val ft = supportFragmentManager.beginTransaction()
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
ft.replace(layout.id, fragment)
ft.commitNow()
}
fun menuOnClicked(view: View) {
when (view.id) {
R.id.iv_attention -> {
startActivityForResult(Intent(this, ConcernListActivity::class.java), REQUEST_CODE)
}
R.id.tv_address_filter -> {
showDialogFragment()
}
}
}
/**
* 初始化筛选框
*/
private fun initFilter(filter: Filter) {
filter.data?.let { it[0].id?.let { currentFilterId = it } }
this.filterDataList = filter.data!!
this.filterDisplay = filter.display!!
if (filterDataList.isEmpty()) {
ll_filter.visibility = View.GONE
} else {
ll_filter.visibility = View.VISIBLE
tv_location_address.text = filterDisplay
}
}
/**
* 筛选框
*/
private fun showDialogFragment() {
val mFragTransaction = supportFragmentManager.beginTransaction()
val fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG)
if (fragment != null) {
//为了不重复显示dialog,在显示对话框之前移除正在显示的对话框
mFragTransaction.remove(fragment)
}
val dialogFragment = FilterDialogFragment.newInstance(filterDataList)
//显示一个Fragment并且给该Fragment添加一个Tag,可通过findFragmentByTag找到该Fragment
dialogFragment!!.show(mFragTransaction, FRAGMENT_TAG)
}
/**
* 筛选回调
*/
override fun complete(menuItems: ArrayList<MenuItem>) {
var addStr = ""
val size = menuItems.size
for (i in 0 until size) {
addStr += menuItems[i].name!! + "||"
}
addStr = addStr.substring(0, addStr.length - 2)
tv_location_address.text = addStr
menuItems[menuItems.size - 1].id?.let {
currentFilterId = it
ll_my_attention_container.removeAllViews()
presenter.loadData(mUserNum, currentFilterId)
}
LogUtil.d(this, "Filter FullName ::: " + addStr)
LogUtil.d(this, "Filter ItemName ::: " + menuItems[menuItems.size - 1].name)
LogUtil.d(this, "Filter id ::: " + menuItems[menuItems.size - 1].id)
}
/**
* 关注 item 后的回调刷新
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE && resultCode == ConcernListActivity.RESPONSE_CODE) {
presenter.loadData(mUserNum, currentFilterId)
}
}
} | gpl-3.0 | 19fa2c85b4e6f25ade2c47c1e94f711a | 35.457944 | 127 | 0.647994 | 4.509249 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/model/ChatRoomAndLastMessage.kt | 1 | 408 | package de.tum.`in`.tumcampusapp.component.ui.chat.model
import androidx.room.ColumnInfo
import androidx.room.Embedded
import org.joda.time.DateTime
class ChatRoomAndLastMessage {
@Embedded
var chatRoomDbRow: ChatRoomDbRow? = null
var text: String? = null
var timestamp: DateTime? = null
@ColumnInfo(name = "nr_unread")
var nrUnread: Int = 0
fun hasUnread() = nrUnread > 0
} | gpl-3.0 | 197262fb7e3991bc77dd92c7d57424f1 | 20.526316 | 56 | 0.715686 | 3.777778 | false | false | false | false |
kohesive/klutter | reflect/src/main/kotlin/uy/klutter/reflect/TypeInfo.kt | 2 | 3140 | package uy.klutter.reflect
import java.lang.reflect.*
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.KTypeProjection
import kotlin.reflect.KVariance
import kotlin.reflect.full.createType
inline fun <reified T> reifiedType(): Type = object : TypeReference<T>() {}.type
@Deprecated(message = "This is experimental based on https://youtrack.jetbrains.com/issue/KT-15992",
level = DeprecationLevel.WARNING)
inline fun <reified T> reifiedKType(): KType = object : KTypeReference<T>(isNullable<T>()) {}.ktype
inline fun <reified T : Any?> isNullable(): Boolean {
return null is T
}
interface TypeToken {
val type: Type
}
abstract class TypeReference<T> protected constructor() : TypeToken {
override val type: Type by lazy {
javaClass.getGenericSuperclass().let { superClass ->
if (superClass is Class<*>) {
throw IllegalArgumentException("Internal error: TypeReference constructed without actual type information")
}
(superClass as ParameterizedType).getActualTypeArguments().single()
}
}
}
abstract class KTypeReference<T> protected constructor(val nullable: Boolean): TypeReference<T>() {
val ktype: KType = type.toKType(nullable)
fun Type.toKTypeProjection(nullable: Boolean = false): KTypeProjection = when (this) {
is Class<*> -> this.kotlin.toInvariantFlexibleProjection(nullable = nullable)
is ParameterizedType -> {
val erasure = (rawType as Class<*>).kotlin
erasure.toInvariantFlexibleProjection((erasure.typeParameters.zip(actualTypeArguments).map { (parameter, argument) ->
val projection = argument.toKTypeProjection()
projection.takeIf {
// Get rid of use-site projections on arguments, where the corresponding parameters already have a declaration-site projection
parameter.variance == KVariance.INVARIANT || parameter.variance != projection.variance
} ?: KTypeProjection.invariant(projection.type!!)
}), nullable = nullable)
}
is WildcardType -> when {
lowerBounds.isNotEmpty() -> KTypeProjection.contravariant(lowerBounds.single().toKType())
upperBounds.isNotEmpty() -> KTypeProjection.covariant(upperBounds.single().toKType())
// This looks impossible to obtain through Java reflection API, but someone may construct and pass such an instance here anyway
else -> KTypeProjection.STAR
}
is GenericArrayType -> Array<Any>::class.toInvariantFlexibleProjection(listOf(genericComponentType.toKTypeProjection()), nullable = nullable)
is TypeVariable<*> -> TODO() // TODO
else -> throw IllegalArgumentException("Unsupported type: $this")
}
fun Type.toKType(nullable: Boolean = false): KType = toKTypeProjection(nullable).type!!
fun KClass<*>.toInvariantFlexibleProjection(arguments: List<KTypeProjection> = emptyList(), nullable: Boolean): KTypeProjection {
return KTypeProjection.invariant(createType(arguments, nullable = nullable))
}
}
| mit | 54635b72d668c56f63a7dc579a0414a0 | 45.176471 | 149 | 0.695541 | 5.032051 | false | false | false | false |
walleth/walleth | app/src/withGeth/java/org/walleth/geth/services/GethLightEthereumService.kt | 1 | 9507 | package org.walleth.geth.services
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.NotificationManager.IMPORTANCE_HIGH
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import org.ethereum.geth.*
import org.kethereum.extensions.transactions.encode
import org.koin.android.ext.android.inject
import org.walleth.R
import org.walleth.chains.ChainInfoProvider
import org.walleth.data.AppDatabase
import org.walleth.data.addresses.CurrentAddressProvider
import org.walleth.data.balances.Balance
import org.walleth.data.config.Settings
import org.walleth.data.syncprogress.SyncProgressProvider
import org.walleth.data.syncprogress.WallethSyncProgress
import org.walleth.data.tokens.getRootToken
import org.walleth.data.transactions.TransactionEntity
import org.walleth.geth.toGethAddr
import org.walleth.notifications.NOTIFICATION_CHANNEL_ID_GETH
import org.walleth.notifications.NOTIFICATION_ID_GETH
import org.walleth.overview.OverviewActivity
import timber.log.Timber
import java.io.File
import java.math.BigInteger
import org.ethereum.geth.Context as EthereumContext
class GethLightEthereumService : LifecycleService() {
companion object {
const val STOP_SERVICE_ACTION = "STOPSERVICE"
fun Context.gethStopIntent() = Intent(this, GethLightEthereumService::class.java).apply {
action = STOP_SERVICE_ACTION
}
var shouldRun = false
var isRunning = false
}
private val syncProgress: SyncProgressProvider by inject()
private val appDatabase: AppDatabase by inject()
private val settings: Settings by inject()
private val networkDefinitionProvider: ChainInfoProvider by inject()
private val currentAddressProvider: CurrentAddressProvider by inject()
private val path by lazy { File(baseContext.cacheDir, "ethereumdata").absolutePath }
private val notificationManager by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }
private var isSyncing = false
private var finishedSyncing = false
private var shouldRestart = false
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
if (intent?.action == STOP_SERVICE_ACTION) {
shouldRun = false
return START_NOT_STICKY
}
shouldRun = true
lifecycleScope.launch(Dispatchers.Default) {
Geth.setVerbosity(settings.currentGoVerbosity.toLong())
val ethereumContext = EthereumContext()
var initial = true
while (shouldRestart || initial) {
initial = false
shouldRestart = false // just did restart
shouldRun = true
withContext(Dispatchers.Main) {
val pendingStopIntent = PendingIntent.getService(baseContext, 0, gethStopIntent(), 0)
val contentIntent = PendingIntent.getActivity(baseContext, 0, Intent(baseContext, OverviewActivity::class.java), 0)
if (Build.VERSION.SDK_INT > 25) {
setNotificationChannel()
}
val notification = NotificationCompat.Builder(this@GethLightEthereumService, NOTIFICATION_CHANNEL_ID_GETH)
.setContentTitle(getString(R.string.geth_service_notification_title))
.setContentText(resources.getString(R.string.geth_service_notification_content_text, networkDefinitionProvider.getCurrent()?.name))
.setContentIntent(contentIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "exit", pendingStopIntent)
.setSmallIcon(R.drawable.notification)
.build()
startForeground(NOTIFICATION_ID_GETH, notification)
}
val network = networkDefinitionProvider.getCurrent()
networkDefinitionProvider.getFlow().collect {
if (network != networkDefinitionProvider.getCurrent()) {
shouldRun = false
shouldRestart = true
}
}
val subPath = File(path, "chain" + network.chainId)
subPath.mkdirs()
val nodeConfig = NodeConfig().apply {
ethereumNetworkID = network.chainId.toLong()
ethereumGenesis = when (ethereumNetworkID) {
1L -> Geth.mainnetGenesis()
3L -> Geth.testnetGenesis()
4L -> Geth.rinkebyGenesis()
else -> throw (IllegalStateException("NO genesis"))
}
}
val ethereumNode = Geth.newNode(subPath.absolutePath, nodeConfig)
Timber.i("Starting Node for " + nodeConfig.ethereumNetworkID)
ethereumNode.start()
isRunning = true
while (shouldRun && !finishedSyncing) {
delay(1000)
syncTick(ethereumNode, ethereumContext)
}
val transactionsLiveData = appDatabase.transactions.getAllToRelayLive()
val transactionObserver = Observer<List<TransactionEntity>> {
it?.forEach { transaction ->
transaction.execute(ethereumNode.ethereumClient, ethereumContext)
}
}
transactionsLiveData.observe(this@GethLightEthereumService, transactionObserver)
try {
ethereumNode.ethereumClient.subscribeNewHead(ethereumContext, object : NewHeadHandler {
override fun onNewHead(p0: Header) {
val address = currentAddressProvider.getCurrentNeverNull()
val gethAddress = address.toGethAddr()
val balance = ethereumNode.ethereumClient.getBalanceAt(ethereumContext, gethAddress, p0.number)
appDatabase.balances.upsert(Balance(
address = address,
tokenAddress = network.getRootToken().address,
chain = network.chainId,
balance = BigInteger(balance.string()),
block = p0.number))
}
override fun onError(p0: String?) {}
}, 16)
} catch (e: Exception) {
Timber.e(e, "node error")
}
while (shouldRun) {
syncTick(ethereumNode, ethereumContext)
}
withContext(Dispatchers.Main) {
transactionsLiveData.removeObserver(transactionObserver)
launch {
ethereumNode.stop()
}
if (!shouldRestart) {
stopForeground(true)
stopSelf()
isRunning = false
} else {
notificationManager.cancel(NOTIFICATION_ID_GETH)
}
}
}
}
return START_NOT_STICKY
}
@TargetApi(26)
private fun setNotificationChannel() {
val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID_GETH, "Geth Service", IMPORTANCE_HIGH)
channel.description = getString(R.string.geth_service_notification_channel_description)
notificationManager.createNotificationChannel(channel)
}
private suspend fun syncTick(ethereumNode: Node, ethereumContext: EthereumContext) {
try {
val ethereumSyncProgress = ethereumNode.ethereumClient.syncProgress(ethereumContext)
lifecycleScope.async(Dispatchers.Main) {
if (ethereumSyncProgress != null) {
isSyncing = true
val newSyncProgress = ethereumSyncProgress.let {
WallethSyncProgress(true, it.currentBlock, it.highestBlock)
}
syncProgress.postValue(newSyncProgress)
} else {
syncProgress.postValue(WallethSyncProgress())
if (isSyncing) {
finishedSyncing = true
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
delay(1000)
}
private fun TransactionEntity.execute(client: EthereumClient, ethereumContext: EthereumContext) {
try {
val rlp = transaction.encode()
val transactionWithSignature = Geth.newTransactionFromRLP(rlp)
client.sendTransaction(ethereumContext, transactionWithSignature)
transactionState.relayed = "GethLight"
} catch (e: Exception) {
transactionState.error = e.message
}
}
}
| gpl-3.0 | a7c2a0fb217d457bd8492b0df401e7f3 | 39.978448 | 159 | 0.598927 | 5.454389 | false | false | false | false |
Exaltead/SceneClassifier | SceneClassifier/app/src/main/java/com/exaltead/sceneclassifier/classification/SceneClassifier.kt | 1 | 2239 | package com.exaltead.sceneclassifier.classification
import com.exaltead.sceneclassifier.extraction.IFeatureExtractor
import com.exaltead.sceneclassifier.ui.App
import org.tensorflow.contrib.android.TensorFlowInferenceInterface
import java.io.Closeable
private const val TAG = "SceneClassifier"
//private val MODEL_FILE_NAME = Environment.getExternalStorageDirectory().name+"/model.pb"
private const val OUTPUT_TENSOR_NAME = "tuutuut"
private const val INPUT_TENSOR_NAME = "dadaa"
private const val SAMPLE_LENGHT = 30L
private const val NUMBER_OF_CLASSES = 15
private const val MODEL_FILE = "fmodel.pb"
private const val LABEL_FILE = "labels.txt"
class SceneClassifier(private val featureExtractor: IFeatureExtractor):Closeable {
private val labels: List<String>
private val inference: TensorFlowInferenceInterface
private var isClosed = false
init {
val manager = App.context.assets
inference = TensorFlowInferenceInterface(manager, MODEL_FILE)
labels = manager.open(LABEL_FILE).use { t -> readLabels(t.reader().readLines())}
}
override fun close() {
synchronized(isClosed, {
isClosed = true
inference.close()})
}
companion object {
init {
System.loadLibrary("tensorflow_inference")
}
}
fun getCurrentClassification(): List<ClassificationResult> =
synchronized(isClosed, { classify()})
private fun classify(): List<ClassificationResult> {
if(isClosed){
return emptyList()
}
val inputs = featureExtractor.receiveFeaturesForTimeSpan()
inference.feed(INPUT_TENSOR_NAME, inputs.toFloatArray(), 1, SAMPLE_LENGHT)
inference.run(arrayOf(OUTPUT_TENSOR_NAME))
val results = FloatArray(NUMBER_OF_CLASSES)
inference.fetch(OUTPUT_TENSOR_NAME, results)
return results.mapIndexed({i, f -> ClassificationResult(labels[i], f.toDouble())})
}
}
private fun readLabels(input: List<String>): List<String>{
val output = MutableList(input.size, {_ -> ""})
input.map { t -> t.split(',') }
.map { a -> Pair(a[0].toInt(), a[1])}
.map { b -> output[b.first] = b.second }
return output.toList()
}
| gpl-3.0 | ffb884175a576f5f553aaa7e593513cb | 32.924242 | 90 | 0.681108 | 4.108257 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/local/Store.kt | 1 | 1028 | package tr.xip.scd.tensuu.local
import android.content.Context
import android.content.SharedPreferences
import tr.xip.scd.tensuu.App
/**
* A SharedPreferences manager object that takes care of storing various simple data
*/
object Store {
private val NAME = "store"
private val KEY_LAST_POINT_ADD_TIMESTAMP = "last_point_add_timestamp"
private val KEY_LAST_POINT_ADD_TIMESTAMP_UPDATED = "last_point_add_timestamp_updated"
private var prefs: SharedPreferences
init {
prefs = App.context.getSharedPreferences(NAME, Context.MODE_PRIVATE)
}
var lastPointAddTimestamp: Long
set(value) = prefs.edit().putLong(KEY_LAST_POINT_ADD_TIMESTAMP, value).apply()
get() = prefs.getLong(KEY_LAST_POINT_ADD_TIMESTAMP, System.currentTimeMillis())
var lastPointTimestampUpdated: Long
set(value) = prefs.edit().putLong(KEY_LAST_POINT_ADD_TIMESTAMP_UPDATED, value).apply()
get() = prefs.getLong(KEY_LAST_POINT_ADD_TIMESTAMP_UPDATED, System.currentTimeMillis() - 1000)
} | gpl-3.0 | f0870a67258c576172d5dbbef4088018 | 34.482759 | 102 | 0.727626 | 3.923664 | false | false | false | false |
Maccimo/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt | 1 | 20231 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.createTask
import com.intellij.diagnostic.telemetry.use
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.SystemProperties
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFile
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.writeNewFile
import org.jetbrains.intellij.build.tasks.*
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.time.LocalDate
import java.util.concurrent.ForkJoinTask
import java.util.function.BiConsumer
import java.util.zip.Deflater
class MacDistributionBuilder(private val context: BuildContext,
private val customizer: MacDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns"
override val targetOs: OsFamily
get() = OsFamily.MACOS
private fun getDocTypes(): String {
val associations = mutableListOf<String>()
if (customizer.associateIpr) {
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>ipr</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${targetIcnsFileName}</string>
<key>CFBundleTypeName</key>
<string>${context.applicationInfo.productName} Project File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
for (fileAssociation in customizer.fileAssociations) {
val iconPath = fileAssociation.iconPath
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>${fileAssociation.extension}</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes
}
override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true)
}
private fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture?, copyDistFiles: Boolean) {
//noinspection SpellCheckingInspection
val platformProperties = mutableListOf(
"\n#---------------------------------------------------------------------",
"# macOS-specific system properties",
"#---------------------------------------------------------------------",
"com.apple.mrj.application.live-resize=false",
"apple.laf.useScreenMenuBar=true",
"jbScreenMenuBar.enabled=true",
"apple.awt.fileDialogForDirectories=true",
"apple.awt.graphics.UseQuartz=true",
"apple.awt.fullscreencapturealldisplays=false"
)
customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") })
layoutMacApp(ideaProperties!!, platformProperties, getDocTypes(), macDistDir, context)
unpackPty4jNative(context, macDistDir, "darwin")
generateBuildTxt(context, macDistDir.resolve("Resources"))
if (copyDistFiles) {
copyDistFiles(context, macDistDir)
}
customizer.copyAdditionalFiles(context, macDistDir.toString())
if (arch != null) {
customizer.copyAdditionalFiles(context, macDistDir, arch)
}
generateUnixScripts(context, emptyList(), macDistDir.resolve("bin"), OsFamily.MACOS)
}
override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false)
context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val publishArchive = !SystemInfoRt.isMac && context.proprietaryBuildTools.macHostProperties?.host == null
val binariesToSign = customizer.getBinariesToSign(context, arch)
if (!binariesToSign.isEmpty()) {
context.executeStep(spanBuilder("sign binaries for macOS distribution")
.setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) {
context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), mapOf(
"mac_codesign_options" to "runtime",
"mac_codesign_force" to "true",
"mac_codesign_deep" to "true",
))
}
}
val macZip = (if (publishArchive || customizer.publishArchive) context.paths.artifactDir else context.paths.tempDir)
.resolve("$baseName.mac.${arch.name}.zip")
val zipRoot = getMacZipRoot(customizer, context)
buildMacZip(
targetFile = macZip,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = null),
allDist = context.paths.distAllDir,
macDist = osAndArchSpecificDistPath,
extraFiles = context.getDistFiles(),
executableFilePatterns = getExecutableFilePatterns(customizer),
compressionLevel = if (publishArchive) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED,
errorsConsumer = context.messages::warning
)
checkInArchive(archiveFile = macZip, pathInArchive = "$zipRoot/Resources", context = context)
if (publishArchive) {
Span.current().addEvent("skip DMG artifact producing because a macOS build agent isn't configured")
context.notifyArtifactBuilt(macZip)
}
else {
buildAndSignDmgFromZip(macZip, arch, context.builtinModule).invoke()
}
}
}
fun buildAndSignDmgFromZip(macZip: Path, arch: JvmArchitecture, builtinModule: BuiltinModulesFileData?): ForkJoinTask<*> {
return createBuildForArchTask(builtinModule, arch, macZip, customizer, context)
}
private fun layoutMacApp(ideaPropertiesFile: Path,
platformProperties: List<String>,
docTypes: String?,
macDistDir: Path,
context: BuildContext) {
val macCustomizer = customizer
copyDirWithFileFilter(context.paths.communityHomeDir.communityRoot.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter)
copyDir(context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir)
val executable = context.productProperties.baseFileName
Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable"))
//noinspection SpellCheckingInspection
val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath)
val resourcesDistDir = macDistDir.resolve("Resources")
copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName))
for (fileAssociation in customizer.fileAssociations) {
if (!fileAssociation.iconPath.isEmpty()) {
val source = Path.of(fileAssociation.iconPath)
val dest = resourcesDistDir.resolve(source.fileName)
Files.deleteIfExists(dest)
copyFile(source, dest)
}
}
val fullName = context.applicationInfo.productName
//todo[nik] improve
val minor = context.applicationInfo.minorVersion
val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta")
val version = if (isNotRelease) "EAP $context.fullBuildNumber" else "${context.applicationInfo.majorVersion}.${minor}"
val isEap = if (isNotRelease) "-EAP" else ""
val properties = Files.readAllLines(ideaPropertiesFile)
properties.addAll(platformProperties)
Files.write(macDistDir.resolve("bin/idea.properties"), properties)
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList()
val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS).toMutableList()
if (!bootClassPath.isEmpty()) {
//noinspection SpellCheckingInspection
additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath")
}
val predicate: (String) -> Boolean = { it.startsWith("-D") }
val launcherProperties = additionalJvmArgs.filter(predicate)
val launcherVmOptions = additionalJvmArgs.filterNot(predicate)
fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log")
fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof")
VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n")
val urlSchemes = macCustomizer.urlSchemes
val urlSchemesString = if (urlSchemes.isEmpty()) {
""
}
else {
"""
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>Stacktrace</string>
<key>CFBundleURLSchemes</key>
<array>
${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }}
</array>
</dict>
</array>
"""
}
val todayYear = LocalDate.now().year.toString()
//noinspection SpellCheckingInspection
substituteTemplatePlaceholders(
inputFile = macDistDir.resolve("Info.plist"),
outputFile = macDistDir.resolve("Info.plist"),
placeholder = "@@",
values = listOf(
Pair("build", context.fullBuildNumber),
Pair("doc_types", docTypes ?: ""),
Pair("executable", executable),
Pair("icns", targetIcnsFileName),
Pair("bundle_name", fullName),
Pair("product_state", isEap),
Pair("bundle_identifier", macCustomizer.bundleIdentifier),
Pair("year", todayYear),
Pair("version", version),
Pair("vm_options", optionsToXml(launcherVmOptions)),
Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))),
Pair("class_path", classPath),
Pair("url_schemes", urlSchemesString),
Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" +
macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } +
" </array>"),
Pair("min_osx", macCustomizer.minOSXVersion),
)
)
val distBinDir = macDistDir.resolve("bin")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/scripts")
Files.newDirectoryStream(sourceScriptDir).use { stream ->
val inspectCommandName = context.productProperties.inspectCommandName
for (file in stream) {
if (file.toString().endsWith(".sh")) {
var fileName = file.fileName.toString()
if (fileName == "inspect.sh" && inspectCommandName != "inspect") {
fileName = "${inspectCommandName}.sh"
}
val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "")
try {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
Files.writeString(sourceFileLf, Files.readString(file).replace("\r", ""))
val target = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
sourceFileLf,
target,
"@@",
listOf(
Pair("product_full", fullName),
Pair("script_name", executable),
Pair("inspectCommandName", inspectCommandName),
),
false,
)
}
finally {
Files.delete(sourceFileLf)
}
}
}
}
}
override fun generateExecutableFilesPatterns(includeJre: Boolean): List<String> = getExecutableFilePatterns(customizer)
}
private fun createBuildForArchTask(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path,
customizer: MacDistributionCustomizer,
context: BuildContext): ForkJoinTask<*> {
return createTask(spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name)) {
val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true)
ForkJoinTask.invokeAll(buildForArch(builtinModule, arch, context.bundledRuntime, macZip, notarize, customizer, context))
Files.deleteIfExists(macZip)
}
}
private fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
jreManager: BundledRuntime,
macZip: Path,
notarize: Boolean,
customizer: MacDistributionCustomizer,
context: BuildContext): List<ForkJoinTask<*>> {
val tasks = mutableListOf<ForkJoinTask<*>?>()
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val archStr = arch.name
// with JRE
if (context.options.buildDmgWithBundledJre) {
tasks.add(createSkippableTask(
spanBuilder("build DMG with JRE").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr",
context
) {
val jreArchive = jreManager.findArchive(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch)
MacDmgBuilder.signAndBuildDmg(builtinModule, context, customizer, context.proprietaryBuildTools.macHostProperties, macZip,
jreArchive, suffix, notarize)
})
}
// without JRE
if (context.options.buildDmgWithoutBundledJre) {
tasks.add(createSkippableTask(
spanBuilder("build DMG without JRE").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr",
context
) {
MacDmgBuilder.signAndBuildDmg(builtinModule, context, customizer, context.proprietaryBuildTools.macHostProperties, macZip,
null, "-no-jdk$suffix", notarize)
})
}
return tasks.filterNotNull()
}
private fun optionsToXml(options: List<String>): String {
val buff = StringBuilder()
for (it in options) {
buff.append(" <string>").append(it).append("</string>\n")
}
return buff.toString().trim()
}
private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String {
val buff = StringBuilder()
for (it in properties) {
val p = it.indexOf('=')
buff.append(" <key>").append(it.substring(2, p)).append("</key>\n")
buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n")
}
moreProperties.forEach { (key, value) ->
buff.append(" <key>").append(key).append("</key>\n")
buff.append(" <string>").append(value).append("</string>\n")
}
return buff.toString().trim()
}
private fun getExecutableFilePatterns(customizer: MacDistributionCustomizer): List<String> {
//noinspection SpellCheckingInspection
return listOf(
"bin/*.sh",
"bin/*.py",
"bin/fsnotifier",
"bin/printenv",
"bin/restarter",
"bin/repair",
"MacOS/*"
) + customizer.extraExecutables
}
internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String {
return "${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents"
}
internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?, context: BuildContext, javaExecutablePath: String?): String {
val executable = context.productProperties.baseFileName
return generateMultiPlatformProductJson(
relativePathToBin = "../bin",
builtinModules = builtinModule,
launch = listOf(
ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
launcherPath = "../MacOS/${executable}",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "../bin/${executable}.vmoptions",
startupWmClass = null,
)
), context = context
)
}
private fun buildMacZip(targetFile: Path,
zipRoot: String,
productJson: String,
allDist: Path,
macDist: Path,
extraFiles: Collection<Map.Entry<Path, String>>,
executableFilePatterns: List<String>,
compressionLevel: Int,
errorsConsumer: (String) -> Unit) {
spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.use {
val fs = targetFile.fileSystem
val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") }
val entryCustomizer: EntryCustomizer = { entry, file, relativeFile ->
when {
patterns.any { it.matches(relativeFile) } -> entry.unixMode = executableFileUnixMode
SystemInfo.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions (file) -> {
errorsConsumer("Executable permissions of $relativeFile won't be set in $targetFile. " +
"Please make sure that executable file patterns are updated.")
}
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray())
val fileFilter: (Path, Path) -> Boolean = { sourceFile, relativeFile ->
val path = relativeFile.toString()
if (path.endsWith(".txt") && !path.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/${FileUtilRt.toSystemIndependentName(path)}", sourceFile)
false
}
else {
true
}
}
zipOutStream.dir(allDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
zipOutStream.dir(macDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
for ((file, relativePath) in extraFiles) {
zipOutStream.entry("$zipRoot/${FileUtilRt.toSystemIndependentName(relativePath)}${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file)
}
}
}
}
}
| apache-2.0 | 3a91690b8399833a7e20eab2489d6e4b | 42.980435 | 158 | 0.668232 | 4.885535 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/Type.kt | 3 | 1281 | package com.intellij.workspaceModel.codegen
import org.jetbrains.deft.Obj
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.deft.TStructure
import com.intellij.workspaceModel.codegen.deft.Field
val Type<*, *>.javaFullName
get() = fqn(packageName, name)
val Type<*, *>.javaSimpleName
get() = name.substringAfterLast('.')
val Type<*, *>.javaBuilderName
get() = "$name.Builder"
val Type<*, *>.javaImplName
get() = "${name.replace(".", "")}Impl"
val Type<*, *>.javaImplFqn
get() = fqn(packageName, javaImplName)
val Type<*, *>.javaImplBuilderName
get() = "${javaImplName}.Builder"
val Type<*, *>.javaSuperType
get() = if (base == null) "Obj" else base!!.javaSimpleName
val Type<*, *>.javaImplSuperType
get() = if (base == null) "ObjImpl" else base!!.javaImplFqn
val TStructure<*, *>.fieldsToStore: List<Field<out Obj, Any?>>
get() = newFields.filter { !it.isOverride && it.hasDefault == Field.Default.none }
val TStructure<*, *>.builderFields: List<Field<out Obj, Any?>>
get() = allFields.filter { it.hasDefault == Field.Default.none }
val TStructure<*, *>.allNonSystemFields: List<Field<out Obj, Any?>>
get() = allFields.filter { it.name != "parent" && it.name != "name" }
| apache-2.0 | 1b6db42bb2127c82445bcc24c505db59 | 31.025 | 84 | 0.69555 | 3.528926 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityToParentImpl.kt | 2 | 8087 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityToParentImpl: MainEntityToParent, WorkspaceEntityBase() {
companion object {
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(MainEntityToParent::class.java, AttachedEntityToParent::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CHILD_CONNECTION_ID,
)
}
override val child: AttachedEntityToParent?
get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)
@JvmField var _x: String? = null
override val x: String
get() = _x!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityToParentData?): ModifiableWorkspaceEntityBase<MainEntityToParent>(), MainEntityToParent.Builder {
constructor(): this(MainEntityToParentData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntityToParent is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field MainEntityToParent#entitySource should be initialized")
}
if (!getEntityData().isXInitialized()) {
error("Field MainEntityToParent#x should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var child: AttachedEntityToParent?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? AttachedEntityToParent
} else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? AttachedEntityToParent
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override fun getEntityData(): MainEntityToParentData = result ?: super.getEntityData() as MainEntityToParentData
override fun getEntityClass(): Class<MainEntityToParent> = MainEntityToParent::class.java
}
}
class MainEntityToParentData : WorkspaceEntityData<MainEntityToParent>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntityToParent> {
val modifiable = MainEntityToParentImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): MainEntityToParent {
val entity = MainEntityToParentImpl()
entity._x = x
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntityToParent::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityToParentData
if (this.entitySource != other.entitySource) return false
if (this.x != other.x) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityToParentData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
} | apache-2.0 | dacbb88c9d980e142a073f7392850e17 | 38.453659 | 191 | 0.631136 | 5.834776 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt | 2 | 33501 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.openapi.util.Key
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult.StrictSuccess
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult.WeakSuccess
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiUnificationResult
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.inspections.PublicApiImplicitTypeInspection
import org.jetbrains.kotlin.idea.inspections.UseExpressionBodyInspection
import org.jetbrains.kotlin.idea.intentions.InfixCallToOrdinaryIntention
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.idea.refactoring.introduce.*
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.*
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValueBoxer.AsTuple
import org.jetbrains.kotlin.idea.refactoring.removeTemplateEntryBracesIfPossible
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.psi.patternMatching.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.isFlexible
import java.util.*
private fun buildSignature(config: ExtractionGeneratorConfiguration, renderer: DescriptorRenderer): CallableBuilder {
val extractionTarget = config.generatorOptions.target
if (!extractionTarget.isAvailable(config.descriptor)) {
val message = KotlinBundle.message("error.text.can.t.generate.0.1",
extractionTarget.targetName,
config.descriptor.extractionData.codeFragmentText
)
throw BaseRefactoringProcessor.ConflictsInTestsException(listOf(message))
}
val builderTarget = when (extractionTarget) {
ExtractionTarget.FUNCTION, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> CallableBuilder.Target.FUNCTION
else -> CallableBuilder.Target.READ_ONLY_PROPERTY
}
return CallableBuilder(builderTarget).apply {
val visibility = config.descriptor.visibility?.value ?: ""
fun TypeParameter.isReified() = originalDeclaration.hasModifier(KtTokens.REIFIED_KEYWORD)
val shouldBeInline = config.descriptor.typeParameters.any { it.isReified() }
val optInAnnotation = if (config.generatorOptions.target != ExtractionTarget.FUNCTION || config.descriptor.optInMarkers.isEmpty()) {
""
} else {
val innerText = config.descriptor.optInMarkers.joinToString(separator = ", ") { "${it.shortName().render()}::class" }
"@${OptInNames.OPT_IN_FQ_NAME.shortName().render()}($innerText)\n"
}
val annotations = if (config.descriptor.annotations.isEmpty()) {
""
} else {
config.descriptor.annotations.joinToString(separator = "\n", postfix = "\n") { renderer.renderAnnotation(it) }
}
val extraModifiers = config.descriptor.modifiers.map { it.value } +
listOfNotNull(if (shouldBeInline) KtTokens.INLINE_KEYWORD.value else null) +
listOfNotNull(if (config.generatorOptions.isConst) KtTokens.CONST_KEYWORD.value else null)
val modifiers = if (visibility.isNotEmpty()) listOf(visibility) + extraModifiers else extraModifiers
modifier(annotations + optInAnnotation + modifiers.joinToString(separator = " "))
typeParams(
config.descriptor.typeParameters.map {
val typeParameter = it.originalDeclaration
val bound = typeParameter.extendsBound
buildString {
if (it.isReified()) {
append(KtTokens.REIFIED_KEYWORD.value)
append(' ')
}
append(typeParameter.name)
if (bound != null) {
append(" : ")
append(bound.text)
}
}
}
)
fun KotlinType.typeAsString() = renderer.renderType(this)
config.descriptor.receiverParameter?.let {
val receiverType = it.parameterType
val receiverTypeAsString = receiverType.typeAsString()
receiver(if (receiverType.isFunctionType) "($receiverTypeAsString)" else receiverTypeAsString)
}
name(config.generatorOptions.dummyName ?: config.descriptor.name)
config.descriptor.parameters.forEach { parameter ->
param(parameter.name, parameter.parameterType.typeAsString())
}
with(config.descriptor.returnType) {
if (KotlinBuiltIns.isUnit(this) || isError || extractionTarget == ExtractionTarget.PROPERTY_WITH_INITIALIZER) {
noReturnType()
} else {
returnType(typeAsString())
}
}
typeConstraints(config.descriptor.typeParameters.flatMap { it.originalConstraints }.map { it.text!! })
}
}
fun ExtractionGeneratorConfiguration.getSignaturePreview(renderer: DescriptorRenderer) = buildSignature(this, renderer).asString()
fun ExtractionGeneratorConfiguration.getDeclarationPattern(
descriptorRenderer: DescriptorRenderer = IdeDescriptorRenderers.SOURCE_CODE
): String {
val extractionTarget = generatorOptions.target
if (!extractionTarget.isAvailable(descriptor)) {
throw BaseRefactoringProcessor.ConflictsInTestsException(
listOf(
KotlinBundle.message("error.text.can.t.generate.0.1",
extractionTarget.targetName,
descriptor.extractionData.codeFragmentText
)
)
)
}
return buildSignature(this, descriptorRenderer).let { builder ->
builder.transform {
for (i in generateSequence(indexOf('$')) { indexOf('$', it + 2) }) {
if (i < 0) break
insert(i + 1, '$')
}
}
when (extractionTarget) {
ExtractionTarget.FUNCTION,
ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION,
ExtractionTarget.PROPERTY_WITH_GETTER -> builder.blockBody("$0")
ExtractionTarget.PROPERTY_WITH_INITIALIZER -> builder.initializer("$0")
ExtractionTarget.LAZY_PROPERTY -> builder.lazyBody("$0")
}
builder.asString()
}
}
fun KotlinType.isSpecial(): Boolean {
val classDescriptor = this.constructor.declarationDescriptor as? ClassDescriptor ?: return false
return classDescriptor.name.isSpecial || DescriptorUtils.isLocal(classDescriptor)
}
fun createNameCounterpartMap(from: KtElement, to: KtElement): Map<KtSimpleNameExpression, KtSimpleNameExpression> {
return from.collectDescendantsOfType<KtSimpleNameExpression>().zip(to.collectDescendantsOfType<KtSimpleNameExpression>()).toMap()
}
class DuplicateInfo(
val range: KotlinPsiRange,
val controlFlow: ControlFlow,
val arguments: List<String>
)
fun ExtractableCodeDescriptor.findDuplicates(): List<DuplicateInfo> {
fun processWeakMatch(match: WeakSuccess<*>, newControlFlow: ControlFlow): Boolean {
val valueCount = controlFlow.outputValues.size
val weakMatches = HashMap(match.weakMatches)
val currentValuesToNew = HashMap<OutputValue, OutputValue>()
fun matchValues(currentValue: OutputValue, newValue: OutputValue): Boolean {
if ((currentValue is Jump) != (newValue is Jump)) return false
if (currentValue.originalExpressions.zip(newValue.originalExpressions).all { weakMatches[it.first] == it.second }) {
currentValuesToNew[currentValue] = newValue
weakMatches.keys.removeAll(currentValue.originalExpressions)
return true
}
return false
}
if (valueCount == 1) {
matchValues(controlFlow.outputValues.first(), newControlFlow.outputValues.first())
} else {
outer@
for (currentValue in controlFlow.outputValues)
for (newValue in newControlFlow.outputValues) {
if ((currentValue is ExpressionValue) != (newValue is ExpressionValue)) continue
if (matchValues(currentValue, newValue)) continue@outer
}
}
return currentValuesToNew.size == valueCount && weakMatches.isEmpty()
}
fun getControlFlowIfMatched(match: KotlinPsiUnificationResult.Success<*>): ControlFlow? {
val analysisResult = extractionData.copy(originalRange = match.range).performAnalysis()
if (analysisResult.status != AnalysisResult.Status.SUCCESS) return null
val newControlFlow = analysisResult.descriptor!!.controlFlow
if (newControlFlow.outputValues.isEmpty()) return newControlFlow
if (controlFlow.outputValues.size != newControlFlow.outputValues.size) return null
val matched = when (match) {
is StrictSuccess -> true
is WeakSuccess -> processWeakMatch(match, newControlFlow)
else -> throw AssertionError("Unexpected unification result: $match")
}
return if (matched) newControlFlow else null
}
val unifierParameters = parameters.map { UnifierParameter(it.originalDescriptor, it.parameterType) }
val unifier = KotlinPsiUnifier(unifierParameters, true)
val scopeElement = getOccurrenceContainer() ?: return Collections.emptyList()
val originalTextRange = extractionData.originalRange.getPhysicalTextRange()
return extractionData
.originalRange
.match(scopeElement, unifier)
.asSequence()
.filter { !(it.range.getPhysicalTextRange().intersects(originalTextRange)) }
.mapNotNull { match ->
val controlFlow = getControlFlowIfMatched(match)
val range = with(match.range) {
(elements.singleOrNull() as? KtStringTemplateEntryWithExpression)?.expression?.toRange() ?: this
}
controlFlow?.let {
DuplicateInfo(range, it, unifierParameters.map { param ->
match.substitution.getValue(param).text!!
})
}
}
.toList()
}
private fun ExtractableCodeDescriptor.getOccurrenceContainer(): PsiElement? {
return extractionData.duplicateContainer ?: extractionData.targetSibling.parent
}
private fun makeCall(
extractableDescriptor: ExtractableCodeDescriptor,
declaration: KtNamedDeclaration,
controlFlow: ControlFlow,
rangeToReplace: KotlinPsiRange,
arguments: List<String>
) {
fun insertCall(anchor: PsiElement, wrappedCall: KtExpression): KtExpression? {
val firstExpression = rangeToReplace.elements.firstOrNull { it is KtExpression } as? KtExpression
if (firstExpression?.isLambdaOutsideParentheses() == true) {
val functionLiteralArgument = firstExpression.getStrictParentOfType<KtLambdaArgument>()!!
return functionLiteralArgument.moveInsideParenthesesAndReplaceWith(wrappedCall, extractableDescriptor.originalContext)
}
if (anchor is KtOperationReferenceExpression) {
val newNameExpression = when (val operationExpression = anchor.parent as? KtOperationExpression ?: return null) {
is KtUnaryExpression -> OperatorToFunctionIntention.convert(operationExpression).second
is KtBinaryExpression -> {
InfixCallToOrdinaryIntention.convert(operationExpression).getCalleeExpressionIfAny()
}
else -> null
}
return newNameExpression?.replaced(wrappedCall)
}
(anchor as? KtExpression)?.extractableSubstringInfo?.let {
return it.replaceWith(wrappedCall)
}
return anchor.replaced(wrappedCall)
}
if (rangeToReplace.isEmpty) return
val anchor = rangeToReplace.elements.first()
val anchorParent = anchor.parent!!
anchor.nextSibling?.let { from ->
val to = rangeToReplace.elements.last()
if (to != anchor) {
anchorParent.deleteChildRange(from, to)
}
}
val calleeName = declaration.name?.quoteIfNeeded()
val callText = when (declaration) {
is KtNamedFunction -> {
val argumentsText = arguments.joinToString(separator = ", ", prefix = "(", postfix = ")")
val typeArguments = extractableDescriptor.typeParameters.map { it.originalDeclaration.name }
val typeArgumentsText = with(typeArguments) {
if (isNotEmpty()) joinToString(separator = ", ", prefix = "<", postfix = ">") else ""
}
"$calleeName$typeArgumentsText$argumentsText"
}
else -> calleeName
}
val anchorInBlock = generateSequence(anchor) { it.parent }.firstOrNull { it.parent is KtBlockExpression }
val block = (anchorInBlock?.parent as? KtBlockExpression) ?: anchorParent
val psiFactory = KtPsiFactory(anchor.project)
val newLine = psiFactory.createNewLine()
if (controlFlow.outputValueBoxer is AsTuple && controlFlow.outputValues.size > 1 && controlFlow.outputValues
.all { it is Initializer }
) {
val declarationsToMerge = controlFlow.outputValues.map { (it as Initializer).initializedDeclaration }
val isVar = declarationsToMerge.first().isVar
if (declarationsToMerge.all { it.isVar == isVar }) {
controlFlow.declarationsToCopy.subtract(declarationsToMerge).forEach {
block.addBefore(psiFactory.createDeclaration(it.text!!), anchorInBlock) as KtDeclaration
block.addBefore(newLine, anchorInBlock)
}
val entries = declarationsToMerge.map { p -> p.name + (p.typeReference?.let { ": ${it.text}" } ?: "") }
anchorInBlock?.replace(
psiFactory.createDestructuringDeclaration("${if (isVar) "var" else "val"} (${entries.joinToString()}) = $callText")
)
return
}
}
val inlinableCall = controlFlow.outputValues.size <= 1
val unboxingExpressions =
if (inlinableCall) {
controlFlow.outputValueBoxer.getUnboxingExpressions(callText ?: return)
} else {
val varNameValidator = Fe10KotlinNewDeclarationNameValidator(block, anchorInBlock, KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE)
val resultVal = Fe10KotlinNameSuggester.suggestNamesByType(extractableDescriptor.returnType, varNameValidator, null).first()
block.addBefore(psiFactory.createDeclaration("val $resultVal = $callText"), anchorInBlock)
block.addBefore(newLine, anchorInBlock)
controlFlow.outputValueBoxer.getUnboxingExpressions(resultVal)
}
val copiedDeclarations = HashMap<KtDeclaration, KtDeclaration>()
for (decl in controlFlow.declarationsToCopy) {
val declCopy = psiFactory.createDeclaration<KtDeclaration>(decl.text!!)
copiedDeclarations[decl] = block.addBefore(declCopy, anchorInBlock) as KtDeclaration
block.addBefore(newLine, anchorInBlock)
}
if (controlFlow.outputValues.isEmpty()) {
anchor.replace(psiFactory.createExpression(callText!!))
return
}
fun wrapCall(outputValue: OutputValue, callText: String): List<PsiElement> {
return when (outputValue) {
is ExpressionValue -> {
val exprText = if (outputValue.callSiteReturn) {
val firstReturn = outputValue.originalExpressions.asSequence().filterIsInstance<KtReturnExpression>().firstOrNull()
val label = firstReturn?.getTargetLabel()?.text ?: ""
"return$label $callText"
} else {
callText
}
Collections.singletonList(psiFactory.createExpression(exprText))
}
is ParameterUpdate ->
Collections.singletonList(
psiFactory.createExpression("${outputValue.parameter.argumentText} = $callText")
)
is Jump -> {
when {
outputValue.elementToInsertAfterCall == null -> Collections.singletonList(psiFactory.createExpression(callText))
outputValue.conditional -> Collections.singletonList(
psiFactory.createExpression("if ($callText) ${outputValue.elementToInsertAfterCall.text}")
)
else -> listOf(
psiFactory.createExpression(callText),
newLine,
psiFactory.createExpression(outputValue.elementToInsertAfterCall.text!!)
)
}
}
is Initializer -> {
val newProperty = copiedDeclarations[outputValue.initializedDeclaration] as KtProperty
newProperty.initializer = psiFactory.createExpression(callText)
Collections.emptyList()
}
else -> throw IllegalArgumentException("Unknown output value: $outputValue")
}
}
val defaultValue = controlFlow.defaultOutputValue
controlFlow.outputValues
.filter { it != defaultValue }
.flatMap { wrapCall(it, unboxingExpressions.getValue(it)) }
.withIndex()
.forEach {
val (i, e) = it
if (i > 0) {
block.addBefore(newLine, anchorInBlock)
}
block.addBefore(e, anchorInBlock)
}
defaultValue?.let {
if (!inlinableCall) {
block.addBefore(newLine, anchorInBlock)
}
insertCall(anchor, wrapCall(it, unboxingExpressions.getValue(it)).first() as KtExpression)?.removeTemplateEntryBracesIfPossible()
}
if (anchor.isValid) {
anchor.delete()
}
}
private var KtExpression.isJumpElementToReplace: Boolean
by NotNullablePsiCopyableUserDataProperty(Key.create("IS_JUMP_ELEMENT_TO_REPLACE"), false)
private var KtReturnExpression.isReturnForLabelRemoval: Boolean
by NotNullablePsiCopyableUserDataProperty(Key.create("IS_RETURN_FOR_LABEL_REMOVAL"), false)
fun ExtractionGeneratorConfiguration.generateDeclaration(
declarationToReplace: KtNamedDeclaration? = null
): ExtractionResult {
val psiFactory = KtPsiFactory(descriptor.extractionData.originalFile)
fun getReturnsForLabelRemoval() = descriptor.controlFlow.outputValues
.flatMapTo(arrayListOf()) { it.originalExpressions.filterIsInstance<KtReturnExpression>() }
fun createDeclaration(): KtNamedDeclaration {
descriptor.controlFlow.jumpOutputValue?.elementsToReplace?.forEach { it.isJumpElementToReplace = true }
getReturnsForLabelRemoval().forEach { it.isReturnForLabelRemoval = true }
return with(descriptor.extractionData) {
if (generatorOptions.inTempFile) {
createTemporaryDeclaration("${getDeclarationPattern()}\n")
} else {
psiFactory.createDeclarationByPattern(
getDeclarationPattern(),
PsiChildRange(originalElements.firstOrNull(), originalElements.lastOrNull())
)
}
}
}
fun getReturnArguments(resultExpression: KtExpression?): List<KtExpression> {
return descriptor.controlFlow.outputValues
.mapNotNull {
when (it) {
is ExpressionValue -> resultExpression
is Jump -> if (it.conditional) psiFactory.createExpression("false") else null
is ParameterUpdate -> psiFactory.createExpression(it.parameter.nameForRef)
is Initializer -> psiFactory.createExpression(it.initializedDeclaration.name!!)
else -> throw IllegalArgumentException("Unknown output value: $it")
}
}
}
fun KtExpression.replaceWithReturn(replacingExpression: KtReturnExpression) {
descriptor.controlFlow.defaultOutputValue?.let {
val boxedExpression = replaced(replacingExpression).returnedExpression!!
descriptor.controlFlow.outputValueBoxer.extractExpressionByValue(boxedExpression, it)
}
}
fun getPublicApiInspectionIfEnabled(): PublicApiImplicitTypeInspection? {
val project = descriptor.extractionData.project
val inspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
val inspectionProfile = inspectionProfileManager.currentProfile
val state = inspectionProfile.getToolsOrNull("PublicApiImplicitType", project)?.defaultState ?: return null
if (!state.isEnabled || state.level == HighlightDisplayLevel.DO_NOT_SHOW) return null
return state.tool.tool as? PublicApiImplicitTypeInspection
}
fun useExplicitReturnType(): Boolean {
if (descriptor.returnType.isFlexible()) return true
val inspection = getPublicApiInspectionIfEnabled() ?: return false
val targetClass = (descriptor.extractionData.targetSibling.parent as? KtClassBody)?.parent as? KtClassOrObject
if ((targetClass != null && targetClass.isLocal) || descriptor.extractionData.isLocal()) return false
val visibility = (descriptor.visibility ?: KtTokens.DEFAULT_VISIBILITY_KEYWORD).toVisibility()
return when {
visibility.isPublicAPI -> true
inspection.reportInternal && visibility == DescriptorVisibilities.INTERNAL -> true
inspection.reportPrivate && visibility == DescriptorVisibilities.PRIVATE -> true
else -> false
}
}
fun adjustDeclarationBody(declaration: KtNamedDeclaration) {
val body = declaration.getGeneratedBody()
(body.blockExpressionsOrSingle().singleOrNull() as? KtExpression)?.let {
if (it.mustBeParenthesizedInInitializerPosition()) {
it.replace(psiFactory.createExpressionByPattern("($0)", it))
}
}
val jumpValue = descriptor.controlFlow.jumpOutputValue
if (jumpValue != null) {
val replacingReturn = psiFactory.createExpression(if (jumpValue.conditional) "return true" else "return")
body.collectDescendantsOfType<KtExpression> { it.isJumpElementToReplace }.forEach {
it.replace(replacingReturn)
it.isJumpElementToReplace = false
}
}
body.collectDescendantsOfType<KtReturnExpression> { it.isReturnForLabelRemoval }.forEach {
it.getTargetLabel()?.delete()
it.isReturnForLabelRemoval = false
}
/*
* Sort by descending position so that internals of value/type arguments in calls and qualified types are replaced
* before calls/types themselves
*/
val currentRefs = body
.collectDescendantsOfType<KtSimpleNameExpression> { it.resolveResult != null }
.sortedByDescending { it.startOffset }
currentRefs.forEach {
val resolveResult = it.resolveResult!!
val currentRef = if (it.isValid) {
it
} else {
body.findDescendantOfType { expr -> expr.resolveResult == resolveResult } ?: return@forEach
}
val originalRef = resolveResult.originalRefExpr
val newRef = descriptor.replacementMap[originalRef]
.fold(currentRef as KtElement) { ref, replacement -> replacement(descriptor, ref) }
(newRef as? KtSimpleNameExpression)?.resolveResult = resolveResult
}
if (generatorOptions.target == ExtractionTarget.PROPERTY_WITH_INITIALIZER) return
if (body !is KtBlockExpression) throw AssertionError("Block body expected: ${descriptor.extractionData.codeFragmentText}")
val firstExpression = body.statements.firstOrNull()
if (firstExpression != null) {
for (param in descriptor.parameters) {
param.mirrorVarName?.let { varName ->
body.addBefore(psiFactory.createProperty(varName, null, true, param.name), firstExpression)
body.addBefore(psiFactory.createNewLine(), firstExpression)
}
}
}
val defaultValue = descriptor.controlFlow.defaultOutputValue
val lastExpression = body.statements.lastOrNull()
if (lastExpression is KtReturnExpression) return
val defaultExpression =
if (!generatorOptions.inTempFile && defaultValue != null && descriptor.controlFlow.outputValueBoxer
.boxingRequired && lastExpression!!.isMultiLine()
) {
val varNameValidator = Fe10KotlinNewDeclarationNameValidator(body, lastExpression, KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE)
val resultVal = Fe10KotlinNameSuggester.suggestNamesByType(defaultValue.valueType, varNameValidator, null).first()
body.addBefore(psiFactory.createDeclaration("val $resultVal = ${lastExpression.text}"), lastExpression)
body.addBefore(psiFactory.createNewLine(), lastExpression)
psiFactory.createExpression(resultVal)
} else lastExpression
val returnExpression =
descriptor.controlFlow.outputValueBoxer.getReturnExpression(getReturnArguments(defaultExpression), psiFactory) ?: return
when (generatorOptions.target) {
ExtractionTarget.LAZY_PROPERTY, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> {
// In the case of lazy property absence of default value means that output values are of OutputValue.Initializer type
// We just add resulting expressions without return, since returns are prohibited in the body of lazy property
if (defaultValue == null) {
body.appendElement(returnExpression.returnedExpression!!)
}
return
}
else -> {}
}
when {
defaultValue == null -> body.appendElement(returnExpression)
!defaultValue.callSiteReturn -> lastExpression!!.replaceWithReturn(returnExpression)
}
if (generatorOptions.allowExpressionBody) {
val bodyExpression = body.statements.singleOrNull()
val bodyOwner = body.parent as KtDeclarationWithBody
val useExpressionBodyInspection = UseExpressionBodyInspection()
if (bodyExpression != null && useExpressionBodyInspection.isActiveFor(bodyOwner)) {
useExpressionBodyInspection.simplify(bodyOwner, !useExplicitReturnType())
}
}
}
fun insertDeclaration(declaration: KtNamedDeclaration, anchor: PsiElement): KtNamedDeclaration {
declarationToReplace?.let { return it.replace(declaration) as KtNamedDeclaration }
return with(descriptor.extractionData) {
val targetContainer = anchor.parent!!
// TODO: Get rid of explicit new-lines in favor of formatter rules
val emptyLines = psiFactory.createWhiteSpace("\n\n")
if (insertBefore) {
(targetContainer.addBefore(declaration, anchor) as KtNamedDeclaration).apply {
targetContainer.addBefore(emptyLines, anchor)
}
} else {
(targetContainer.addAfter(declaration, anchor) as KtNamedDeclaration).apply {
if (!(targetContainer is KtClassBody && (targetContainer.parent as? KtClass)?.isEnum() == true)) {
targetContainer.addAfter(emptyLines, anchor)
}
}
}
}
}
val duplicates = if (generatorOptions.inTempFile) Collections.emptyList() else descriptor.duplicates
val anchor = with(descriptor.extractionData) {
val targetParent = targetSibling.parent
val anchorCandidates = duplicates.mapTo(arrayListOf()) { it.range.elements.first().substringContextOrThis }
anchorCandidates.add(targetSibling)
if (targetSibling is KtEnumEntry) {
anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry })
}
val marginalCandidate = if (insertBefore) {
anchorCandidates.minByOrNull { it.startOffset }!!
} else {
anchorCandidates.maxByOrNull { it.startOffset }!!
}
// Ascend to the level of targetSibling
marginalCandidate.parentsWithSelf.first { it.parent == targetParent }
}
val shouldInsert = !(generatorOptions.inTempFile || generatorOptions.target == ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION)
val declaration = createDeclaration().let { if (shouldInsert) insertDeclaration(it, anchor) else it }
adjustDeclarationBody(declaration)
if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, Collections.emptyMap())
val replaceInitialOccurrence = {
val arguments = descriptor.parameters.map { it.argumentText }
makeCall(descriptor, declaration, descriptor.controlFlow, descriptor.extractionData.originalRange, arguments)
}
if (!generatorOptions.delayInitialOccurrenceReplacement) replaceInitialOccurrence()
if (shouldInsert) {
ShortenReferences.DEFAULT.process(declaration)
}
if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, emptyMap())
val duplicateReplacers = HashMap<KotlinPsiRange, () -> Unit>().apply {
if (generatorOptions.delayInitialOccurrenceReplacement) {
put(descriptor.extractionData.originalRange, replaceInitialOccurrence)
}
putAll(duplicates.map {
val smartListRange = KotlinPsiRange.SmartListRange(it.range.elements)
smartListRange to { makeCall(descriptor, declaration, it.controlFlow, smartListRange, it.arguments) }
})
}
if (descriptor.typeParameters.isNotEmpty()) {
for (ref in ReferencesSearch.search(declaration, LocalSearchScope(descriptor.getOccurrenceContainer()!!))) {
val typeArgumentList = (ref.element.parent as? KtCallExpression)?.typeArgumentList ?: continue
if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(typeArgumentList, false)) {
typeArgumentList.delete()
}
}
}
if (declaration is KtProperty) {
if (declaration.isExtensionDeclaration() && !declaration.isTopLevel) {
val receiverTypeReference = (declaration as? KtCallableDeclaration)?.receiverTypeReference
receiverTypeReference?.siblings(withItself = false)?.firstOrNull { it.node.elementType == KtTokens.DOT }?.delete()
receiverTypeReference?.delete()
}
if ((declaration.descriptor as? PropertyDescriptor)?.let { DescriptorUtils.isOverride(it) } == true) {
val scope = declaration.getResolutionScope()
val newName = Fe10KotlinNameSuggester.suggestNameByName(descriptor.name) {
it != descriptor.name && scope.getAllAccessibleVariables(Name.identifier(it)).isEmpty()
}
declaration.setName(newName)
}
}
CodeStyleManager.getInstance(descriptor.extractionData.project).reformat(declaration)
return ExtractionResult(this, declaration, duplicateReplacers)
}
| apache-2.0 | f19bd1638e9783f3dc82fd11bf3ecf1c | 45.3361 | 153 | 0.67789 | 5.632313 | false | false | false | false |
Andreyv1989/KotlinLessons | src/i_introduction/_7_Nullable_Types/NullableTypes.kt | 1 | 1086 | package i_introduction._7_Nullable_Types
import util.TODO
import util.doc7
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0
}
fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO(
"""
Task 7.
Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression.
Declarations of Client, PersonalInfo and Mailer are given below.
""",
documentation = doc7(),
references = { JavaCode7().sendMessageToClient(client, message, mailer) }
)
fun sendMessageToClient( client: Client?, message: String?, mailer: Mailer)
{
var email= client?.personalInfo?.email
if (email !=null && message != null)
mailer.sendMessage(email,message)
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
| mit | 00a794657061866805558e891fe3f6b6 | 28.351351 | 88 | 0.67035 | 3.978022 | false | false | false | false |
zephir-lang/idea-plugin | src/main/kotlin/com/zephir/ide/color/ZephirColorSettingsPage.kt | 1 | 2311 | // Copyright (c) 2014-2020 Zephir Team
//
// This source file is subject the MIT license, that is bundled with
// this package in the file LICENSE, and is available through the
// world-wide-web at the following url:
//
// https://github.com/zephir-lang/idea-plugin/blob/master/LICENSE
package com.zephir.ide.color
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import com.zephir.ide.highlight.ZephirSyntaxHighlighter
import com.zephir.ide.icons.ZephirIcons
class ZephirColorSettingsPage : ColorSettingsPage {
private val attributes = ZephirColor.values().map {
it.attributesDescriptor
}.toTypedArray()
override fun getHighlighter() = ZephirSyntaxHighlighter()
override fun getIcon() = ZephirIcons.FILE
override fun getAttributeDescriptors() = attributes
override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName() = "Zephir"
override fun getDemoText() = demoCodeText
override fun getAdditionalHighlightingTagToDescriptorMap(): MutableMap<String, TextAttributesKey> {
// TODO(serghei): Implement me
return mutableMapOf()
}
}
private const val demoCodeText = """
%{
// top statement before namespace, add to after headers
#define MAX_FACTOR 10
}%
namespace Acme;
%{
// top statement before class, add to after
// headers test include .h
#include "kernel/require.h"
}%
// a single line comment
use Acme\Some\Buz;
class Foo extends Bar implements Baz, Buz
{
const FOO_BAR = 30 * 24 * 60;
/**
* @var int
*/
public num;
/** @var string */
static private str;
public function __construct(int num, string str, array arr)
{
var abc;
int a = 0;
string s = "test";
char c = 'A';
%{
a = MAX_FACTOR;
%}
if fetch abc, arr[str] {
let this->num = [abc: a, c: c];
} elseif isset arr[num] {
let self::str = [str: a, c: c];
}
}
private function calc(
<Arithmetic> l,
<Arithmetic> r,
<Bitwise> op
) -> <Result> | null {
return <Result> op->calc(l, r);
}
}
"""
| mit | 1cd197015eeef6f9714aa6875bd70fb8 | 24.677778 | 103 | 0.655993 | 3.950427 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/workers/reminder/ReminderNotification.kt | 1 | 1435 | package org.wordpress.android.workers.reminder
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_DEFAULT
data class ReminderNotification(
val channel: String,
val contentIntentBuilder: () -> PendingIntent,
val deleteIntentBuilder: (() -> PendingIntent)? = null,
val contentTitle: String,
val contentText: String,
val priority: Int = PRIORITY_DEFAULT,
val category: String,
val autoCancel: Boolean = true,
val colorized: Boolean = true,
val color: Int,
val smallIcon: Int,
val firstAction: NotificationCompat.Action? = null,
val secondAction: NotificationCompat.Action? = null
) {
fun asNotificationCompatBuilder(context: Context): NotificationCompat.Builder {
return NotificationCompat.Builder(context, channel)
.setContentIntent(contentIntentBuilder.invoke())
.setDeleteIntent(deleteIntentBuilder?.invoke())
.setContentTitle(contentTitle)
.setContentText(contentText)
.setPriority(priority)
.setCategory(category)
.setAutoCancel(autoCancel)
.setColorized(colorized)
.setColor(color)
.setSmallIcon(smallIcon)
.addAction(firstAction)
.addAction(secondAction)
}
}
| gpl-2.0 | fbe7771317eecad140fda9fb16d050bc | 36.763158 | 83 | 0.66899 | 5.143369 | false | false | false | false |
edwardharks/Aircraft-Recognition | androidcommon/src/test/kotlin/com/edwardharker/aircraftrecognition/android/FakeAircraftSharedPreferences.kt | 1 | 847 | package com.edwardharker.aircraftrecognition.android
import com.edwardharker.aircraftrecognition.android.preferences.AircraftSharedPreferences
class FakeAircraftSharedPreferences(
private val getIntReturns: Pair<String, Int>? = null,
private val containsReturns: Pair<String, Boolean>? = null
) : AircraftSharedPreferences {
private val _saveIntCalls = mutableListOf<Pair<String, Int>>()
val saveIntCalls: List<Pair<String, Int>> = _saveIntCalls
override fun getInt(key: String, default: Int): Int {
return if (getIntReturns?.first == key) getIntReturns.second else 0
}
override fun saveInt(key: String, value: Int) {
_saveIntCalls.add(key to value)
}
override fun contains(key: String): Boolean {
return if (containsReturns?.first == key) containsReturns.second else false
}
}
| gpl-3.0 | 40c78a857096e01b00a27efeda5e3d4d | 35.826087 | 89 | 0.727273 | 4.299492 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/AbstractIdeKotlinAnnotationsResolverTest.kt | 5 | 2696 | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.analysis.providers
import com.intellij.openapi.components.service
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.analysis.providers.KotlinAnnotationsResolver
import org.jetbrains.kotlin.analysis.providers.KotlinAnnotationsResolverFactory
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtAnnotated
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import java.io.File
abstract class AbstractIdeKotlinAnnotationsResolverTest : KotlinLightCodeInsightFixtureTestCase() {
private val expectedAnnotationsDirective: String = "// ANNOTATION:"
override fun isFirPlugin(): Boolean = true
private val annotationsResolver: KotlinAnnotationsResolver
get() = project.service<KotlinAnnotationsResolverFactory>().createAnnotationResolver(GlobalSearchScope.projectScope(project))
fun doTest(path: String) {
val mainTestFile = File(path)
val allTestFiles = listOf(mainTestFile) + resolveDependencyFiles(mainTestFile)
myFixture.configureByFiles(*allTestFiles.toTypedArray())
val annotatedElement = myFixture.elementAtCaret.parentOfType<KtAnnotated>(withSelf = true)
?: error("Expected KtAnnotation element at the caret: ${myFixture.elementAtCaret.getElementTextWithContext()}")
val actualAnnotations = annotationsResolver.annotationsOnDeclaration(annotatedElement).sortedBy { it.toString() }
val expectedAnnotations = InTextDirectivesUtils.findListWithPrefixes(
myFixture.editor.document.text,
expectedAnnotationsDirective
).filter { it.isNotEmpty() }
assertEquals(
"Expected annotations not found on the element under the caret:",
expectedAnnotations,
actualAnnotations.map { it.toString() }
)
}
private fun resolveDependencyFiles(mainFile: File): List<File> {
val dependencySuffixes = listOf(".dependency.kt", ".dependency1.kt", ".dependency2.kt")
return dependencySuffixes
.map { suffix -> mainFile.resolveSiblingWithDifferentExtension(suffix) }
.filter { it.exists() }
}
private fun File.resolveSiblingWithDifferentExtension(newExtension: String): File =
resolveSibling("$nameWithoutExtension$newExtension")
}
| apache-2.0 | 8b97fe145f40c292dc9eb5d6caa7d250 | 44.694915 | 133 | 0.75816 | 5.194605 | false | true | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/model/ThreadList.kt | 1 | 1747 | package io.github.bkmioa.nexusrss.model
import org.jsoup.nodes.Element
import pl.droidsonroids.jspoon.ElementConverter
import pl.droidsonroids.jspoon.annotation.Selector
import java.text.SimpleDateFormat
import java.util.*
class ThreadList {
@Selector(".torrents", index = 0, converter = ThreadListConverter::class)
var list: List<Item>? = null
class ThreadListConverter : ElementConverter<List<Item>> {
override fun convert(node: Element, selector: Selector): List<Item>? {
val trs = node.child(0).children() ?: return null
val items = ArrayList<Item>()
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
for (tr in trs) {
if (tr.select(".colhead").isNotEmpty()) continue
val item = Item()
val tds = tr.children()
item.imageUrl = tr.select(".torrentimg img").first()?.absUrl("src")
val selectTitle = tr.select("a[title]")
item.title = selectTitle.attr("title")
item.link = selectTitle.first()?.absUrl("href")
item.subTitle = tr.select(".embedded:has(a[title])").takeIf { it.select("br").isNotEmpty() }?.first()?.childNodes()?.last()?.toString() ?: item.title
item.pubDate = dateFormat.parse(tds[3].select("span").attr("title"))
item.sizeText = tds[4].text()
item.description = ""
item.author = tds[9].select("b").text()
item.category = tds[0].select("img").attr("title")
item.torrentUrl = tr.select("a:has(.download)").first()?.absUrl("href")
items.add(item)
}
return items
}
}
} | apache-2.0 | aa04bac82250463524df989cbe597b8d | 41.634146 | 165 | 0.579279 | 4.240291 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/metadata/TablePrivilegesResult.kt | 1 | 1919 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.kotlinsql.metadata
import io.github.pdvrieze.kotlinsql.UnmanagedSql
import io.github.pdvrieze.kotlinsql.dml.ResultSetWrapper
import io.github.pdvrieze.kotlinsql.metadata.impl.KeysResultImpl
import io.github.pdvrieze.kotlinsql.metadata.impl.TableMetaResultBase
import io.github.pdvrieze.kotlinsql.metadata.impl.TablePrivilegesResultImpl
import java.sql.ResultSet
interface TablePrivilegesResult: TableMetaResultBase<TablePrivilegesResult.Data> {
val grantor: String?
val grantee: String
val isGrantable: Boolean
val privilege: String
override fun data(): Data = Data(this)
class Data(data: TablePrivilegesResult): TableMetaResultBase.Data<Data>(data), TablePrivilegesResult {
override val grantor: String? = data.grantor
override val grantee: String = data.grantee
override val isGrantable: Boolean = data.isGrantable
override val privilege: String = data.privilege
override fun data(): Data = this
}
companion object {
@UnmanagedSql
operator fun invoke(r: ResultSet): ResultSetWrapper<TablePrivilegesResult, Data> = TablePrivilegesResultImpl(r)
}
}
| apache-2.0 | 0cb71064086ab136bad283c77830fbe7 | 36.627451 | 119 | 0.751954 | 4.208333 | false | false | false | false |
jk1/intellij-community | python/src/com/jetbrains/python/inspections/stdlib/PyStdlibInspectionExtension.kt | 3 | 2408 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections.stdlib
import com.intellij.psi.PsiReference
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleType
import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleTypeProvider
import com.jetbrains.python.codeInsight.stdlib.PyStdlibClassMembersProvider
import com.jetbrains.python.inspections.PyInspectionExtension
import com.jetbrains.python.psi.PyElement
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.types.PyClassLikeType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
class PyStdlibInspectionExtension : PyInspectionExtension() {
companion object {
private val NAMEDTUPLE_SPECIAL_ATTRIBUTES = setOf("_make", "_asdict", "_replace", "_source", "_fields")
}
override fun ignoreInitNewSignatures(original: PyFunction, complementary: PyFunction): Boolean {
return PyNames.TYPE_ENUM == complementary.containingClass?.qualifiedName
}
override fun ignoreUnresolvedMember(type: PyType, name: String, context: TypeEvalContext): Boolean {
if (type is PyClassLikeType) {
return type is PyNamedTupleType && type.fields.containsKey(name) ||
type.getAncestorTypes(context).filterIsInstance<PyNamedTupleType>().any { it.fields.containsKey(name) }
}
return false
}
override fun ignoreUnresolvedReference(node: PyElement, reference: PsiReference, context: TypeEvalContext): Boolean {
if (node is PyReferenceExpression && node.isQualified) {
val qualifier = node.qualifier
if (qualifier is PyReferenceExpression) {
return PyStdlibClassMembersProvider.referenceToMockPatch(qualifier, context) &&
PyStdlibClassMembersProvider.calcMockPatchMembers(qualifier).any { it.name == node.name }
}
}
return false
}
override fun ignoreProtectedSymbol(expression: PyReferenceExpression, context: TypeEvalContext): Boolean {
val qualifier = expression.qualifier
return qualifier != null &&
expression.referencedName in NAMEDTUPLE_SPECIAL_ATTRIBUTES &&
PyNamedTupleTypeProvider.isNamedTuple(context.getType(qualifier), context)
}
} | apache-2.0 | d70a6e43104d7681e6c9e157f0133939 | 43.611111 | 140 | 0.775748 | 4.703125 | false | false | false | false |
linheimx/ZimuDog | app/src/main/java/com/linheimx/zimudog/vp/search/ZimuDialog.kt | 1 | 9610 | package com.linheimx.zimudog.vp.search
import android.app.Dialog
import android.app.Notification
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.NotificationCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.linheimx.zimudog.App
import com.linheimx.zimudog.R
import com.linheimx.zimudog.m.bean.*
import com.linheimx.zimudog.m.net.ApiManger
import com.linheimx.zimudog.utils.Utils
import java.util.concurrent.TimeUnit
import com.linheimx.zimudog.utils.bindView
import com.linheimx.zimudog.utils.rxbus.RxBus
import com.linheimx.zimudog.utils.rxbus.RxBus_Behavior
import com.linheimx.zimudog.vp.main.MainActivity
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloader
import com.liulishuo.filedownloader.model.FileDownloadStatus
import com.liulishuo.filedownloader.notification.BaseNotificationItem
import com.liulishuo.filedownloader.notification.FileDownloadNotificationHelper
import com.liulishuo.filedownloader.notification.FileDownloadNotificationListener
import com.liulishuo.filedownloader.util.FileDownloadHelper
import es.dmoral.toasty.Toasty
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
/**
* Created by x1c on 2017/4/23.
*/
class ZimuDialog : DialogFragment() {
val rv: RecyclerView by bindView(R.id.rv)
lateinit var _Dialog: Dialog
lateinit var _view: View
lateinit var _QuickAdapter: QuickAdapter
lateinit var _CompositeDisposable: CompositeDisposable
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_view = inflater!!.inflate(R.layout.dialog_zimu, null)
_view.y = -2500f
return _view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_CompositeDisposable = CompositeDisposable()
rv.setHasFixedSize(true)
rv.layoutManager = LinearLayoutManager(activity)
val bundle = arguments
val movie = bundle!!.getSerializable("movie") as Movie
_QuickAdapter = QuickAdapter()
_QuickAdapter.bindToRecyclerView(rv)
_QuickAdapter.setEmptyView(R.layout.rv_loding_view2)
ApiManger.api.getHtml(movie.detail_url)
.subscribeOn(Schedulers.io())
.delay(1000, TimeUnit.MILLISECONDS)
.flatMap { ApiManger.apiParse.parse_Zimus(it.string()) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<Resp_Zimus> {
override fun onSubscribe(d: Disposable) {
_CompositeDisposable.add(d)
}
override fun onNext(t: Resp_Zimus) {
_QuickAdapter.setNewData(t.obj)
}
override fun onError(e: Throwable) {
_QuickAdapter.setEmptyView(R.layout.rv_error_view)
}
override fun onComplete() {
}
})
}
override fun onResume() {
super.onResume()
// show the view
_view.animate()
.alpha(1f)
.y(0f)
.setDuration(680)
.start()
val dialog = dialog
if (dialog != null) {
_Dialog = dialog
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
}
override fun onDestroyView() {
super.onDestroyView()
_CompositeDisposable.dispose()
}
inner class QuickAdapter : BaseQuickAdapter<Zimu, BaseViewHolder>(R.layout.rv_item_zimu) {
override fun addData(zimuList: List<Zimu>) {
if (mData == null) {
mData = zimuList
} else {
mData.addAll(zimuList)
}
notifyDataSetChanged()
}
override fun convert(helper: BaseViewHolder, item: Zimu) {
// logo
val picUrl = item.avatar_url
if (picUrl.contains("jollyroger")) {
Glide.with(this@ZimuDialog)
.load(R.drawable.doge_512_512)
.crossFade()
.into(helper.getView<View>(R.id.img) as ImageView)
} else {
Glide.with(this@ZimuDialog)
.load(item.avatar_url)
.crossFade()
.into(helper.getView<View>(R.id.img) as ImageView)
}
// title
helper.setText(R.id.tv_name, item.name)
// 点击事件
helper.itemView.setOnClickListener {
if (!Utils.isNetConnected) {
Toasty.info(App.get()!!, "请检查您的网络!", Toast.LENGTH_SHORT, true).show()
} else {
Toasty.success(App.get()!!, "已加入下载队列", Toast.LENGTH_SHORT, true).show()
ApiManger.api.getHtml(item.detail_url)
.subscribeOn(Schedulers.io())
.flatMap { ApiManger.apiParse.parse_Zimus_DURL(it.string()) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<Resp_Zimus_DURL> {
override fun onSubscribe(d: Disposable) {
_CompositeDisposable.add(d)
}
override fun onNext(t: Resp_Zimus_DURL) {
if (t.success) {
var fileName = item.name// 名字中可能包含 /
fileName = fileName.replace('/', '_')
val filePath = Utils.rootDirPath + "/" + fileName
download(t.obj!!, filePath)
} else {
Toasty.error(App.get()!!, "下载失败:" + t.errorMsg, Toast.LENGTH_SHORT, true).show()
}
}
override fun onError(e: Throwable) {
_QuickAdapter.setEmptyView(R.layout.rv_error_view)
}
override fun onComplete() {
}
})
}
}
}
}
fun download(url: String, path: String) {
FileDownloader.getImpl().create(url)
.setPath(path)
.setAutoRetryTimes(2)
.setListener(NotificationListener(FileDownloadNotificationHelper<NotificationItem>()))
.start()
}
companion object {
fun newInstance(movie: Movie): ZimuDialog {
val dialog = ZimuDialog()
val bundle = Bundle()
bundle.putSerializable("movie", movie)
dialog.arguments = bundle
return dialog
}
}
}
class NotificationListener(helper: FileDownloadNotificationHelper<*>) : FileDownloadNotificationListener(helper) {
override fun create(task: BaseDownloadTask): BaseNotificationItem {
return NotificationItem(task.id,
task.filename, "(゜-゜)つロ")
}
override fun completed(task: BaseDownloadTask?) {
super.completed(task)
RxBus_Behavior.post(Ok())
}
}
class NotificationItem constructor(id: Int, title: String, desc: String) : BaseNotificationItem(id, title, desc) {
var pendingIntent: PendingIntent
var builder: NotificationCompat.Builder
init {
val intents = arrayOfNulls<Intent>(1)
intents[0] = Intent(App.get(), MainActivity::class.java)
this.pendingIntent = PendingIntent.getActivities(App.get(), 0, intents,
PendingIntent.FLAG_UPDATE_CURRENT)
builder = NotificationCompat.Builder(FileDownloadHelper.getAppContext())
builder.setDefaults(Notification.DEFAULT_LIGHTS)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setContentTitle(getTitle())
.setContentText(desc)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.doge1)
}
override fun show(statusChanged: Boolean, status: Int, isShowProgress: Boolean) {
var desc = desc
builder.setContentTitle(title)
.setContentText(desc)
if (statusChanged) {
builder.setTicker(desc)
}
builder.setProgress(total, sofar, !isShowProgress)
manager.notify(id, builder.build())
}
} | apache-2.0 | a1b1bf23f751d4428c2eafa56ed13842 | 34.600746 | 120 | 0.590776 | 4.674179 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/util/reference/ClassNameReferenceProvider.kt | 1 | 3793 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util.reference
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.mapToArray
import com.demonwav.mcdev.util.packageName
import com.intellij.codeInsight.completion.JavaClassNameCompletionContributor
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiPackage
import com.intellij.psi.ResolveResult
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PackageScope
import com.intellij.util.ArrayUtil
import com.intellij.util.PlatformIcons
abstract class ClassNameReferenceProvider : PackageNameReferenceProvider() {
override val description: String
get() = "class/package '%s'"
protected abstract fun findClasses(element: PsiElement, scope: GlobalSearchScope): List<PsiClass>
override fun canBindTo(element: PsiElement) = super.canBindTo(element) || element is PsiClass
override fun resolve(qualifiedName: String, element: PsiElement, facade: JavaPsiFacade): Array<ResolveResult> {
val classes = facade.findClasses(qualifiedName, element.resolveScope)
if (classes.isNotEmpty()) {
return classes.mapToArray(::PsiElementResolveResult)
}
return super.resolve(qualifiedName, element, facade)
}
override fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> {
return if (context != null) {
if (context is PsiPackage) {
collectSubpackages(element, context)
} else {
ArrayUtil.EMPTY_OBJECT_ARRAY // TODO: Add proper support for inner classes
}
} else {
collectClasses(element)
}
}
private fun collectClasses(element: PsiElement): Array<Any> {
val classes = findClasses(element, element.resolveScope).ifEmpty { return ArrayUtil.EMPTY_OBJECT_ARRAY }
val list = ArrayList<Any>()
val packages = HashSet<String>()
val basePackage = getBasePackage(element)
for (psiClass in classes) {
list.add(JavaClassNameCompletionContributor.createClassLookupItem(psiClass, false))
val topLevelPackage = getTopLevelPackageName(psiClass, basePackage) ?: continue
if (packages.add(topLevelPackage)) {
list.add(LookupElementBuilder.create(topLevelPackage).withIcon(PlatformIcons.PACKAGE_ICON))
}
}
return list.toArray()
}
private fun getTopLevelPackageName(psiClass: PsiClass, basePackage: String?): String? {
val packageName = psiClass.packageName ?: return null
val start = if (basePackage != null && packageName.startsWith(basePackage)) {
if (packageName.length == basePackage.length) {
// packageName == basePackage
return null
}
basePackage.length + 1
} else 0
val end = packageName.indexOf('.', start)
return if (end == -1) {
packageName.substring(start)
} else {
packageName.substring(start, end)
}
}
private fun collectSubpackages(element: PsiElement, context: PsiPackage): Array<Any> {
val classes = findClasses(element, PackageScope(context, true, true).intersectWith(element.resolveScope))
.ifEmpty { return ArrayUtil.EMPTY_OBJECT_ARRAY }
return collectPackageChildren(context, classes) {
JavaClassNameCompletionContributor.createClassLookupItem(it, false)
}
}
}
| mit | 2b4e9b6d2875e8aa520b7fdafa4b93a5 | 35.12381 | 115 | 0.686264 | 4.96466 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/i18n/lang/I18nParserDefinition.kt | 1 | 1555 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.lang
import com.demonwav.mcdev.i18n.lang.gen.parser.I18nParser
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nTypes
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
class I18nParserDefinition : ParserDefinition {
override fun createParser(project: Project) = I18nParser()
override fun createLexer(project: Project) = I18nLexerAdapter()
override fun createFile(viewProvider: FileViewProvider) = I18nFile(viewProvider)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode) =
LanguageUtil.canStickTokensTogetherByLexer(left, right, I18nLexerAdapter())!!
override fun getStringLiteralElements() = STRING_LITERALS
override fun getWhitespaceTokens() = WHITE_SPACES
override fun getFileNodeType() = FILE
override fun createElement(node: ASTNode) = I18nTypes.Factory.createElement(node)!!
override fun getCommentTokens() = TokenSet.EMPTY!!
companion object {
val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE)
val STRING_LITERALS = TokenSet.create(I18nTypes.KEY, I18nTypes.VALUE)
val FILE = IFileElementType(I18nLanguage)
}
}
| mit | 8ec5438699bc673139c8ec2c742344ac | 34.340909 | 87 | 0.771061 | 4.113757 | false | false | false | false |
zhclwr/YunWeatherKotlin | app/src/main/java/com/victor/yunweatherkotlin/activity/LoadActivity.kt | 1 | 4203 | package com.victor.yunweatherkotlin.activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.victor.yunweatherkotlin.R
import com.victor.yunweatherkotlin.app.MyApplication
import com.victor.yunweatherkotlin.bean.City
import com.victor.yunweatherkotlin.db.CityDB
import kotlinx.android.synthetic.main.activity_load.*
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.net.URL
/**
* china-city-list:http://116.196.93.90/china-city-list.txt
* 上面服务器到期了。。
* 改用本地资源
*
* */
class LoadActivity : BaseActivity() {
private var list = ArrayList<CityDB>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_load)
loadByGreenDao()
setListener()
}
private fun setListener() {
bt_load.setOnClickListener {
startActivity(Intent(this, WeatherActivity::class.java))
finish()
}
}
/**从assets文件导入数据库*/
private fun load(){
doAsync {
val ins = assets.open("china-city-list.txt")
val reader = ins.reader()
val list = reader.readLines()
var num = 0
var progress = 0
for (s in list){
val c = s.split("\t".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
CityDB(c[0], c[2], c[9], c[7]).save()
num++
if (num in 1..3181 step 31){
uiThread { progressBar.progress = progress++ }
}
}
val edit = defaultSharedPreferences.edit()
edit.putBoolean("data",false).apply()
uiThread {
tv_load.text = "数据库升级完成"
bt_load.visibility = View.VISIBLE
}
}
}
/**
*通过greenDao从assets文件导入数据库
*/
private fun loadByGreenDao(){
doAsync {
val ins = assets.open("china-city-list.txt")
val reader = ins.reader()
val list = reader.readLines()
var num = 0
var progress = 0
val dao = MyApplication.getInstances().daoSession.cityDao
var datas = ArrayList<City>()
for (s in list){
var c = s.split("\t".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
datas.add(City(c[0], c[2], c[9], c[7]))
num++
//但是這裡的進度就不太準確了,恩 我知道
if (num in 1..3181 step 31){
uiThread { progressBar.progress = progress++ }
}
}
dao.insertInTx(datas)
uiThread {
tv_load.text = "数据库升级完成"
bt_load.visibility = View.VISIBLE
}
defaultSharedPreferences.edit().putBoolean("data",false).apply()
}
}
/**
* 从网络导入查询数据库
* 服务器到期,就不续费了。。。*/
private fun loadFromNet(){
doAsync {
val citys :String = URL("http://116.196.93.90/china-city-list.txt").readText()
val temp = citys.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var num = 0
var progress = 0
for (s in temp){
var c = s.split("\t".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
CityDB(c[0], c[2], c[9], c[7]).save()
num++
if (num in 1..3181 step 31){
uiThread { progressBar.progress = progress++ }
}
}
val edit = defaultSharedPreferences.edit()
edit.putBoolean("data",false).apply()
uiThread {
tv_load.text = "数据库升级完成"
bt_load.visibility = View.VISIBLE
}
}
}
}
| apache-2.0 | 338176abbcf277f103c24f807e88578e | 31.132231 | 96 | 0.518084 | 4.189133 | false | false | false | false |
Tickaroo/tikxml | processor/src/main/java/com/tickaroo/tikxml/processor/field/PropertyField.kt | 1 | 3978 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.processor.field
import com.squareup.javapoet.*
import com.tickaroo.tikxml.processor.generator.CodeGeneratorHelper
import com.tickaroo.tikxml.processor.utils.ifValueNotNullCheck
import com.tickaroo.tikxml.processor.xml.XmlChildElement
import java.util.*
import javax.lang.model.element.Modifier
import javax.lang.model.element.VariableElement
/**
* This class represents a field annotated with [com.tickaroo.tikxml.annotation.PropertyElement]
* @author Hannes Dorfmann
*/
class PropertyField(element: VariableElement, name: String, val writeAsCData: Boolean = false, val converterQualifiedName: String? = null) : NamedField(element, name), XmlChildElement {
override val attributes = LinkedHashMap<String, AttributeField>()
override val childElements = LinkedHashMap<String, XmlChildElement>()
override fun isXmlElementAccessableFromOutsideTypeAdapter() = true
override fun generateReadXmlCode(codeGeneratorHelper: CodeGeneratorHelper): TypeSpec {
if (!hasAttributes()) {
val fromXmlMethod = codeGeneratorHelper.fromXmlMethodBuilder()
.addCode(codeGeneratorHelper.ignoreAttributes())
.addCode(codeGeneratorHelper.assignViaTypeConverterOrPrimitive(element, CodeGeneratorHelper.AssignmentType.ELEMENT, accessResolver, converterQualifiedName))
.build()
return TypeSpec.anonymousClassBuilder("")
.addSuperinterface(codeGeneratorHelper.childElementBinderType)
.addMethod(fromXmlMethod)
.build()
}
val fromXmlMethod = codeGeneratorHelper.fromXmlMethodBuilder()
.addCode(codeGeneratorHelper.assignViaTypeConverterOrPrimitive(element, CodeGeneratorHelper.AssignmentType.ELEMENT, accessResolver, converterQualifiedName))
.build()
// Multiple attributes
val attributeMapType = ParameterizedTypeName.get(ClassName.get(Map::class.java), ClassName.get(String::class.java), codeGeneratorHelper.attributeBinderType)
val attributeHashMapType = ParameterizedTypeName.get(ClassName.get(Map::class.java), ClassName.get(String::class.java), codeGeneratorHelper.attributeBinderType)
return TypeSpec.anonymousClassBuilder("")
.addSuperinterface(codeGeneratorHelper.nestedChildElementBinderType)
.addField(FieldSpec.builder(attributeMapType, CodeGeneratorHelper.attributeBindersParam, Modifier.PRIVATE)
.initializer("new \$T()", attributeHashMapType)
.build())
.addInitializerBlock(codeGeneratorHelper.generateAttributeBinders(this))
.addMethod(fromXmlMethod)
.build()
}
override fun generateWriteXmlCode(codeGeneratorHelper: CodeGeneratorHelper) =
CodeBlock.builder()
.ifValueNotNullCheck(this) {
add(codeGeneratorHelper.writeBeginElementAndAttributes(this@PropertyField))
add(codeGeneratorHelper.writeTextContentViaTypeConverterOrPrimitive(element, accessResolver, converterQualifiedName, writeAsCData))
addStatement("${CodeGeneratorHelper.writerParam}.endElement()")
}
.build()
} | apache-2.0 | 3bd60cad09d33ef0cb7e414e71a0834b | 46.939759 | 185 | 0.711916 | 5.304 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/descreasing_subsequences/DecreasingSubsequences.kt | 1 | 2436 | package katas.kotlin.leetcode.descreasing_subsequences
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/350233/Google-or-Summer-Intern-OA-2019-or-Decreasing-Subsequences
*/
class DecreasingSubsequencesTests {
@Test fun `split array into strictly decreasing subsequences`() {
split(arrayOf(5, 2, 4, 3, 1, 6)).printed() shouldEqual listOf(listOf(5, 2, 1), listOf(4, 3), listOf(6))
split(arrayOf(2, 9, 12, 13, 4, 7, 6, 5, 10)).printed() shouldEqual listOf(
listOf(2), listOf(9, 4), listOf(12, 7, 6, 5), listOf(13, 10)
)
split(arrayOf(1, 1, 1)).printed() shouldEqual listOf(listOf(1), listOf(1), listOf(1))
leastSubsequences(5, 2, 4, 3, 1, 6) shouldEqual 3
leastSubsequences(2, 9, 12, 13, 4, 7, 6, 5, 10) shouldEqual 4
leastSubsequences(1, 1, 1) shouldEqual 3
}
}
private fun leastSubsequences(vararg nums: Int): Int {
val piles = IntArray(nums.size)
var size = 0
for (n in nums) {
val pile = binarySearch(piles, size, n)
piles[pile] = n
if (pile == size) size++
}
return size
}
private fun binarySearch(nums: IntArray, size: Int, target: Int): Int {
var from = 0
var to = size
while (from < to) {
val mid = (from + to) / 2
if (target < nums[mid]) to = mid
else from = mid + 1
}
return from
}
private fun split(array: Array<Int>): List<List<Int>> {
return allSubsequences(Solution(array.toList())).minByOrNull { it: Solution -> it.seqs.size }!!.seqs
}
private fun allSubsequences(solution: Solution): List<Solution> {
if (solution.isComplete()) return listOf(solution)
return solution.nextValidSteps()
.flatMap { subSolution -> allSubsequences(subSolution) }
}
private data class Solution(private val list: List<Int>, val seqs: List<List<Int>> = emptyList()) {
fun isComplete() = list.isEmpty()
fun nextValidSteps(): List<Solution> {
val head = list.first()
val tail = list.drop(1)
return seqs.mapIndexedNotNull { i, seq ->
if (seq.last() <= head) null
else {
val updatedValue = ArrayList(seqs).also { it[i] = seq + head }
Solution(tail, updatedValue)
}
} + Solution(tail, seqs + listOf(listOf(head)))
}
override fun toString() = "Solution=$seqs"
}
| unlicense | 5689b3eda130f343c200e78d1c697877 | 32.369863 | 116 | 0.619869 | 3.520231 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/activity/SplashActivity.kt | 1 | 1532 | package com.tungnui.abccomputer.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.WindowManager
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.utils.ActivityUtils
import com.tungnui.abccomputer.utils.AppUtility
import kotlinx.android.synthetic.main.activity_splash.*
class SplashActivity : AppCompatActivity() {
// init variables
private var mContext: Context? = null
private var mActivity: Activity? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
initVariables()
setContentView(R.layout.activity_splash)
}
override fun onResume() {
super.onResume()
initFunctionality()
}
private fun initFunctionality() {
if (AppUtility.isNetworkAvailable(mContext)) {
Handler().postDelayed({
ActivityUtils.instance.invokeActivity(this@SplashActivity, MainActivity::class.java, true) }, SPLASH_DURATION.toLong())
} else {
AppUtility.noInternetWarning(splashBody, mContext)
}
}
private fun initVariables() {
mActivity = this@SplashActivity
mContext = mActivity?.applicationContext
}
companion object {
private val SPLASH_DURATION = 2500
}
} | mit | 34d5fff9a32b9db8efae7ab785314a10 | 29.058824 | 135 | 0.71671 | 4.848101 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/rekognition/src/main/kotlin/com/kotlin/rekognition/DeleteFacesFromCollection.kt | 1 | 1907 | // snippet-sourcedescription:[DeleteFacesFromCollection.kt demonstrates how to delete faces from an Amazon Rekognition collection.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Rekognition]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.rekognition
// snippet-start:[rekognition.kotlin.delete_faces_collection.import]
import aws.sdk.kotlin.services.rekognition.RekognitionClient
import aws.sdk.kotlin.services.rekognition.model.DeleteFacesRequest
// snippet-end:[rekognition.kotlin.delete_faces_collection.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<collectionId> <faceId>
Where:
collectionId - The id of the collection from which faces are deleted.
faceId - The id of the face to delete.
"""
if (args.size != 2) {
println(usage)
System.exit(1)
}
val collectionId = args[0]
val faceId = args[1]
deleteFacesCollection(collectionId, faceId)
}
// snippet-start:[rekognition.kotlin.delete_faces_collection.main]
suspend fun deleteFacesCollection(collectionIdVal: String?, faceIdVal: String) {
val deleteFacesRequest = DeleteFacesRequest {
collectionId = collectionIdVal
faceIds = listOf(faceIdVal)
}
RekognitionClient { region = "us-east-1" }.use { rekClient ->
rekClient.deleteFaces(deleteFacesRequest)
println("$faceIdVal was deleted from the collection")
}
}
// snippet-end:[rekognition.kotlin.delete_faces_collection.main]
| apache-2.0 | 3e0d9a9953d93523a28441d0ed6be1e1 | 32.053571 | 131 | 0.706345 | 4.040254 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/ActDrawableList.kt | 1 | 3449 | package jp.juggler.subwaytooter
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.*
import jp.juggler.subwaytooter.global.appDispatchers
import jp.juggler.subwaytooter.util.AsyncActivity
import jp.juggler.util.LogCategory
import jp.juggler.util.asciiPattern
import kotlinx.coroutines.*
class ActDrawableList : AsyncActivity(), CoroutineScope {
companion object {
private val log = LogCategory("ActDrawableList")
}
private class MyItem(val id: Int, val name: String)
private val drawableList = ArrayList<MyItem>()
private lateinit var adapter: MyAdapter
private lateinit var listView: ListView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App1.setActivityTheme(this)
initUI()
load()
}
private fun initUI() {
setContentView(R.layout.act_drawable_list)
App1.initEdgeToEdge(this)
Styler.fixHorizontalPadding(findViewById(R.id.llContent))
listView = findViewById(R.id.listView)
adapter = MyAdapter()
listView.adapter = adapter
}
private fun load() = launch {
try {
val rePackageSpec = """.+/""".toRegex()
val reSkipName =
"""^(abc_|avd_|btn_checkbox_|btn_radio_|googleg_|ic_keyboard_arrow_|ic_menu_arrow_|notification_|common_|emj_|cpv_|design_|exo_|mtrl_|ic_mtrl_)"""
.asciiPattern()
val list = withContext(appDispatchers.io) {
R.drawable::class.java.fields
.mapNotNull {
val id = it.get(null) as? Int ?: return@mapNotNull null
val name = resources.getResourceName(id).replaceFirst(rePackageSpec, "")
if (reSkipName.matcher(name).find()) return@mapNotNull null
MyItem(id, name)
}
.toMutableList()
.apply { sortBy { it.name } }
}
drawableList.clear()
drawableList.addAll(list)
adapter.notifyDataSetChanged()
} catch (ex: Throwable) {
log.trace(ex)
}
}
private class MyViewHolder(viewRoot: View) {
private val tvCaption: TextView = viewRoot.findViewById(R.id.tvCaption)
private val ivImage: ImageView = viewRoot.findViewById(R.id.ivImage)
fun bind(item: MyItem) {
tvCaption.text = item.name
ivImage.setImageResource(item.id)
}
}
private inner class MyAdapter : BaseAdapter() {
override fun getCount(): Int = drawableList.size
override fun getItemId(idx: Int): Long = 0L
override fun getItem(idx: Int): Any = drawableList[idx]
override fun getView(idx: Int, viewArg: View?, parent: ViewGroup?): View {
val view: View
val holder: MyViewHolder
if (viewArg == null) {
view = layoutInflater.inflate(R.layout.lv_drawable, parent, false)
holder = MyViewHolder(view)
view.tag = holder
} else {
view = viewArg
holder = view.tag as MyViewHolder
}
holder.bind(drawableList[idx])
return view
}
}
}
| apache-2.0 | adadd230d285cd7b9927d922e3dfac59 | 32.838384 | 162 | 0.575529 | 4.724658 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/kendra/src/main/kotlin/com/example/kendra/DeleteIndex.kt | 1 | 1587 | // snippet-sourcedescription:[DeleteIndex.kt demonstrates how to delete an Amazon Kendra index.]
// snippet-keyword:[SDK for Kotlin]
// snippet-service:[Amazon Kendra]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.kendra
// snippet-start:[kendra.kotlin.delete.index.import]
import aws.sdk.kotlin.services.kendra.KendraClient
import aws.sdk.kotlin.services.kendra.model.DeleteIndexRequest
import kotlin.system.exitProcess
// snippet-end:[kendra.kotlin.delete.index.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<indexId>
Where:
indexId - The id value of the index.
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val indexId = args[0]
deleteSpecificIndex(indexId)
}
// snippet-start:[kendra.kotlin.delete.index.main]
suspend fun deleteSpecificIndex(indexId: String) {
val deleteIndexRequest = DeleteIndexRequest {
id = indexId
}
KendraClient { region = "us-east-1" }.use { kendra ->
kendra.deleteIndex(deleteIndexRequest)
println("$indexId was successfully deleted.")
}
}
// snippet-end:[kendra.kotlin.delete.index.main]
| apache-2.0 | 949a29f256b41454fe844a382b758aab | 25.842105 | 96 | 0.676749 | 3.725352 | false | false | false | false |
nukc/RecyclerAdapter | app/src/main/java/com/github/nukc/recycleradapter/sample/MainActivity.kt | 1 | 7493 | package com.github.nukc.recycleradapter.sample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.PagerAdapter
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.holder.Holder
import com.bumptech.glide.Glide
import com.github.nukc.recycleradapter.RecyclerAdapter
import com.github.nukc.recycleradapter.dsl.setup
import com.github.nukc.recycleradapter.sample.databinding.ItemChosenBinding
import com.github.nukc.recycleradapter.sample.databinding.ItemLeftBinding
import com.github.nukc.recycleradapter.sample.databinding.ItemPureBinding
import com.github.nukc.recycleradapter.sample.databinding.ViewBannerBinding
import com.github.nukc.recycleradapter.sample.model.Banner
import com.github.nukc.recycleradapter.sample.model.Chosen
import com.github.nukc.recycleradapter.sample.model.NumberItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var adapter: RecyclerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setup()
}
private fun setup() {
val imageUrl = "https://raw.githubusercontent.com/nukc/RecyclerAdapter/kotlin/art/banner.png"
val banners: List<Banner> = mutableListOf(Banner(imageUrl))
val chosen = Chosen(imageUrl, "Chosen")
adapter = recycler_view.setup(LinearLayoutManager(this)) {
hasStableIds = true
renderItem<List<Banner>, ViewBannerBinding> {
type = Banner::class.java
getViewBinding = {
ViewBannerBinding.bind(it)
}
res(R.layout.view_banner)
bind {
if (binding.convenientBanner.childCount > 0 && binding.convenientBanner.getChildAt(0) is ViewGroup) {
val viewPager = binding.convenientBanner.getChildAt(0) as ViewGroup
if (viewPager.childCount > 0) {
return@bind
}
}
// setup banner
(binding.convenientBanner as ConvenientBanner<Any>).setPages(creator, data)
?.setOnItemClickListener { position ->
val item = data[position]
Toast.makeText(this@MainActivity, item.image, Toast.LENGTH_SHORT).show()
}
?.setCanLoop(true)
?.startTurning(3000)
?.setPageIndicator(intArrayOf(R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused))
}
}
renderItem<List<Chosen>, ItemChosenBinding> {
type = Chosen::class.java
getViewBinding = {
ItemChosenBinding.bind(it)
}
res(R.layout.item_chosen) {
binding.viewPager.setPageTransformer(true, AlphaAndScalePageTransformer())
binding.viewPager.pageMargin = Utils.dip2px(itemView.context, 15f)
}
bind {
if (binding.viewPager.adapter == null) {
binding.viewPager.adapter = ChosenPagerAdapter(data)
binding.viewPager.offscreenPageLimit = data.size - 1
if (data.size > 3) {
binding.viewPager.post {
binding.viewPager.currentItem = 1
}
}
}
}
}
renderItem<Int, ItemPureBinding> {
getViewBinding = {
ItemPureBinding.bind(it)
}
res(R.layout.item_pure) {
binding.layoutLikest.setOnClickListener {
Toast.makeText(this@MainActivity, "每日最赞", Toast.LENGTH_SHORT).show()
}
binding.layoutEditorPicks.setOnClickListener {
Toast.makeText(this@MainActivity, "编辑精选", Toast.LENGTH_SHORT).show()
}
binding.tvMore.setOnClickListener {
Toast.makeText(this@MainActivity, "更多", Toast.LENGTH_SHORT).show()
}
}
}
renderItem<NumberItem, ItemLeftBinding> {
getViewBinding = {
ItemLeftBinding.bind(it)
}
res(R.layout.item_left, R.layout.item_right)
getItemViewType {
when (data.number % 2) {
0 -> R.layout.item_left
else -> R.layout.item_right
}
}
bind {
binding.tvText.text = data.number.toString()
}
}
}
adapter.addAll(mutableListOf(banners, mutableListOf(chosen, chosen, chosen), 1))
recycler_view.postDelayed({
val numberItems = mutableListOf<NumberItem>()
for (i in 0..5) {
numberItems.add(NumberItem(i))
}
adapter.addAll(numberItems.toMutableList())
}, 500)
}
private val creator = object : CBViewHolderCreator {
override fun createHolder(itemView: View): Holder<Banner> {
return LocalImageHolderView(itemView)
}
override fun getLayoutId(): Int {
return R.layout.item_banner
}
}
private class LocalImageHolderView(itemView: View) : Holder<Banner>(itemView) {
private var imageView: ImageView? = null
override fun initView(itemView: View) {
imageView = itemView.findViewById(R.id.iv_banner)
}
override fun updateUI(data: Banner) {
imageView?.let {
Glide.with(it)
.load(data.image)
.into(it)
}
}
}
private class ChosenPagerAdapter(var list: List<Chosen>) : PagerAdapter() {
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return list.size
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = LayoutInflater.from(container.context)
.inflate(R.layout.item_chosen_child, container, false)
val data = list[position]
Glide.with(container)
.load(data.image)
.into(view.findViewById(R.id.iv_cover))
view.findViewById<TextView>(R.id.tv_title).text = data.title
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View?)
}
}
}
| apache-2.0 | 9a8c822a6225155023a0ee90f28d617e | 37.127551 | 126 | 0.563763 | 4.952286 | false | false | false | false |
noboru-i/SlideViewer | app/src/main/java/hm/orz/chaos114/android/slideviewer/widget/ViewPagerFixed.kt | 1 | 1546 | package hm.orz.chaos114.android.slideviewer.widget
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import timber.log.Timber
class ViewPagerFixed : ViewPager {
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
override fun onTouchEvent(ev: MotionEvent): Boolean {
try {
return super.onTouchEvent(ev)
} catch (ex: IllegalArgumentException) {
Timber.w(ex)
}
return false
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
try {
return super.onInterceptTouchEvent(ev)
} catch (ex: IllegalArgumentException) {
Timber.w(ex)
}
return false
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val heightSize = View.MeasureSpec.getSize(heightMeasureSpec)
var height = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(heightSize, View.MeasureSpec.AT_MOST))
val h = child.measuredHeight
if (h > height) {
height = h
}
}
val newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
| mit | 6dd9b33cbc0cd25ba8290e49881a5795 | 28.730769 | 115 | 0.654592 | 4.801242 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/controller/SponsoringController.kt | 1 | 8775 | package backend.controller
import backend.configuration.CustomUserDetails
import backend.controller.exceptions.BadRequestException
import backend.controller.exceptions.NotFoundException
import backend.controller.exceptions.UnauthorizedException
import backend.model.event.Team
import backend.model.event.TeamService
import backend.model.sponsoring.Sponsoring
import backend.model.sponsoring.SponsoringService
import backend.model.sponsoring.UnregisteredSponsor
import backend.model.user.Participant
import backend.model.user.Sponsor
import backend.model.user.UserService
import backend.services.ConfigurationService
import backend.view.SponsorTeamProfileView
import backend.view.UnregisteredSponsorView
import backend.view.sponsoring.SponsoringTeamProfileView
import backend.view.sponsoring.SponsoringView
import org.javamoney.moneta.Money
import org.springframework.http.HttpStatus.CREATED
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.*
import javax.validation.Valid
@RestController
class SponsoringController(private var sponsoringService: SponsoringService,
private var userService: UserService,
private var teamService: TeamService,
private var configurationService: ConfigurationService) {
private val jwtSecret: String = configurationService.getRequired("org.breakout.api.jwt_secret")
/**
* GET /event/{eventId}/team/{teamId}/sponsoring/
* Get a list of all sponsorings for the team with teamId
*/
@GetMapping("/event/{eventId}/team/{teamId}/sponsoring/")
fun getAllSponsorings(@AuthenticationPrincipal customUserDetails: CustomUserDetails?,
@PathVariable teamId: Long): Iterable<SponsoringView> {
val team = teamService.findOne(teamId) ?: throw NotFoundException("No team with id $teamId found")
return if (customUserDetails != null) getAllSponsoringsAuthenticated(customUserDetails, team)
else getAllSponsoringsUnauthenticated(team)
}
private fun getAllSponsoringsAuthenticated(customUserDetails: CustomUserDetails, team: Team): Iterable<SponsoringView> {
val user = userService.getUserFromCustomUserDetails(customUserDetails)
val participant = user.getRole(Participant::class)
if (participant != null && team.isMember(participant)) {
return sponsoringService.findByTeamId(team.id!!).map(::SponsoringView)
} else {
throw UnauthorizedException("Only members of the team ${team.id} can view its sponsorings")
}
}
private fun getAllSponsoringsUnauthenticated(team: Team): Iterable<SponsoringView> {
return sponsoringService.findByTeamId(team.id!!).map { sponsoring ->
val view = SponsoringView(sponsoring)
sponsoring.sponsor?.unregisteredSponsor?.let {
if (it.isHidden) {
view.unregisteredSponsor = null
view.sponsorIsHidden = true
}
view.unregisteredSponsor?.address = null
view.unregisteredSponsor?.email = null
}
sponsoring.sponsor?.let {
if (it.isHidden) {
view.sponsorId = null
view.sponsorIsHidden = true
}
}
return@map view
}
}
/**
* POST /event/{eventId}/team/{teamId}/sponsoring/
* Create a new sponsoring for the team with teamId
* This can only done if user is a sponsor
*/
@PreAuthorize("isAuthenticated()")
@PostMapping("/event/{eventId}/team/{teamId}/sponsoring/")
@ResponseStatus(CREATED)
fun createSponsoring(@PathVariable teamId: Long,
@Valid @RequestBody body: SponsoringView,
@AuthenticationPrincipal customUserDetails: CustomUserDetails): SponsoringView {
val user = userService.getUserFromCustomUserDetails(customUserDetails)
val team = teamService.findOne(teamId) ?: throw NotFoundException("Team with id $teamId not found")
val amountPerKm = Money.of(body.amountPerKm, "EUR")
val limit = Money.of(body.limit, "EUR")
val sponsoring = if (body.unregisteredSponsor != null) {
user.getRole(Participant::class) ?: throw UnauthorizedException("Cannot add unregistered sponsor if user is no participant")
createSponsoringWithUnregisteredSponsor(team, amountPerKm, limit, body.unregisteredSponsor!!)
} else {
val sponsor = user.getRole(Sponsor::class) ?: throw UnauthorizedException("Cannot add user as sponsor. Missing role sponsor")
createSponsoringWithAuthenticatedSponsor(team, amountPerKm, limit, sponsor)
}
return SponsoringView(sponsoring)
}
private fun createSponsoringWithAuthenticatedSponsor(team: Team, amount: Money, limit: Money, sponsor: Sponsor): Sponsoring {
return sponsoringService.createSponsoring(sponsor, team, amount, limit)
}
private fun createSponsoringWithUnregisteredSponsor(team: Team, amount: Money, limit: Money, sponsor: UnregisteredSponsorView): Sponsoring {
val unregisteredSponsor = UnregisteredSponsor(
firstname = sponsor.firstname!!,
lastname = sponsor.lastname!!,
company = sponsor.company!!,
address = sponsor.address!!.toAddress()!!,
email = sponsor.email,
isHidden = sponsor.isHidden)
return sponsoringService.createSponsoringWithOfflineSponsor(team, amount, limit, unregisteredSponsor)
}
/**
* GET /user/{userId}/sponsor/sponsoring/
* Get a list of all sponsorings for the user with userId
* This can only be done if the user is a sponsor
*/
@PreAuthorize("isAuthenticated()")
@GetMapping("/user/{userId}/sponsor/sponsoring/")
fun getAllSponsoringsForSponsor(@AuthenticationPrincipal customUserDetails: CustomUserDetails,
@PathVariable userId: Long): Iterable<SponsoringView> {
val user = userService.getUserFromCustomUserDetails(customUserDetails)
if (user.account.id != userId) throw UnauthorizedException("A sponsor can only see it's own sponsorings")
val sponsorings = sponsoringService.findBySponsorId(userId)
return sponsorings.map(::SponsoringView)
}
@PreAuthorize("isAuthenticated()")
@PutMapping("/event/{eventId}/team/{teamId}/sponsoring/{sponsoringId}/status/")
fun acceptOrRejectSponsoring(@AuthenticationPrincipal customUserDetails: CustomUserDetails,
@PathVariable sponsoringId: Long,
@RequestBody body: Map<String, String>): SponsoringView {
val sponsoring = sponsoringService.findOne(sponsoringId) ?: throw NotFoundException("No sponsoring with id $sponsoringId found")
val status = body["status"] ?: throw BadRequestException("Missing status in body")
return when (status.toLowerCase()) {
"accepted" -> SponsoringView(sponsoringService.acceptSponsoring(sponsoring))
"rejected" -> SponsoringView(sponsoringService.rejectSponsoring(sponsoring))
"withdrawn" -> SponsoringView(sponsoringService.withdrawSponsoring(sponsoring))
else -> throw BadRequestException("Invalid status $status")
}
}
@GetMapping("/team/{teamId}/sponsoring/")
fun getAllSponsoringsForTeamOverview(@PathVariable teamId: Long): Iterable<SponsoringTeamProfileView> {
return sponsoringService.findByTeamId(teamId).map {
val sponsor = when (it.sponsor?.isHidden ?: true) {
true -> SponsorTeamProfileView(
sponsorId = null,
firstname = "",
lastname = "",
company = null,
sponsorIsHidden = it.sponsor?.isHidden ?: true,
url = null,
logoUrl = null)
false -> SponsorTeamProfileView(
sponsorId = it.sponsor?.registeredSponsor?.id,
firstname = it.sponsor?.firstname ?: "",
lastname = it.sponsor?.lastname ?: "",
company = it.sponsor?.company,
sponsorIsHidden = it.sponsor?.isHidden ?: true,
url = it.sponsor?.url,
logoUrl = it.sponsor?.logo?.url)
}
SponsoringTeamProfileView(sponsor, it.status.toString())
}
}
}
| agpl-3.0 | 12f00f13bb35bcd492b12f3e362a39a1 | 44.942408 | 144 | 0.663704 | 5.373546 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/cli/GeoRocketCommand.kt | 1 | 2937 | package io.georocket.cli
import de.undercouch.underline.Command
import de.undercouch.underline.InputReader
import de.undercouch.underline.OptionDesc
import de.undercouch.underline.OptionGroup
import de.undercouch.underline.OptionIntrospector
import de.undercouch.underline.OptionIntrospector.ID
import de.undercouch.underline.OptionParser
import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.JsonObject
import io.vertx.core.streams.WriteStream
import java.io.PrintWriter
abstract class GeoRocketCommand : Command {
private val options: OptionGroup<ID> = OptionIntrospector.introspect(javaClass)
protected val vertx: Vertx by lazy { Vertx.currentContext().owner() }
protected val config: JsonObject by lazy { Vertx.currentContext().config() }
/**
* The command's name displayed in the help
*/
abstract val usageName: String
/**
* The command description that should be displayed in the help
*/
abstract val usageDescription: String
/**
* `true` if the command's help should be displayed
*/
@set:OptionDesc(longName = "help", shortName = "h",
description = "display this help and exit", priority = 9000)
var displayHelp: Boolean = false
@Deprecated("Use suspend version of this method!", replaceWith = ReplaceWith("coRun(args, `in`, out)"))
override fun run(args: Array<String>, `in`: InputReader, out: PrintWriter): Int {
throw RuntimeException("Use suspend version of this method!")
}
suspend fun coRun(args: Array<String>, reader: InputReader, out: WriteStream<Buffer>): Int {
val unknownArgs = OptionIntrospector.hasUnknownArguments(javaClass)
val parsedOptions = OptionParser.parse(args, options,
if (unknownArgs) OptionIntrospector.DEFAULT_ID else null)
OptionIntrospector.evaluate(parsedOptions.values, this)
if (displayHelp) {
usage()
return 0
}
if (!checkArguments()) {
return 1
}
return doRun(parsedOptions.remainingArgs, reader, out)
}
abstract suspend fun doRun(remainingArgs: Array<String>, reader: InputReader,
out: WriteStream<Buffer>): Int
/**
* Outputs an error message
* @param msg the message
*/
protected fun error(msg: String?) {
System.err.println("georocket: $msg")
}
/**
* Prints out usage information
*/
protected fun usage() {
var name = "georocket"
val footnotes: String? = if (options.commands.isNotEmpty()) {
"Use `$name help <command>' to read about a specific command."
} else {
null
}
if (usageName.isNotEmpty()) {
name += " $usageName"
}
val unknownArguments = OptionIntrospector.getUnknownArgumentName(javaClass)
OptionParser.usage(name, usageDescription, options, unknownArguments,
footnotes, PrintWriter(System.out, true))
}
open fun checkArguments(): Boolean {
// nothing to check by default. subclasses may override
return true
}
}
| apache-2.0 | 92c776cf372e6ad8c2cee5c23d657bc6 | 29.278351 | 105 | 0.715696 | 4.319118 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/core/event/LogEntryComparison.kt | 2 | 3387 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.core.event
import io.kvision.html.ButtonStyle
import kotlinx.serialization.Serializable
import org.apache.causeway.client.kroviz.ui.core.Constants
import org.apache.causeway.client.kroviz.utils.XmlHelper
enum class ChangeType(val id: String, val iconName: String, val style: ButtonStyle) {
ADDED("ADDED", "fas fa-plus", ButtonStyle.INFO),
MISSING("MISSING", "fas fa-minus", ButtonStyle.DANGER),
DIFF("DIFF", "fas fa-bell", ButtonStyle.WARNING),
INFO("INFO", "fas fa-info-circle", ButtonStyle.OUTLINEINFO),
ERROR("ERROR", "fas fa-bug", ButtonStyle.OUTLINEDANGER),
}
@Serializable
data class LogEntryComparison(val title: String, val expected: LogEntry?, val actual: LogEntry?) {
var changeType: ChangeType
var iconName: String
var expectedResponse: String? = null
var actualResponse: String? = null
var expectedBaseUrl = ""
var actualBaseUrl = ""
init {
if (expected == null && actual == null) {
throw Throwable("[LogEntryComparison.init] neither actual nor expected set")
} else {
changeType = compare()
iconName = changeType.iconName
actualResponse = actual?.response
expectedResponse = expected?.response
if (expected != null) {
expectedBaseUrl = extractBaseUrl(expected)
if (expected.subType == Constants.subTypeXml) {
expectedResponse = XmlHelper.format(expectedResponse!!)
}
}
if (actual != null) {
actualBaseUrl = extractBaseUrl(actual)
if (actual.subType == Constants.subTypeXml) {
actualResponse = XmlHelper.format(actualResponse!!)
}
}
}
}
private fun extractBaseUrl(event: LogEntry): String {
val title = event.title
return title.split(Constants.restInfix).first()
}
private fun compare(): ChangeType {
val responsesAreEqual = areResponsesEqual()
return when {
expected == null -> ChangeType.ADDED
actual == null -> ChangeType.MISSING
responsesAreEqual -> ChangeType.INFO
!responsesAreEqual -> ChangeType.DIFF
else -> ChangeType.ERROR
}
}
private fun areResponsesEqual(): Boolean {
val expected = expectedResponse?.replace(expectedBaseUrl, "")
val actual = actualResponse?.replace(actualBaseUrl, "")
return (expected == actual)
}
}
| apache-2.0 | 9edd2dd7c653cbecde73aad68d66cdf7 | 37.05618 | 98 | 0.652495 | 4.639726 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/overlay/OverlayBackground.kt | 1 | 770 | package org.runestar.client.api.overlay
import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics2D
import java.awt.Paint
class OverlayBackground(
val overlay: Overlay,
val paint: Paint
) : Overlay {
companion object {
val DEFAULT = Color(70, 61, 50, 156)
}
override fun draw(g: Graphics2D, size: Dimension) {
if (size.width == 0 && size.height == 0) return
g.paint = paint
g.fillRect(0, 0, size.width, size.height)
overlay.draw(g, size)
}
override fun getSize(g: Graphics2D, result: Dimension) = overlay.getSize(g, result)
}
fun Overlay.withBackground(paint: Paint) = OverlayBackground(this, paint)
fun Overlay.withBackground() = withBackground(OverlayBackground.DEFAULT) | mit | 5bf515db69bd9b41fb4c8e94df9525be | 25.586207 | 87 | 0.681818 | 3.684211 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt | 2 | 15034 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject
import org.jetbrains.kotlin.idea.quickfix.KotlinCrossLanguageQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.*
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.isAbstract
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.descriptorUtil.classValueType
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import java.lang.ref.WeakReference
class CreateExtensionCallableFromUsageFix<E : KtElement>(
originalExpression: E,
private val callableInfosFactory: (E) -> List<CallableInfo>?
) : CreateCallableFromUsageFixBase<E>(originalExpression, true), LowPriorityAction {
init {
init()
}
override val callableInfos: List<CallableInfo>
get() = element?.let { callableInfosFactory(it) } ?: emptyList()
}
class CreateCallableFromUsageFix<E : KtElement>(
originalExpression: E,
private val callableInfosFactory: (E) -> List<CallableInfo>?
) : CreateCallableFromUsageFixBase<E>(originalExpression, false) {
init {
init()
}
override val callableInfos: List<CallableInfo>
get() = element?.let { callableInfosFactory(it) } ?: emptyList()
}
abstract class AbstractCreateCallableFromUsageFixWithTextAndFamilyName<E : KtElement>(
providedText: String,
@Nls private val familyName: String,
originalExpression: E
): CreateCallableFromUsageFixBase<E>(originalExpression, false) {
override val calculatedText: String = providedText
override fun getFamilyName(): String = familyName
}
abstract class CreateCallableFromUsageFixBase<E : KtElement>(
originalExpression: E,
val isExtension: Boolean
) : KotlinCrossLanguageQuickFixAction<E>(originalExpression) {
private var callableInfoReference: WeakReference<List<CallableInfo>>? = null
protected open val callableInfos: List<CallableInfo>
get() = listOfNotNull(callableInfo)
protected open val callableInfo: CallableInfo?
get() = throw UnsupportedOperationException()
protected fun callableInfos(): List<CallableInfo> =
callableInfoReference?.get() ?: callableInfos.also {
callableInfoReference = WeakReference(it)
}
protected fun notEmptyCallableInfos() = callableInfos().takeIf { it.isNotEmpty() }
private var initialized: Boolean = false
protected open val calculatedText: String by lazy(fun(): String {
val element = element ?: return ""
val callableInfos = notEmptyCallableInfos() ?: return ""
val callableInfo = callableInfos.first()
val receiverTypeInfo = callableInfo.receiverTypeInfo
val renderedCallables = callableInfos.map {
buildString {
if (it.isAbstract) {
append(KotlinBundle.message("text.abstract"))
append(' ')
}
val kind = when (it.kind) {
CallableKind.FUNCTION -> KotlinBundle.message("text.function")
CallableKind.PROPERTY -> KotlinBundle.message("text.property")
CallableKind.CONSTRUCTOR -> KotlinBundle.message("text.secondary.constructor")
else -> throw AssertionError("Unexpected callable info: $it")
}
append(kind)
if (it.name.isNotEmpty()) {
append(" '")
val receiverType = if (!receiverTypeInfo.isOfThis) {
CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension)
.createBuilder()
.computeTypeCandidates(receiverTypeInfo)
.firstOrNull { candidate -> if (it.isAbstract) candidate.theType.isAbstract() else true }
?.theType
} else null
val staticContextRequired = receiverTypeInfo.staticContextRequired
if (receiverType != null) {
if (isExtension && !staticContextRequired) {
val receiverTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(receiverType)
val isFunctionType = receiverType.constructor.declarationDescriptor is FunctionClassDescriptor
append(if (isFunctionType) "($receiverTypeText)" else receiverTypeText).append('.')
} else {
receiverType.constructor.declarationDescriptor?.let {
val companionText = if (staticContextRequired && it !is JavaClassDescriptor) ".Companion" else ""
val receiverText =
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderClassifierName(it) + companionText
append(receiverText).append('.')
}
}
}
append("${it.name}'")
}
}
}
return buildString {
append(KotlinBundle.message("text.create"))
append(' ')
if (!callableInfos.any { it.isAbstract }) {
if (isExtension) {
append(KotlinBundle.message("text.extension"))
append(' ')
} else if (receiverTypeInfo != TypeInfo.Empty) {
append(KotlinBundle.message("text.member"))
append(' ')
}
}
renderedCallables.joinTo(this)
}
})
protected open val calculatedAvailableImpl: Boolean by lazy(fun(): Boolean {
val element = element ?: return false
val callableInfos = notEmptyCallableInfos() ?: return false
val callableInfo = callableInfos.first()
val receiverInfo = callableInfo.receiverTypeInfo
if (receiverInfo == TypeInfo.Empty) {
if (callableInfos.any { it is PropertyInfo && it.possibleContainers.isEmpty() }) return false
return !isExtension
}
val callableBuilder = CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension).createBuilder()
val receiverTypeCandidates = callableBuilder.computeTypeCandidates(receiverInfo)
val propertyInfo = callableInfos.firstOrNull { it is PropertyInfo } as PropertyInfo?
val isFunction = callableInfos.any { it.kind == CallableKind.FUNCTION }
return receiverTypeCandidates.any {
val declaration = getDeclarationIfApplicable(element.project, it, receiverInfo.staticContextRequired)
val insertToJavaInterface = declaration is PsiClass && declaration.isInterface
when {
!isExtension && propertyInfo != null && insertToJavaInterface && (!receiverInfo.staticContextRequired || propertyInfo.writable) ->
false
isFunction && insertToJavaInterface && receiverInfo.staticContextRequired ->
false
!isExtension && declaration is KtTypeParameter -> false
propertyInfo != null && !propertyInfo.isAbstract && declaration is KtClass && declaration.isInterface() -> false
else ->
declaration != null
}
}
})
/**
* Has to be invoked manually from final class ctor (as all final class properties have to be initialized)
*/
protected fun init() {
check(!initialized) { "${javaClass.simpleName} is already initialized" }
this.element ?: return
val callableInfos = callableInfos()
if (callableInfos.size > 1) {
val receiverSet = callableInfos.mapTo(HashSet()) { it.receiverTypeInfo }
if (receiverSet.size > 1) throw AssertionError("All functions must have common receiver: $receiverSet")
val possibleContainerSet = callableInfos.mapTo(HashSet()) { it.possibleContainers }
if (possibleContainerSet.size > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet")
}
initializeLazyProperties()
}
@Suppress("UNUSED_VARIABLE")
private fun initializeLazyProperties() {
// enforce lazy properties be calculated as QuickFix is created on a bg thread
val text = calculatedText
val availableImpl = calculatedAvailableImpl
initialized = true
}
private fun getDeclaration(descriptor: ClassifierDescriptor, project: Project): PsiElement? {
if (descriptor is FunctionClassDescriptor) {
val psiFactory = KtPsiFactory(project)
val syntheticClass = psiFactory.createClass(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(descriptor))
return psiFactory.createAnalyzableFile("${descriptor.name.asString()}.kt", "", element!!).add(syntheticClass)
}
return DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor)
}
private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate, staticContextRequired: Boolean): PsiElement? {
val descriptor = candidate.theType.constructor.declarationDescriptor ?: return null
if (isExtension && staticContextRequired && descriptor is JavaClassDescriptor) return null
val declaration = getDeclaration(descriptor, project) ?: return null
if (declaration !is KtClassOrObject && declaration !is KtTypeParameter && declaration !is PsiClass) return null
return if ((isExtension && !staticContextRequired) || declaration.canRefactor()) declaration else null
}
private fun checkIsInitialized() {
check(initialized) { "${javaClass.simpleName} is not initialized" }
}
override fun getText(): String {
checkIsInitialized()
element ?: return ""
return calculatedText
}
override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family")
override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean {
checkIsInitialized()
element ?: return false
return calculatedAvailableImpl
}
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
checkIsInitialized()
val element = element ?: return
val callableInfos = callableInfos()
val callableInfo = callableInfos.first()
val fileForBuilder = element.containingKtFile
val editorForBuilder = EditorHelper.openInEditor(element)
if (editorForBuilder != editor) {
NavigationUtil.activateFileWithPsiElement(element)
}
val callableBuilder =
CallableBuilderConfiguration(callableInfos, element as KtElement, fileForBuilder, editorForBuilder, isExtension).createBuilder()
fun runBuilder(placement: () -> CallablePlacement) {
project.executeCommand(text) {
callableBuilder.placement = placement()
callableBuilder.build()
}
}
if (callableInfo is ConstructorInfo) {
runBuilder { CallablePlacement.NoReceiver(callableInfo.targetClass) }
}
val popupTitle = KotlinBundle.message("choose.target.class.or.interface")
val receiverTypeInfo = callableInfo.receiverTypeInfo
val receiverTypeCandidates = callableBuilder.computeTypeCandidates(receiverTypeInfo).let {
if (callableInfo.isAbstract)
it.filter { it.theType.isAbstract() }
else if (!isExtension && receiverTypeInfo != TypeInfo.Empty)
it.filter { !it.theType.isTypeParameter() }
else
it
}
if (receiverTypeCandidates.isNotEmpty()) {
val staticContextRequired = receiverTypeInfo.staticContextRequired
val containers = receiverTypeCandidates
.mapNotNull { candidate -> getDeclarationIfApplicable(project, candidate, staticContextRequired)?.let { candidate to it } }
chooseContainerElementIfNecessary(containers, editorForBuilder, popupTitle, false, { it.second }) {
runBuilder {
val receiverClass = it.second as? KtClass
if (staticContextRequired && receiverClass?.isWritable == true) {
val hasCompanionObject = receiverClass.companionObjects.isNotEmpty()
val companionObject = receiverClass.getOrCreateCompanionObject()
if (!hasCompanionObject && [email protected]) companionObject.body?.delete()
val classValueType = (companionObject.descriptor as? ClassDescriptor)?.classValueType
val receiverTypeCandidate = if (classValueType != null) TypeCandidate(classValueType) else it.first
CallablePlacement.WithReceiver(receiverTypeCandidate)
} else {
CallablePlacement.WithReceiver(it.first)
}
}
}
} else {
assert(receiverTypeInfo == TypeInfo.Empty) {
"No receiver type candidates: ${element.text} in ${file.text}"
}
chooseContainerElementIfNecessary(callableInfo.possibleContainers, editorForBuilder, popupTitle, true) {
val container = if (it is KtClassBody) it.parent as KtClassOrObject else it
runBuilder { CallablePlacement.NoReceiver(container) }
}
}
}
}
| apache-2.0 | 188b8e317c012ec4552982eb82b83691 | 45.258462 | 158 | 0.658108 | 5.735979 | false | false | false | false |
google/intellij-community | plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpSearch.kt | 7 | 3463 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.builtInHelp.search
import com.google.gson.Gson
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import org.apache.commons.compress.utils.IOUtils
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.DirectoryReader
import org.apache.lucene.queryparser.classic.QueryParser
import org.apache.lucene.search.IndexSearcher
import org.apache.lucene.search.Query
import org.apache.lucene.search.TopScoreDocCollector
import org.apache.lucene.search.highlight.Highlighter
import org.apache.lucene.search.highlight.QueryScorer
import org.apache.lucene.search.highlight.Scorer
import org.apache.lucene.store.FSDirectory
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.NonNls
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class HelpSearch {
companion object {
val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1")
@NonNls
val PREFIX = "/search/"
val NOT_FOUND = "[]"
private val analyzer: StandardAnalyzer = StandardAnalyzer()
@NotNull
fun search(query: String, maxHits: Int): String {
val indexDir: Path? = Files.createTempDirectory("search-index")
var indexDirectory: FSDirectory? = null
var reader: DirectoryReader? = null
if (indexDir != null)
try {
for (resourceName in resources) {
val input = HelpSearch::class.java.getResourceAsStream(
PREFIX + resourceName)
val fos = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile())
IOUtils.copy(input, fos)
fos.flush()
fos.close()
input.close()
}
indexDirectory = FSDirectory.open(indexDir)
reader = DirectoryReader.open(indexDirectory)
ApplicationInfo.getInstance()
val searcher = IndexSearcher(reader)
val collector: TopScoreDocCollector = TopScoreDocCollector.create(maxHits, maxHits)
val q: Query = QueryParser("contents", analyzer).parse(query)
searcher.search(q, collector)
val hits = collector.topDocs().scoreDocs
val scorer: Scorer = QueryScorer(q)
val highlighter = Highlighter(scorer)
val results = ArrayList<HelpSearchResult>()
for (i in hits.indices) {
val doc = searcher.doc(hits[i].doc)
results.add(
HelpSearchResult(i, doc.get("filename"), highlighter.getBestFragment(
analyzer, "contents", doc.get("contents")) + "...",
doc.get("title"), listOf("webhelp")))
}
val searchResults = HelpSearchResults(results)
return if (searchResults.results.isEmpty()) NOT_FOUND else Gson().toJson(searchResults)
}
catch (e: Exception) {
Logger.getInstance(HelpSearch::class.java).error("Error searching help for $query", e)
}
finally {
indexDirectory?.close()
reader?.close()
val tempFiles = indexDir.toFile().listFiles()
tempFiles?.forEach { it.delete() }
Files.delete(indexDir)
}
return NOT_FOUND
}
}
} | apache-2.0 | c6d984e298d01abae80aa1803cdb6d6a | 35.463158 | 140 | 0.669073 | 4.39467 | false | false | false | false |
google/intellij-community | java/java-analysis-impl/src/com/intellij/workspaceModel/ide/legacyBridge/impl/java/LanguageLevelModuleExtensionBridge.kt | 5 | 3140 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.legacyBridge.impl.java
import com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl
import com.intellij.openapi.roots.ModuleExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.java.languageLevel
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridgeFactory
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addJavaModuleSettingsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity
class LanguageLevelModuleExtensionBridge private constructor(private val module: ModuleBridge,
private val entityStorage: VersionedEntityStorage,
private val diff: MutableEntityStorage?) : LanguageLevelModuleExtensionImpl(), ModuleExtensionBridge {
private var changed = false
private val moduleEntity
get() = entityStorage.current.findModuleEntity(module)
override fun setLanguageLevel(languageLevel: LanguageLevel?) {
if (diff == null) error("Cannot modify data via read-only extensions")
val moduleEntity = moduleEntity ?: error("Cannot find entity for $module")
val javaSettings = moduleEntity.javaSettings
if (javaSettings != null) {
diff.modifyEntity(javaSettings) {
this.languageLevel = languageLevel
}
}
else if (languageLevel != null) {
diff.addJavaModuleSettingsEntity(inheritedCompilerOutput = true, excludeOutput = true, compilerOutput = null,
compilerOutputForTests = null, languageLevelId = languageLevel.name, module = moduleEntity,
source = moduleEntity.entitySource)
}
}
override fun getLanguageLevel(): LanguageLevel? {
return moduleEntity?.javaSettings?.languageLevel
}
override fun isChanged(): Boolean = changed
override fun getModifiableModel(writable: Boolean): ModuleExtension {
throw UnsupportedOperationException("This method must not be called for extensions backed by workspace model")
}
override fun commit() = Unit
override fun dispose() = Unit
companion object : ModuleExtensionBridgeFactory<LanguageLevelModuleExtensionBridge> {
override fun createExtension(module: ModuleBridge,
entityStorage: VersionedEntityStorage,
diff: MutableEntityStorage?): LanguageLevelModuleExtensionBridge {
return LanguageLevelModuleExtensionBridge(module, entityStorage, diff)
}
}
} | apache-2.0 | 66ba5998b48ef2cd12ce699c6f0192aa | 51.35 | 163 | 0.742994 | 5.935728 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/DualNodeDeque.kt | 1 | 2667 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Method2
import org.objectweb.asm.Opcodes.GOTO
import org.objectweb.asm.Type.VOID_TYPE
@DependsOn(DualNode::class)
class DualNodeDeque : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.interfaces.isEmpty() }
.and { it.instanceFields.size == 1 }
.and { it.instanceFields.all { it.type == type<DualNode>() } }
class sentinel : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { true }
}
// class clear : IdentityMapper.InstanceMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
// .and { it.instructions.any { it.opcode == GOTO } }
// }
@DependsOn(DualNode::class, DualNode.previousDual::class)
class last : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == type<DualNode>() }
.and { it.instructions.filter { it.isField && it.fieldId == field<DualNode.previousDual>().id }.count() == 1 }
.and { it.instructions.none { it.isMethod } }
}
// @DependsOn(DualNode::class, DualNode.previousDual::class)
// class removeLast : IdentityMapper.InstanceMethod() {
// override val predicate = predicateOf<Method2> { it.returnType == type<DualNode>() }
// .and { it.instructions.filter { it.isField && it.fieldId == field<DualNode.previousDual>().id }.count() == 1 }
// .and { it.instructions.any { it.isMethod } }
// }
@DependsOn(DualNode.previousDual::class)
class addFirst : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.filter { it.isField && it.fieldId == field<DualNode.previousDual>().id }.count() == 3 }
}
@DependsOn(DualNode.previousDual::class)
class addLast : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE }
.and { it.instructions.filter { it.isField && it.fieldId == field<DualNode.previousDual>().id }.count() == 4 }
}
} | mit | ce1356af93a2f965b591690e33bff426 | 47.509091 | 128 | 0.672666 | 4.047041 | false | false | false | false |
jogy/jmoney | src/main/kotlin/name/gyger/jmoney/report/ReportService.kt | 1 | 5303 | package name.gyger.jmoney.report
import name.gyger.jmoney.account.Entry
import name.gyger.jmoney.account.EntryRepository
import name.gyger.jmoney.category.Category
import name.gyger.jmoney.category.CategoryRepository
import name.gyger.jmoney.session.SessionRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
@Service
@Transactional
class ReportService(private val sessionRepository: SessionRepository,
private val categoryRepository: CategoryRepository,
private val reportRepository: ReportRepository,
private val entryRepository: EntryRepository) {
fun getBalances(date: Date?): List<Balance> {
val session = sessionRepository.getSession()
val result = ArrayList<Balance>()
val entrySums = getEntrySumsByAccountId(date)
var totalBalance: Long = 0
for (account in session.accounts) {
var balance: Long = 0
val sum = entrySums[account.id]
if (sum != null) {
balance = sum
}
balance += account.startBalance
totalBalance += balance
val dto = Balance(account.name, balance, false)
result.add(dto)
}
val totalBalanceDto = Balance("Total", totalBalance, true)
result.add(totalBalanceDto)
return result
}
fun getCashFlow(from: Date?, to: Date?): List<CashFlow> {
val session = sessionRepository.getSession()
val resultList = ArrayList<CashFlow>()
categoryRepository.findAll() // prefetch
val root = session.rootCategory
val entrySums = getEntrySumsByCategoryId(from, to)
var totalIncome: Long = 0
var totalExpense: Long = 0
for (child in root.children) {
val subList = ArrayList<CashFlow>()
calculateCashFlowForCategory(subList, entrySums, child, null)
var income: Long = 0
var expense: Long = 0
for (cashFlow in subList) {
income += toZeroIfNull(cashFlow.income)
expense += toZeroIfNull(cashFlow.expense)
}
if (income != 0L || expense != 0L) {
val childDto = CashFlow(null, child.name + " (Total)", income, expense, income - expense, true)
subList.add(childDto)
}
totalIncome += income
totalExpense += expense
resultList.addAll(subList)
}
val total = CashFlow(null, "Total", totalIncome, totalExpense, totalIncome - totalExpense, true)
resultList.add(total)
return resultList
}
fun getInconsistentSplitEntries(): List<Entry> {
val splitCategory = sessionRepository.getSession().splitCategory
val entries = entryRepository.getInconsistentSplitEntries(splitCategory.id)
val splitEntrySums = getSplitEntrySums()
val result = ArrayList<Entry>()
for (entry in entries) {
var sum: Long? = splitEntrySums[entry.id]
if (sum == null) {
sum = java.lang.Long.valueOf(0)
}
if (entry.amount != sum) {
result.add(entry)
}
entry.accountId = entry.account?.id ?: 0
}
return result
}
private fun getEntrySumsByAccountId(date: Date?): Map<Long, Long> {
return reportRepository.getEntrySumsByAccountId(date)
.map { it.id to it.amount }.toMap()
}
private fun getEntrySumsByCategoryId(from: Date?, to: Date?): Map<Long, Long> {
return reportRepository.getEntrySumsByCategoryId(from, to)
.map { it.id to it.amount }.toMap()
}
fun getSplitEntrySums(): Map<Long, Long> {
return reportRepository.getSplitEntrySums()
.map { it.id to it.amount }.toMap()
}
private fun toZeroIfNull(value: Long?): Long {
return value ?: 0
}
private fun calculateCashFlowForCategory(resultList: MutableList<CashFlow>, entrySums: Map<Long, Long>,
category: Category, parentName: String?) {
val name = createCategoryName(category, parentName)
if (category.type == Category.Type.NORMAL) {
val sum = entrySums[category.id]
createCategoryFlowDto(resultList, category.id, name, sum)
}
for (child in category.children) {
calculateCashFlowForCategory(resultList, entrySums, child, name)
}
}
private fun createCategoryFlowDto(resultList: MutableList<CashFlow>, id: Long?, name: String, sum: Long?) {
if (sum != null) {
var income: Long? = null
var expense: Long? = null
if (sum >= 0) {
income = sum
} else {
expense = -sum
}
val dto = CashFlow(id, name, income, expense, null, false)
resultList.add(dto)
}
}
private fun createCategoryName(category: Category, parentName: String?): String {
var name = category.name
if (parentName != null) {
name = parentName + ":" + name
}
return name
}
}
| mit | a2d9eccff2c05c7a51eb2825a679ea0c | 32.352201 | 111 | 0.596455 | 4.611304 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/achievement/ui/activity/AchievementsListActivity.kt | 1 | 1367 | package org.stepik.android.view.achievement.ui.activity
import android.content.Context
import android.content.Intent
import android.view.MenuItem
import androidx.fragment.app.Fragment
import org.stepic.droid.base.SingleFragmentActivity
import org.stepik.android.view.achievement.ui.fragment.AchievementsListFragment
class AchievementsListActivity : SingleFragmentActivity() {
companion object {
private const val EXTRA_USER_ID = "user_id"
private const val EXTRA_IS_MY_PROFILE = "is_my_profile"
fun createIntent(context: Context, userId: Long, isMyProfile: Boolean): Intent =
Intent(context, AchievementsListActivity::class.java)
.putExtra(EXTRA_USER_ID, userId)
.putExtra(EXTRA_IS_MY_PROFILE, isMyProfile)
}
override fun createFragment(): Fragment =
AchievementsListFragment
.newInstance(
userId = intent?.getLongExtra(EXTRA_USER_ID, 0) ?: 0,
isMyProfile = intent?.getBooleanExtra(EXTRA_IS_MY_PROFILE, false) ?: false
)
override fun applyTransitionPrev() {
// no-op
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | c9e95ea625188536baf6617a31fc46a2 | 34.076923 | 90 | 0.671544 | 4.602694 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/TrackChangeButton.kt | 2 | 3393 | package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Interpolation
import io.github.chrislo27.rhre3.editor.CameraPan
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.editor.action.EntitySelectionAction
import io.github.chrislo27.rhre3.editor.action.TrackResizeAction
import io.github.chrislo27.rhre3.entity.Entity
import io.github.chrislo27.rhre3.entity.model.special.EndRemixEntity
import io.github.chrislo27.rhre3.screen.EditorScreen
import io.github.chrislo27.rhre3.track.PlayState
import io.github.chrislo27.rhre3.track.Remix
import io.github.chrislo27.toolboks.i18n.Localization
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.ui.*
import kotlin.math.roundToInt
class TrackChangeButton(val editor: Editor, palette: UIPalette, parent: UIElement<EditorScreen>, stage: Stage<EditorScreen>)
: Button<EditorScreen>(palette, parent, stage) {
private val remix: Remix
get() = editor.remix
init {
addLabel(ImageLabel(palette, this, this.stage).apply {
this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO
this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_track_change_button"))
})
}
override var tooltipText: String?
set(_) {}
get() {
return Localization["editor.trackChange"] + " [LIGHT_GRAY](${Editor.MIN_TRACK_COUNT}≦[]${remix.trackCount}[LIGHT_GRAY]≦${Editor.MAX_TRACK_COUNT})[]\n" +
Localization[if (remix.canIncreaseTrackCount()) "editor.trackChange.increase" else "editor.trackChange.max"] + "\n" +
Localization[if (!remix.canDecreaseTrackCount()) "editor.trackChange.min" else if (remix.entitiesTouchTrackTop) "editor.trackChange.impedance" else "editor.trackChange.decrease"]
}
override fun onLeftClick(xPercent: Float, yPercent: Float) {
super.onLeftClick(xPercent, yPercent)
if (remix.playState == PlayState.STOPPED && remix.canIncreaseTrackCount()) {
remix.mutate(TrackResizeAction(editor, remix.trackCount, remix.trackCount + 1))
remix.recomputeCachedData()
}
}
override fun onRightClick(xPercent: Float, yPercent: Float) {
super.onRightClick(xPercent, yPercent)
if (remix.playState == PlayState.STOPPED && remix.canDecreaseTrackCount()) {
if (!remix.wouldEntitiesFitNewTrackCount(remix.trackCount - 1)) {
// Jump to first blocking entity
val entities = remix.entities.filterNot { it is EndRemixEntity }
.filter { (it.bounds.y + it.bounds.height).roundToInt() >= remix.trackCount }.takeUnless(List<Entity>::isEmpty) ?: return
if (!(editor.selection.containsAll(entities) && editor.selection.size == entities.size)) {
remix.mutate(EntitySelectionAction(editor, editor.selection.toList(), entities))
}
editor.cameraPan = CameraPan(editor.camera.position.x, entities.first().bounds.x, 0.5f, Interpolation.exp10Out)
} else {
remix.mutate(TrackResizeAction(editor, remix.trackCount, remix.trackCount - 1))
remix.recomputeCachedData()
}
}
}
} | gpl-3.0 | eb34fa2cb60657e873332872910bb666 | 48.852941 | 198 | 0.694305 | 4.107879 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCaseExt.kt | 3 | 16806 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.impl
import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader
import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder
import com.intellij.testGuiFramework.fixtures.ActionButtonFixture
import com.intellij.testGuiFramework.fixtures.GutterFixture
import com.intellij.testGuiFramework.fixtures.IdeFrameFixture
import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.framework.toPrintable
import com.intellij.testGuiFramework.util.*
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.LocationUnavailableException
import org.fest.swing.exception.WaitTimedOutError
import org.fest.swing.timing.Timeout
import org.hamcrest.Matcher
import org.junit.Assert.assertTrue
import org.junit.rules.ErrorCollector
import java.awt.IllegalComponentStateException
import javax.swing.JTree
fun <T> ErrorCollector.checkThat(value: T, matcher: Matcher<T>, reason: () -> String) {
checkThat(reason(), value, matcher)
}
/**
* Closes the current project
* */
fun GuiTestCase.closeProject() {
ideFrame {
step("close the project") {
waitAMoment()
closeProject()
}
}
}
/**
* Provide waiting for background tasks to finish
* This function should be used instead of [IdeFrameFixture.waitForBackgroundTasksToFinish]
* because sometimes the latter doesn't wait enough time
* The function searches for async icon indicator and waits for its disappearing
* This occurs several times as background processes often goes one after another.
* */
fun GuiTestCase.waitAMoment() {
fun isWaitIndicatorPresent(): Boolean {
var result = false
ideFrame {
result = indexingProcessIconNullable(Timeouts.seconds03) != null
}
return result
}
fun waitBackgroundTaskOneAttempt(attempt: Int) {
step("wait for background task - attempt #$attempt") {
ideFrame {
this.waitForBackgroundTasksToFinish()
val asyncIcon = indexingProcessIconNullable(Timeouts.seconds03)
if (asyncIcon != null) {
val timeoutForBackgroundTasks = Timeouts.minutes10
try {
step("search and click on async icon") {
asyncIcon.click()
}
step("wait for panel 'Background tasks' disappears") {
waitForPanelToDisappear(
panelTitle = "Background Tasks",
timeoutToAppear = Timeouts.seconds01,
timeoutToDisappear = timeoutForBackgroundTasks
)
}
}
catch (ignore: NullPointerException) {
// if asyncIcon disappears at once after getting the NPE from fest might occur
// but it's ok - nothing to wait anymore
}
catch (ignore: IllegalComponentStateException) {
// do nothing - asyncIcon disappears, background process has stopped
}
catch (ignore: ComponentLookupException) {
// do nothing - panel hasn't appeared and it seems ok
}
catch (ignore: IllegalStateException) {
// asyncIcon searched earlier might disappear at all (it's ok)
}
catch (ignore: IllegalArgumentException) {
// asyncIcon searched earlier might disappear at all (it's ok)
}
catch (e: WaitTimedOutError) {
throw WaitTimedOutError("Background process hadn't finished after ${timeoutForBackgroundTasks.toPrintable()}")
}
}
else logInfo("no async icon found - no background process")
}
logInfo("attempt #$attempt of waiting for background task finished")
}
}
step("wait for background task") {
val maxAttemptsWaitForBackgroundTasks = 5
var currentAttempt = maxAttemptsWaitForBackgroundTasks
while (isWaitIndicatorPresent() && currentAttempt >= 0) {
waitBackgroundTaskOneAttempt(maxAttemptsWaitForBackgroundTasks - currentAttempt)
currentAttempt--
}
if (currentAttempt < 0) {
throw WaitTimedOutError(
"Background processes still continue after $maxAttemptsWaitForBackgroundTasks attempts to wait for their finishing")
}
logInfo("wait for background task finished")
}
}
/**
* Performs test whether the specified item exists in a tree
* Note: the dialog with the investigated tree must be open
* before using this test
* @param expectedItem - expected exact item
* @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message
* @param predicate - searcher rule, how to compare an item and name. By default they are compared by equality
* */
fun GuiTestCase.testTreeItemExist(name: String, vararg expectedItem: String, predicate: FinderPredicate = Predicate.equality, timeout: Timeout = Timeouts.defaultTimeout) {
ideFrame {
logInfo("Check that $name -> ${expectedItem.joinToString(" -> ")} exists in a tree element")
kotlin.assert(exists { jTree(*expectedItem, predicate = predicate, timeout = timeout) }) { "$name '${expectedItem.joinToString(", ")}' not found" }
}
}
/**
* Performs test whether the specified item exists in a list
* Note: the dialog with the investigated list must be open
* before using this test
* @param expectedItem - expected exact item
* @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message
* */
fun GuiTestCase.testListItemExist(name: String, expectedItem: String) {
ideFrame {
logInfo("Check that $name -> $expectedItem exists in a list element")
kotlin.assert(exists { jList(expectedItem, timeout = Timeouts.seconds05) }) { "$name '$expectedItem' not found" }
}
}
/**
* Performs test whether the specified item exists in a table
* Note: the dialog with the investigated list must be open
* before using this test
* @param expectedItem - expected exact item
* @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message
* */
fun GuiTestCase.testTableItemExist(name: String, expectedItem: String) {
ideFrame {
logInfo("Check that $name -> $expectedItem exists in a list element")
kotlin.assert(exists { table(expectedItem, timeout = Timeouts.seconds05) }) { "$name '$expectedItem' not found" }
}
}
/**
* Selects specified [path] in the tree by keyboard searching
* @param path in string form
* @param testCase - test case is required only because of keyboard related functions
*
* TODO: remove [testCase] parameter (so move [shortcut] and [typeText] functions
* out of GuiTestCase)
* */
fun ExtendedJTreePathFixture.selectWithKeyboard(testCase: GuiTestCase, vararg path: String) {
fun currentValue(): String {
val selectedRow = target().selectionRows.first()
return valueAt(selectedRow) ?: throw IllegalStateException("Nothing is selected in the tree")
}
click()
testCase.shortcut(Key.HOME) // select the top row
for((index, step) in path.withIndex()){
if(currentValue() != step) {
testCase.typeText(step)
while (currentValue() != step)
testCase.shortcut(Key.DOWN)
}
if(index < path.size -1) testCase.shortcut(Key.RIGHT)
}
}
/**
* Wait for Gradle reimport finishing
* I detect end of reimport by following signs:
* - action button "Refresh all external projects" becomes enable. But sometimes it becomes
* enable only for a couple of moments and becomes disable again.
* - status in the first line in the Build tool window becomes `sync finished` or `sync failed`
*
* @param rootPath root name expected to be shown in the tree. Checked only if [waitForProject] is true
* @return status of reimport - true - successful, false - failed
* */
fun GuiTestCase.waitForGradleReimport(rootPath: String): Boolean {
val syncSuccessful = "sync finished"
val syncFailed = "sync failed"
var reimportStatus = ""
step("wait for Gradle project reload") {
GuiTestUtilKt.waitUntil("for gradle project reload finishing", timeout = Timeouts.minutes05) {
var isReimportButtonEnabled: Boolean = false
var syncState = false
try {
ideFrame {
toolwindow(id = "Gradle") {
content(tabName = "") {
// first, check whether the action button "Refresh all external projects" is enabled
val text = "Refresh all external projects"
isReimportButtonEnabled = try {
val fixtureByTextAnyState = ActionButtonFixture.fixtureByTextAnyState(this.target(), robot(), text)
assertTrue("Gradle refresh button should be visible and showing", this.target().isShowing && this.target().isVisible)
fixtureByTextAnyState.isEnabled
}
catch (e: Exception) {
false
}
logInfo("'$text' button is ${if(isReimportButtonEnabled) "enabled" else "disabled"}")
}
}
// second, check status in the Build tool window
toolwindow(id = "Build") {
content(tabName = "Sync") {
val tree = treeTable().target().tree
val pathStrings = listOf(rootPath)
val treePath = try {
ExtendedJTreePathFinder(tree).findMatchingPathByPredicate(pathStrings = pathStrings, predicate = Predicate.startWith)
}
catch (e: LocationUnavailableException) {
null
}
if (treePath != null) {
reimportStatus = ExtendedJTreeCellReader().valueAtExtended(tree, treePath) ?: ""
syncState = reimportStatus.contains(syncSuccessful) || reimportStatus.contains(syncFailed)
}
else {
syncState = false
}
logInfo("Project reload status is '$reimportStatus', synchronization is ${if(syncState) "finished" else "in process"}")
}
}
}
}
catch (ignore: Exception) {}
// final calculating of result
val result = isReimportButtonEnabled && syncState
result
}
logInfo("end of waiting for background task")
}
return reimportStatus.contains(syncSuccessful)
}
fun GuiTestCase.gradleReimport() {
step("reload gradle project") {
ideFrame {
toolwindow(id = "Gradle") {
content(tabName = "") {
waitAMoment()
step("click 'Refresh all external projects' button") {
actionButton("Refresh all external projects", timeout = Timeouts.minutes05).click()
}
}
}
}
}
}
fun GuiTestCase.mavenReimport() {
step("reload maven project") {
ideFrame {
toolwindow(id = "Maven") {
content(tabName = "") {
step("search when button 'Reload All Maven Projects' becomes enable and click it") {
val reimportAction = "Reload All Maven Projects"
val showDepAction = "Show UML Diagram" // but tooltip says "Show Dependencies"
GuiTestUtilKt.waitUntil("Wait for button '$reimportAction' to be enabled.", timeout = Timeouts.minutes02) {
actionButton(reimportAction, timeout = Timeouts.seconds30).isEnabled
}
try {
actionButton(showDepAction, timeout = Timeouts.minutes01)
}
catch (ignore: ComponentLookupException) {
logInfo("Maven reload: not found 'Show Dependencies' button after 1 min waiting")
}
robot().waitForIdle()
actionButton(reimportAction).click()
robot().waitForIdle()
}
}
}
}
}
}
fun GuiTestCase.checkProjectIsCompiled(expectedStatus: String) {
val textEventLog = "Event Log"
ideFrame {
step("check the project compiles") {
step("invoke main menu 'CompileProject' ") { invokeMainMenu("CompileProject") }
waitAMoment()
toolwindow(id = textEventLog) {
content(tabName = "") {
editor {
GuiTestUtilKt.waitUntil("Wait for '$expectedStatus' appears") {
val output = this.getCurrentFileContents(false)?.lines() ?: emptyList()
val lastLine = output.lastOrNull { it.trim().isNotEmpty() } ?: ""
lastLine.contains(expectedStatus)
}
}
}
}
}
}
}
fun GuiTestCase.checkProjectIsRun(configuration: String, message: String) {
val buttonRun = "Run"
step("run configuration `$configuration`") {
ideFrame {
navigationBar {
actionButton(buttonRun).click()
}
waitAMoment()
toolwindow(id = buttonRun) {
content(tabName = configuration) {
editor {
GuiTestUtilKt.waitUntil("Wait for '$message' appears") {
val output = this.getCurrentFileContents(false)?.lines()?.filter { it.trim().isNotEmpty() } ?: listOf()
logInfo("output: ${output.map { "\n\t$it" }}")
logInfo("expected message = '$message'")
output.firstOrNull { it.contains(message) } != null
}
}
}
}
}
}
}
fun GuiTestCase.checkGutterIcons(gutterIcon: GutterFixture.GutterIcon,
expectedNumberOfIcons: Int,
expectedLines: List<String>) {
ideFrame {
step("check whether $expectedNumberOfIcons '$gutterIcon' gutter icons are present") {
editor {
step("wait for editor file has been loaded") {
waitUntilFileIsLoaded()
waitAMoment()
waitUntilErrorAnalysisFinishes()
}
}
editor {
step("wait for gutter icons appearing") {
gutter.waitUntilIconsShown(mapOf(gutterIcon to expectedNumberOfIcons))
moveToLine(expectedNumberOfIcons)
}
val gutterLinesWithIcon = gutter.linesWithGutterIcon(gutterIcon)
val contents = [email protected](false)?.lines() ?: listOf()
for ((index, line) in gutterLinesWithIcon.withIndex()) {
// line numbers start with 1, but index in the contents list starts with 0
val currentLine = contents[line - 1]
val expectedLine = expectedLines[index]
logInfo("Found line '$currentLine' with icon '$gutterIcon'. Expected line is '$expectedLine'")
assert(currentLine.contains(expectedLine)) {
"At line #$line the actual text is `$currentLine`, but it was expected `$expectedLine`"
}
}
}
}
}
}
fun GuiTestCase.createJdk(jdkPath: String, jdkName: String = ""): String{
val dialogName = "Project Structure for New Projects"
return step("create a JDK on the path `$jdkPath`") {
lateinit var installedJdkName: String
welcomeFrame {
actionLink("Configure").click()
popupMenu("Structure for New Projects").clickSearchedItem()
step("open `$dialogName` dialog") {
dialog(dialogName) {
jList("SDKs").clickItem("SDKs")
val sdkTree: ExtendedJTreePathFixture = jTree()
fun JTree.getListOfInstalledSdks(): List<String> {
val root = model.root
return (0 until model.getChildCount(root))
.map { model.getChild(root, it).toString() }.toList()
}
val preInstalledSdks = sdkTree.tree.getListOfInstalledSdks()
installedJdkName = if (jdkName.isEmpty() || preInstalledSdks.contains(jdkName).not()) {
actionButton("Add New SDK").click()
popupMenu("JDK").clickSearchedItem()
step("open `Select Home Directory for JDK` dialog") {
dialog("Select Home Directory for JDK") {
actionButton("Refresh").click()
step("type the path `$jdkPath`") {
typeText(jdkPath)
}
step("close `Select Home Directory for JDK` dialog with OK") {
button("OK").click()
}
}
}
val postInstalledSdks = sdkTree.tree.getListOfInstalledSdks()
postInstalledSdks.first { preInstalledSdks.contains(it).not() }
}
else jdkName
step("close `Default Project Structure` dialog with OK") {
button("OK").click()
}
} // dialog Project Structure
}
} // ideFrame
return@step installedJdkName
}
}
fun <T1, T2, R> combine(first: Iterable<T1>,
second: Iterable<T2>,
combiner: (T1, T2) -> R): List<R> = first.flatMap { firstItem ->
second.map { secondItem ->
combiner(firstItem, secondItem)
}
}
| apache-2.0 | b12360475a2fc3247307e5693b683283 | 38.450704 | 171 | 0.643937 | 4.808584 | false | true | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/sdk/PySdkSettings.kt | 1 | 4133 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.application.options.ReplacePathToMacroMap
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtil
import com.intellij.util.SystemProperties
import com.intellij.util.xmlb.XmlSerializerUtil
import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor
import org.jetbrains.annotations.SystemIndependent
import org.jetbrains.jps.model.serialization.PathMacroUtil
/**
* @author vlan
*/
@State(name = "PySdkSettings", storages = [Storage(value = "pySdk.xml", roamingType = RoamingType.DISABLED)])
class PySdkSettings : PersistentStateComponent<PySdkSettings.State> {
companion object {
@JvmStatic
val instance: PySdkSettings
get() = ApplicationManager.getApplication().getService(PySdkSettings::class.java)
private const val VIRTUALENV_ROOT_DIR_MACRO_NAME = "VIRTUALENV_ROOT_DIR"
}
private val state: State = State()
var useNewEnvironmentForNewProject: Boolean
get() = state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT
set(value) {
state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT = value
}
var preferredEnvironmentType: String?
get() = state.PREFERRED_ENVIRONMENT_TYPE
set(value) {
state.PREFERRED_ENVIRONMENT_TYPE = value
}
var preferredVirtualEnvBaseSdk: String?
get() = state.PREFERRED_VIRTUALENV_BASE_SDK
set(value) {
state.PREFERRED_VIRTUALENV_BASE_SDK = value
}
fun onVirtualEnvCreated(baseSdk: Sdk, location: @SystemIndependent String, projectPath: @SystemIndependent String?) {
setPreferredVirtualEnvBasePath(location, projectPath)
preferredVirtualEnvBaseSdk = baseSdk.homePath
}
fun setPreferredVirtualEnvBasePath(value: @SystemIndependent String, projectPath: @SystemIndependent String?) {
val pathMap = ReplacePathToMacroMap().apply {
projectPath?.let {
addMacroReplacement(it, PathMacroUtil.PROJECT_DIR_MACRO_NAME)
}
addMacroReplacement(defaultVirtualEnvRoot, VIRTUALENV_ROOT_DIR_MACRO_NAME)
}
val pathToSave = when {
projectPath != null && FileUtil.isAncestor(projectPath, value, true) -> value.trimEnd { !it.isLetter() }
else -> PathUtil.getParentPath(value)
}
state.PREFERRED_VIRTUALENV_BASE_PATH = pathMap.substitute(pathToSave, true)
}
fun getPreferredVirtualEnvBasePath(projectPath: @SystemIndependent String?): @SystemIndependent String {
val pathMap = ExpandMacroToPathMap().apply {
addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectPath ?: userHome)
addMacroExpand(VIRTUALENV_ROOT_DIR_MACRO_NAME, defaultVirtualEnvRoot)
}
val defaultPath = when {
defaultVirtualEnvRoot != userHome -> defaultVirtualEnvRoot
else -> "$${PathMacroUtil.PROJECT_DIR_MACRO_NAME}$/venv"
}
val rawSavedPath = state.PREFERRED_VIRTUALENV_BASE_PATH ?: defaultPath
val savedPath = pathMap.substitute(rawSavedPath, true)
return when {
projectPath != null && FileUtil.isAncestor(projectPath, savedPath, true) -> savedPath
projectPath != null -> "$savedPath/${PathUtil.getFileName(projectPath)}"
else -> savedPath
}
}
override fun getState(): State = state
override fun loadState(state: State) {
XmlSerializerUtil.copyBean(state, this.state)
}
@Suppress("PropertyName")
class State {
@JvmField
var USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT: Boolean = true
@JvmField
var PREFERRED_ENVIRONMENT_TYPE: String? = null
@JvmField
var PREFERRED_VIRTUALENV_BASE_PATH: String? = null
@JvmField
var PREFERRED_VIRTUALENV_BASE_SDK: String? = null
}
private val defaultVirtualEnvRoot: @SystemIndependent String
get() = VirtualEnvSdkFlavor.getDefaultLocation()?.path ?: userHome
private val userHome: @SystemIndependent String
get() = FileUtil.toSystemIndependentName(SystemProperties.getUserHome())
} | apache-2.0 | b46907baaeff685db3ce1708d3141a6b | 36.926606 | 140 | 0.744737 | 4.571903 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/common/Movie.kt | 1 | 2615 | package slatekit.examples.common
import slatekit.common.DateTime
import slatekit.common.DateTimes
import slatekit.common.Field
import slatekit.entities.EntityWithId
// NOTES: You can entities properties to be persisted
// in 3 different ways:
// 1. annotations on the Entity
// 2. building a Model and manually registering property references
// 3. building a Model and manually registering via field/names
//
// See Example_Mapper.kt and slatekit.common.Model for more info.
//
// IMMUTABILITY:
// The ORM is originally built for immutable Entities ( Data Classes )
// It also supports Entities with "vars", but has not been tested.
// In a future release, we will fully support var properties
data class Movie(
override val id :Long = 0L,
@property:Field(required = true, length = 50)
val title :String = "",
@property:Field(length = 20)
val category :String = "",
@property:Field(required = true)
val playing :Boolean = false,
@property:Field(required = true)
val cost:Int,
@property:Field(required = true)
val rating: Double,
@property:Field(required = true)
val released: DateTime,
// These are the timestamp and audit fields.
@property:Field(required = true)
val createdAt : DateTime = DateTime.now(),
@property:Field(required = true)
val createdBy :Long = 0,
@property:Field(required = true)
val updatedAt : DateTime = DateTime.now(),
@property:Field(required = true)
val updatedBy :Long = 0
)
: EntityWithId<Long>
{
override fun isPersisted(): Boolean = id > 0
companion object {
fun of(title:String, playing:Boolean, cost:Int, released: DateTime):Movie {
return Movie(title = title, playing = playing, cost = cost, rating = 0.0, released = released)
}
fun samples():List<Movie> = listOf(
Movie(
title = "Indiana Jones: Raiders of the Lost Ark",
category = "Adventure",
playing = false,
cost = 10,
rating = 4.5,
released = DateTimes.of(1985, 8, 10)
),
Movie(
title = "WonderWoman",
category = "action",
playing = true,
cost = 100,
rating = 4.2,
released = DateTimes.of(2017, 7, 4)
)
)
}
} | apache-2.0 | 8c4d7e513c89e3d0ef0909597c4e2ea8 | 26.536842 | 107 | 0.560994 | 4.571678 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.