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
googlecodelabs/odml-pathways
object-detection/codelab2/android/final/app/src/main/java/org/tensorflow/codelabs/objectdetection/MainActivity.kt
2
12586
/** * 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 * * https://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.tensorflow.codelabs.objectdetection import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.graphics.* import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import androidx.exifinterface.media.ExifInterface import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.task.vision.detector.Detection import org.tensorflow.lite.task.vision.detector.ObjectDetector import java.io.File import java.io.IOException import java.text.SimpleDateFormat import java.util.* import kotlin.math.max import kotlin.math.min class MainActivity : AppCompatActivity(), View.OnClickListener { companion object { const val TAG = "TFLite - ODT" const val REQUEST_IMAGE_CAPTURE: Int = 1 private const val MAX_FONT_SIZE = 96F } private lateinit var captureImageFab: Button private lateinit var inputImageView: ImageView private lateinit var imgSampleOne: ImageView private lateinit var imgSampleTwo: ImageView private lateinit var imgSampleThree: ImageView private lateinit var tvPlaceholder: TextView private lateinit var currentPhotoPath: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) captureImageFab = findViewById(R.id.captureImageFab) inputImageView = findViewById(R.id.imageView) imgSampleOne = findViewById(R.id.imgSampleOne) imgSampleTwo = findViewById(R.id.imgSampleTwo) imgSampleThree = findViewById(R.id.imgSampleThree) tvPlaceholder = findViewById(R.id.tvPlaceholder) captureImageFab.setOnClickListener(this) imgSampleOne.setOnClickListener(this) imgSampleTwo.setOnClickListener(this) imgSampleThree.setOnClickListener(this) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK ) { setViewAndDetect(getCapturedImage()) } } /** * onClick(v: View?) * Detect touches on the UI components */ override fun onClick(v: View?) { when (v?.id) { R.id.captureImageFab -> { try { dispatchTakePictureIntent() } catch (e: ActivityNotFoundException) { Log.e(TAG, e.message.toString()) } } R.id.imgSampleOne -> { setViewAndDetect(getSampleImage(R.drawable.img_meal_one)) } R.id.imgSampleTwo -> { setViewAndDetect(getSampleImage(R.drawable.img_meal_two)) } R.id.imgSampleThree -> { setViewAndDetect(getSampleImage(R.drawable.img_meal_three)) } } } /** * runObjectDetection(bitmap: Bitmap) * TFLite Object Detection function */ private fun runObjectDetection(bitmap: Bitmap) { // Step 1: Create TFLite's TensorImage object val image = TensorImage.fromBitmap(bitmap) // Step 2: Initialize the detector object val options = ObjectDetector.ObjectDetectorOptions.builder() .setMaxResults(5) .setScoreThreshold(0.3f) .build() val detector = ObjectDetector.createFromFileAndOptions( this, "salad.tflite", options ) // Step 3: Feed given image to the detector val results = detector.detect(image) // Step 4: Parse the detection result and show it val resultToDisplay = results.map { // Get the top-1 category and craft the display text val category = it.categories.first() val text = "${category.label}, ${category.score.times(100).toInt()}%" // Create a data object to display the detection result DetectionResult(it.boundingBox, text) } // Draw the detection result on the bitmap and show it. val imgWithResult = drawDetectionResult(bitmap, resultToDisplay) runOnUiThread { inputImageView.setImageBitmap(imgWithResult) } } /** * debugPrint(visionObjects: List<Detection>) * Print the detection result to logcat to examine */ private fun debugPrint(results : List<Detection>) { for ((i, obj) in results.withIndex()) { val box = obj.boundingBox Log.d(TAG, "Detected object: ${i} ") Log.d(TAG, " boundingBox: (${box.left}, ${box.top}) - (${box.right},${box.bottom})") for ((j, category) in obj.categories.withIndex()) { Log.d(TAG, " Label $j: ${category.label}") val confidence: Int = category.score.times(100).toInt() Log.d(TAG, " Confidence: ${confidence}%") } } } /** * setViewAndDetect(bitmap: Bitmap) * Set image to view and call object detection */ private fun setViewAndDetect(bitmap: Bitmap) { // Display capture image inputImageView.setImageBitmap(bitmap) tvPlaceholder.visibility = View.INVISIBLE // Run ODT and display result // Note that we run this in the background thread to avoid blocking the app UI because // TFLite object detection is a synchronised process. lifecycleScope.launch(Dispatchers.Default) { runObjectDetection(bitmap) } } /** * getCapturedImage(): * Decodes and crops the captured image from camera. */ private fun getCapturedImage(): Bitmap { // Get the dimensions of the View val targetW: Int = inputImageView.width val targetH: Int = inputImageView.height val bmOptions = BitmapFactory.Options().apply { // Get the dimensions of the bitmap inJustDecodeBounds = true BitmapFactory.decodeFile(currentPhotoPath, this) val photoW: Int = outWidth val photoH: Int = outHeight // Determine how much to scale down the image val scaleFactor: Int = max(1, min(photoW / targetW, photoH / targetH)) // Decode the image file into a Bitmap sized to fill the View inJustDecodeBounds = false inSampleSize = scaleFactor inMutable = true } val exifInterface = ExifInterface(currentPhotoPath) val orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED ) val bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions) return when (orientation) { ExifInterface.ORIENTATION_ROTATE_90 -> { rotateImage(bitmap, 90f) } ExifInterface.ORIENTATION_ROTATE_180 -> { rotateImage(bitmap, 180f) } ExifInterface.ORIENTATION_ROTATE_270 -> { rotateImage(bitmap, 270f) } else -> { bitmap } } } /** * getSampleImage(): * Get image form drawable and convert to bitmap. */ private fun getSampleImage(drawable: Int): Bitmap { return BitmapFactory.decodeResource(resources, drawable, BitmapFactory.Options().apply { inMutable = true }) } /** * rotateImage(): * Decodes and crops the captured image from camera. */ private fun rotateImage(source: Bitmap, angle: Float): Bitmap { val matrix = Matrix() matrix.postRotate(angle) return Bitmap.createBitmap( source, 0, 0, source.width, source.height, matrix, true ) } /** * createImageFile(): * Generates a temporary image file for the Camera app to write to. */ @Throws(IOException::class) private fun createImageFile(): File { // Create an image file name val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date()) val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( "JPEG_${timeStamp}_", /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ).apply { // Save a file: path for use with ACTION_VIEW intents currentPhotoPath = absolutePath } } /** * dispatchTakePictureIntent(): * Start the Camera app to take a photo. */ private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> // Ensure that there's a camera activity to handle the intent takePictureIntent.resolveActivity(packageManager)?.also { // Create the File where the photo should go val photoFile: File? = try { createImageFile() } catch (e: IOException) { Log.e(TAG, e.message.toString()) null } // Continue only if the File was successfully created photoFile?.also { val photoURI: Uri = FileProvider.getUriForFile( this, "org.tensorflow.codelabs.objectdetection.fileprovider", it ) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) } } } } /** * drawDetectionResult(bitmap: Bitmap, detectionResults: List<DetectionResult> * Draw a box around each objects and show the object's name. */ private fun drawDetectionResult( bitmap: Bitmap, detectionResults: List<DetectionResult> ): Bitmap { val outputBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true) val canvas = Canvas(outputBitmap) val pen = Paint() pen.textAlign = Paint.Align.LEFT detectionResults.forEach { // draw bounding box pen.color = Color.RED pen.strokeWidth = 8F pen.style = Paint.Style.STROKE val box = it.boundingBox canvas.drawRect(box, pen) val tagSize = Rect(0, 0, 0, 0) // calculate the right font size pen.style = Paint.Style.FILL_AND_STROKE pen.color = Color.YELLOW pen.strokeWidth = 2F pen.textSize = MAX_FONT_SIZE pen.getTextBounds(it.text, 0, it.text.length, tagSize) val fontSize: Float = pen.textSize * box.width() / tagSize.width() // adjust the font size so texts are inside the bounding box if (fontSize < pen.textSize) pen.textSize = fontSize var margin = (box.width() - tagSize.width()) / 2.0F if (margin < 0F) margin = 0F canvas.drawText( it.text, box.left + margin, box.top + tagSize.height().times(1F), pen ) } return outputBitmap } } /** * DetectionResult * A class to store the visualization info of a detected object. */ data class DetectionResult(val boundingBox: RectF, val text: String)
apache-2.0
ee4b61bd39c872af1e3a0282dea70a72
34.254902
97
0.612983
4.831478
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/go/GoCommon.kt
1
15389
package ee.lang.gen.go import ee.common.ext.* import ee.lang.* import ee.lang.gen.java.j fun <T : MacroCompositeI<*>> T.toGoMacrosBefore(c: GenerationContext, derived: String, api: String): String = macrosBefore().joinToString("$nL ") { c.body(it, this, derived, api) } fun <T : MacroCompositeI<*>> T.toGoMacrosBeforeBody(c: GenerationContext, derived: String, api: String): String = macrosBeforeBody().joinToString("$nL ") { c.body(it, this, derived, api) } fun <T : MacroCompositeI<*>> T.toGoMacrosBody(c: GenerationContext, derived: String, api: String): String = macrosBody().joinToString("$nL ") { c.body(it, this, derived, api) } fun <T : MacroCompositeI<*>> T.toGoMacrosAfterBody(c: GenerationContext, derived: String, api: String): String = macrosAfterBody().joinToString("$nL ") { c.body(it, this, derived, api) } fun <T : MacroCompositeI<*>> T.toGoMacrosAfter(c: GenerationContext, derived: String, api: String): String = macrosAfter().joinToString("$nL ") { c.body(it, this, derived, api) } fun AttributeI<*>.toGoInitVariables(c: GenerationContext, derived: String, parentConstrName: String = ""): String { val name = "${name().decapitalize()} := " return name + if (isDefault() || value() != null) { toGoValue(c, derived, parentConstrName) } else { name() } } fun AttributeI<*>.toGoInitVariablesExplodedAnonymous( c: GenerationContext, derived: String, parentConstrName: String = "" ): String { val name = "${name().decapitalize()} := " return name + if (isDefault() || value() != null) { toGoValue(c, derived, parentConstrName) } else if (isAnonymous()) { type().toGoInstance(c, derived, derived, parentConstrName) } else { name() } } fun TypeI<*>.toGoCall(c: GenerationContext, api: String): String = c.n(this, api).substringAfterLast(".") fun <T : AttributeI<*>> T.toGoDefault(c: GenerationContext, derived: String, parentConstrName: String = ""): String = isNullable().ifElse({ "nil" }, { type().toGoDefault(c, derived, this, parentConstrName) }) fun <T : AttributeI<*>> T.toGoValue(c: GenerationContext, derived: String, parentConstrName: String = ""): String { return if (value() != null) { when (type()) { n.String, n.Text -> "\"${value()}\"" n.Boolean, n.Int, n.Long, n.Float, n.Date, n.Path, n.Blob, n.Void -> "${value()}" else -> { if (value() is LiteralI<*>) { val lit = value() as LiteralI<*> lit.toGoValue(c, derived) } else { "${value()}" } } } } else { toGoDefault(c, derived, parentConstrName) } } fun AttributeI<*>.toGoInitForConstructor(c: GenerationContext, derived: String): String { val name = "${isAnonymous().ifElse({ type().toGoCall(c, derived) }, { nameForGoMember() })}: " return name + if (isDefault() || value() != null) { toGoValue(c, derived) } else if (isAnonymous()) { type().toGoInstance(c, derived, derived) } else { name() } } fun AttributeI<*>.toGoInitForConstructorEnum(c: GenerationContext, derived: String): String { val name = "${isAnonymous().ifElse({ type().toGoCall(c, derived) }, { nameForGoMember().decapitalize() })}: " return name + if (isDefault() || value() != null) { toGoValue(c, derived) } else if (isAnonymous()) { type().toGoInstance(c, derived, derived) } else { name() } } fun AttributeI<*>.toGoInitForConstructorFunc(c: GenerationContext, derived: String): String = "${isAnonymous().ifElse({ type().toGoCall(c, derived) }, { nameForGoMember() })}: ${name().decapitalize()}" fun <T : AttributeI<*>> T.toGoTypeDef(c: GenerationContext, api: String): String = "${type().toGo(c, api)}${toGoMacrosAfterBody(c, api, api)}" fun <T : TypeI<*>> T.toGoDefault( c: GenerationContext, derived: String, attr: AttributeI<*>, parentConstrName: String = "" ): String { val baseType = findDerivedOrThis() return when (baseType) { n.String, n.Text -> "\"\"" n.Boolean -> "false" n.Int -> "0" n.Long -> "0L" n.Float -> "0f" n.Date -> g.time.Now.toGoCall(c, derived, derived) n.Path -> "${c.n(j.nio.file.Paths)}.get(\"\")" n.Blob -> "ByteArray(0)" n.Void -> "" n.Error -> "Throwable()" n.Exception -> "Exception()" n.Url -> "${c.n(j.net.URL)}(\"\")" n.Map -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("hashMapOf()", "emptyMap()") n.List -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("arrayListOf()", "arrayListOf()") else -> { if (baseType is LiteralI) { baseType.toGoValue(c, derived) } else if (baseType is EnumTypeI) { "${c.n(this, derived)}.${baseType.literals().first().toGoValue(c, derived)}" } else if (baseType is TypeI<*>) { toGoInstance(c, derived, derived, parentConstrName) } else { (this.parent() == n).ifElse("\"\"", { "${c.n(this, derived)}.EMPTY" }) } } } } fun <T : LogicUnitI<*>> T.toGoCallValueByPropName( c: GenerationContext, derived: String, api: String, saltIntName: String, parentConstrName: String = "" ): String = if (isNotEMPTY()) { val logicUnitName = c.n(this, derived) """$logicUnitName(${ params().nonDefaultAndNonDerived() .toGoCallValueByPropName(c, api, saltIntName, parentConstrName) })""" } else "" fun List<AttributeI<*>>.toGoCallValueByPropName( c: GenerationContext, api: String, saltIntName: String, parentConstrName: String = "" ): String = joinWrappedToString(", ", " ") { it.toGoValueByPropName(c, api, saltIntName, parentConstrName) } fun <T : AttributeI<*>> T.toGoValueByPropName( c: GenerationContext, derived: String, saltIntName: String, parentConstrName: String = "" ): String { val baseType = type().findDerivedOrThis() val ret = when (baseType) { n.String, n.Text, n.Any -> "${c.n(g.fmt.Sprintf)}(\"${name().capitalize()} %v\", $saltIntName)" n.Boolean -> "false" n.Byte -> saltIntName n.Int -> saltIntName n.Long -> saltIntName n.Short -> saltIntName n.UShort -> "ushort($saltIntName)" n.UInt -> "uint32($saltIntName)" n.ULong -> "uint64($saltIntName)" n.Float -> "float32($saltIntName)" n.Double -> "float64($saltIntName)" n.Date -> "${c.n(g.gee.PtrTime)}(${g.time.Now.toGoCall(c, derived, derived)})" n.Path -> "\"/\"" n.Blob -> "[]byte(${c.n(g.fmt.Sprintf)}(\"${name().capitalize()} %v\", $saltIntName))" n.Void -> "" n.Error -> "nil" n.Exception -> "nil" n.Url -> "${c.n(j.net.URL)}(\"\")" n.UUID -> g.google.uuid.New.toGoCall(c, derived, derived) n.Map -> "make(map[${type().generics()[0].toGo(c, derived)}]${type().generics()[1].toGo(c, derived)})" n.List -> "[]${type().generics().first().type().toGo(c, derived)}{}" else -> { if (baseType is LiteralI) { baseType.toGoValue(c, derived) } else if (baseType is EnumTypeI) { baseType.literals().first().toGoValue(c, derived) } else if (baseType is TypeI<*>) { type().findByNameOrPrimaryOrFirstConstructorFull(parentConstrName) .toGoCallValueByPropName(c, derived, derived, saltIntName, parentConstrName) } else { (this.parent() == n).ifElse("\"\"", { "${c.n(this, derived)}.EMPTY" }) } } } return ret } //"${(baseType.findParent(EnumTypeI::class.java) as EnumTypeI<*>).toGo(c, derived)}s().${baseType.toGo()}()" fun <T : LiteralI<*>> T.toGoValue(c: GenerationContext, derived: String): String = "${(findParentMust(EnumTypeI::class.java).toGoCall(c, derived))}s().${toGo()}()" fun <T : TypeI<*>> T.toGoIfNative(c: GenerationContext, derived: String): String? { val baseType = findDerivedOrThis() return when (baseType) { n.String, n.Path, n.Text -> "string" n.Boolean -> "bool" n.Int, n.Long -> "int" n.UShort -> "ushort" n.UInt -> "uint32" n.ULong -> "uint64" n.Float -> "float32" n.Double -> "float64" n.Date -> g.time.Time.toGo(c, derived) n.TimeUnit -> g.time.Time.toGo(c, derived) n.Blob -> "[]byte" n.Exception, n.Error -> "error" n.Void -> "" n.Any -> "interface{}" n.Url -> c.n(j.net.URL) n.UUID -> c.n(g.google.uuid.UUID) n.List -> "[]${generics()[0].toGo(c, derived)}" n.Map -> "map[${generics()[0].toGo(c, derived)}]${generics()[1].toGo(c, derived)}" else -> { if (this is LambdaI<*>) operation().toGoLambda(c, derived) else null } } } fun <T : TypeI<*>> T.toGoNilOrEmpty(c: GenerationContext): String? { val baseType = findDerivedOrThis() return when (baseType) { n.String, n.UUID -> "\"\"" else -> { "nil" } } } fun GenericI<*>.toGo(c: GenerationContext, derived: String): String = type().toGo(c, derived) fun <T : TypeI<*>> T.toGo(c: GenerationContext, derived: String): String = toGoIfNative(c, derived) ?: "${(isIfc()).not().then("*")}${c.n(this, derived)}" fun OperationI<*>.toGoIfc(c: GenerationContext, api: String = LangDerivedKind.API): String { return """ ${name().capitalize()}(${params().toGoSignature(c, api)}) ${toGoReturns(c, api)}""" } fun List<AttributeI<*>>.toGoSignature(c: GenerationContext, api: String): String = joinWrappedToString(", ") { it.toGoSignature(c, api) } fun <T : AttributeI<*>> T.toGoSignatureExplodeAnonymous(c: GenerationContext, api: String): String = isAnonymous().ifElse({ type().props().filter { !it.isMeta() }.toGoSignature(c, api) }, { "${name()} ${toGoTypeDef(c, api)}" }) fun <T : AttributeI<*>> T.toGoSignature(c: GenerationContext, api: String): String = "${name()} ${toGoTypeDef(c, api)}" fun <T : AttributeI<*>> T.toGoCallExplodeAnonymous(c: GenerationContext, api: String): String = isAnonymous().ifElse({ type().props().filter { !it.isMeta() }.toGoCall(c, api) }, { name() }) fun <T : AttributeI<*>> T.toGoCall(c: GenerationContext, api: String): String = name() fun <T : AttributeI<*>> T.toGoMember(c: GenerationContext, api: String): String = isAnonymous().ifElse({ " ${toGoTypeDef(c, api)}" }, { " ${nameForGoMember()} ${toGoTypeDef(c, api)}" }) fun <T : AttributeI<*>> T.toGoJsonTags(): String { val replaceable = isReplaceable() return (replaceable != null && !replaceable).ifElse({ "" }, { """ `json:"${externalName() ?: name().decapitalize()},omitempty" eh:"optional"`""" }) } fun <T : AttributeI<*>> T.toGoEnumMember(c: GenerationContext, api: String): String = isAnonymous().ifElse({ " ${toGoTypeDef(c, api)}" }, { " ${nameDecapitalize()} ${toGoTypeDef(c, api)}" }) fun OperationI<*>.toGoReturns(c: GenerationContext, api: String = LangDerivedKind.API): String = if (returns().isNotEmpty()) { if (isErr()) { returns().joinSurroundIfNotEmptyToString(", ", "(", ", err error)") { it.toGoSignature(c, api) } } else { returns().joinSurroundIfNotEmptyToString(", ", "(", ")") { it.toGoSignature(c, api) } } } else { if (isErr()) "(err error)" else "" } fun List<AttributeI<*>>.toGoCall(c: GenerationContext, api: String): String = joinWrappedToString(", ") { it.toGoCall(c, api) } fun <T : ConstructorI<*>> T.toGo(c: GenerationContext, derived: String, api: String): String { val type = findParentMust(CompilationUnitI::class.java) val name = c.n(type, derived) return if (isNotEMPTY()) """${toGoMacrosBefore(c, derived, api)} func ${c.n(this, derived)}(${ params().nonDefaultAndNonDerived().joinWrappedToString( ", ", " " ) { it.toGoSignature(c, api) } }) (ret *$name${isErrorHandling().then(", err error")}) {${toGoMacrosBeforeBody(c, derived, api)}${ macrosBody().isNotEmpty().ifElse({ """ ${toGoMacrosBody(c, derived, api)}""" }, { """${ params().defaultAndValueOrInit().joinSurroundIfNotEmptyToString("") { """ ${it.toGoInitVariables(c, derived, name())}""" } } ret = &$name{${ paramsForType().joinSurroundIfNotEmptyToString( ",$nL ", "$nL ", ",$nL " ) { it.toGoInitForConstructorFunc(c, derived) } }}""" }) }${toGoMacrosAfterBody(c, derived, api)} return }${toGoMacrosAfter(c, derived, api)}""" else "" } fun <T : AttributeI<*>> T.toGoAssign(o: String): String = "$o.${isMutable().setAndTrue().ifElse({ name().capitalize() }, { name().decapitalize() })} = ${name()}" fun <T : LogicUnitI<*>> T.toGoCall(c: GenerationContext, derived: String, api: String): String = if (isNotEMPTY()) """${c.n(this, derived)}(${ params().nonDefaultAndNonDerived().toGoCall( c, api ) })""" else "" fun <T : TypeI<*>> T.toGoInstance( c: GenerationContext, derived: String, api: String, parentConstrName: String = "" ): String { val constructor = findByNameOrPrimaryOrFirstConstructorFull(parentConstrName) return if (constructor.isNotEMPTY()) { constructor.toGoCall(c, derived, api) } else { "&${c.n(this, derived)}{}" } } fun <T : AttributeI<*>> T.toGoType(c: GenerationContext, derived: String): String = type().toGo(c, derived) fun List<AttributeI<*>>.toGoTypes(c: GenerationContext, derived: String): String = joinWrappedToString(", ") { it.toGoType(c, derived) } fun <T : OperationI<*>> T.toGoLambda(c: GenerationContext, derived: String): String = """func (${params().toGoTypes(c, derived)}) ${toGoReturns(c, derived)}""" fun <T : LogicUnitI<*>> T.toGoName(): String = isVisible().ifElse({ name().capitalize() }, { name().decapitalize() }) fun <T : OperationI<*>> T.toGoImpl(o: String, c: GenerationContext, api: String): String { return hasMacros().then { """${toGoMacrosBefore(c, api, api)} func (o *$o) ${toGoName()}(${params().toGoSignature(c, api)}) ${toGoReturns(c, api)}{${ toGoMacrosBeforeBody( c, api, api ) }${toGoMacrosBody(c, api, api)}${toGoMacrosAfterBody(c, api, api)}${ (returns().isNotEmpty() || isErr()).then { """ return""" } } }${toGoMacrosAfter(c, api, api)}""" } } fun CompilationUnitI<*>.toGoPropAnonymousInit( c: GenerationContext, derived: String, api: String, prefix: String ="", ) = propsAnonymous().joinSurroundIfNotEmptyToString(", ", prefix = prefix) { prop -> "${prop.type().name()}: ${prop.type().primaryOrFirstConstructorOrFull().toGoCall(c, derived, api)}" }
apache-2.0
593d3951df8d3cb2a425ebaa2bb226a5
38.461538
117
0.572422
3.585508
false
false
false
false
eugeis/ee
ee-design_gen/src/main/kotlin/ee/design/d.kt
1
8488
package ee.design import ee.lang.* object d : StructureUnit({ artifact("ee-design").namespace("ee.design").name("Design") }) { object Model : CompilationUnit({ superUnit(l.StructureUnit) }) { val models = prop(Model).multi(true) val comps = prop(Comp).multi(true) } object Bundle : CompilationUnit({ superUnit(l.StructureUnit) }) { val units = prop(l.StructureUnit).multi(true) } object Module : CompilationUnit({ superUnit(l.StructureUnit) }) { val parentNamespace = prop(n.Boolean).value(false) val dependencies = prop(Module).multi(true) val entities = prop(Entity).multi(true).nonFluent("entity") val enums = prop(l.EnumType).multi(true).nonFluent("enumType") val values = prop(l.Values).multi(true).nonFluent("valueType") val basics = prop(l.Basic).multi(true).nonFluent("basic") val controllers = prop(BusinessController).multi(true).nonFluent("controller") val sagas = prop(Saga).multi(true).nonFluent("saga") val projectors = prop(Projector).multi(true).nonFluent("projector") } object ModuleGroup : CompilationUnit({ superUnit(l.StructureUnit) }) { val modules = prop(Module).multi(true) } object Comp : CompilationUnit({ superUnit(ModuleGroup) }) { val moduleGroups = prop(ModuleGroup).multi(true) } object Event : CompilationUnit({ superUnit(l.DataType) }) {} object BusinessEvent : CompilationUnit({ superUnit(Event) }) object Facet : CompilationUnit({ superUnit(ModuleGroup) }) object ExternalModule : CompilationUnit({ superUnit(Module) }) { val externalTypes = prop(l.ExternalType).multi(true) } object Controller : CompilationUnit({ superUnit(l.CompilationUnit) }) { val enums = prop(l.EnumType).multi(true).nonFluent("enumType") .doc("Enums used special for controller needs, like CommandTypeEnums") val values = prop(l.Values).multi(true).nonFluent("valueType").doc("Values used special for controller needs") val basics = prop(l.Basic).multi(true).nonFluent("basic").doc("Basics used special for controller needs") } object BusinessController : CompilationUnit({ superUnit(Controller) }) object Command : CompilationUnit({ superUnit(l.DataType) }) { val httpMethod = propS() val affectMulti = prop(n.Boolean).value(false) val event = prop(Event).doc("Default target/to be produced event") } object StateMachine : CompilationUnit({ superUnit(Controller) }) { val defaultState = prop(State) val stateProp = prop(l.Attribute) val timeoutProp = prop(l.Attribute) val timeout = propL() val states = prop(State).multi(true).nonFluent("state") val checks = prop(l.Predicate).multi(true).nonFluent("check") val controllers = prop(BusinessController).multi(true).nonFluent("controller") } object Saga : CompilationUnit({ superUnit(StateMachine) }) {} object Projector : CompilationUnit({ superUnit(StateMachine) }) {} object AggregateHandler : CompilationUnit({ superUnit(StateMachine) }) {} object State : CompilationUnit({ superUnit(Controller) }) { val timeout = propL() val entryActions = prop(l.Action).multi(true).nonFluent("entry") val exitActions = prop(l.Action).multi(true).nonFluent("exit") val executors = prop(Executor).multi(true).nonFluent("execute") val handlers = prop(Handler).multi(true).nonFluent("handle") val controllers = prop(BusinessController).multi(true).nonFluent("controller") } object DynamicState : CompilationUnit({ superUnit(State) }) { val ifTrue = prop(l.Predicate).multi(true).nonFluent("ifT") val ifFalse = prop(l.Predicate).multi(true).nonFluent("ifF") } object Executor : CompilationUnit({ superUnit(l.LogicUnit) }) { val on = prop(Command) val ifTrue = prop(l.Predicate).multi(true).nonFluent("ifT") val ifFalse = prop(l.Predicate).multi(true).nonFluent("ifF") val actions = prop(l.Action).multi(true).nonFluent("action") val output = prop(Event).multi(true).nonFluent("produce") } object Handler : CompilationUnit({ superUnit(l.LogicUnit) }) { val on = prop(Event) val ifTrue = prop(l.Predicate).multi(true).nonFluent("ifT") val ifFalse = prop(l.Predicate).multi(true).nonFluent("ifF") val to = prop(State) val actions = prop(l.Action).multi(true).nonFluent("action") val output = prop(Command).multi(true).nonFluent("produce") } object BusinessCommand : CompilationUnit({ superUnit(Command) }) object CompositeCommand : CompilationUnit({ superUnit(l.CompilationUnit) }) { val commands = prop(Command).multi(true) } object FindBy : CompilationUnit({ superUnit(l.DataTypeOperation) }) { val multiResult = prop(n.Boolean).value(true) } object CountBy : CompilationUnit({ superUnit(l.DataTypeOperation) }) object ExistBy : CompilationUnit({ superUnit(l.DataTypeOperation) }) object CreateBy : CompilationUnit({ superUnit(Command) }) object DeleteBy : CompilationUnit({ superUnit(Command) }) object UpdateBy : CompilationUnit({ superUnit(Command) }) object ChildCommandBy : CompilationUnit({ superUnit(Command) }) { val type = prop(l.Type) val child = prop(l.Attribute) } object AddChildBy : CompilationUnit({ superUnit(ChildCommandBy) }) object UpdateChildBy : CompilationUnit({ superUnit(ChildCommandBy) }) object RemoveChildBy : CompilationUnit({ superUnit(ChildCommandBy) }) object Created : CompilationUnit({ superUnit(Event) }) object Deleted : CompilationUnit({ superUnit(Event) }) object Updated : CompilationUnit({ superUnit(Event) }) object ChildEvent : CompilationUnit({ superUnit(Event) }) { val type = prop(l.Type) val child = prop(l.Attribute) } object ChildAdded : CompilationUnit({ superUnit(ChildEvent) }) object ChildUpdated : CompilationUnit({ superUnit(ChildEvent) }) object ChildRemoved : CompilationUnit({ superUnit(ChildEvent) }) object Entity : CompilationUnit({ superUnit(l.DataType) }) { val defaultEvents = propB().value(true) val defaultQueries = propB().value(true) val defaultCommands = propB().value(true) val belongsToAggregate = prop(Entity) val aggregateFor = prop(Entity).multi(true) val controllers = prop(BusinessController).multi(true).nonFluent("controller") val findBys = prop(FindBy).multi(true).nonFluent("findBy") val countBys = prop(CountBy).multi(true).nonFluent("countBy") val existBys = prop(ExistBy).multi(true).nonFluent("existBy") val commands = prop(BusinessCommand).multi(true).nonFluent("command") val composites = prop(CompositeCommand).multi(true).nonFluent("composite") val createBys = prop(CreateBy).multi(true).nonFluent("createBy") val updateBys = prop(UpdateBy).multi(true).nonFluent("updateBy") val deleteBys = prop(DeleteBy).multi(true).nonFluent("deleteBy") val addChildBys = prop(AddChildBy).multi(true).nonFluent("addChildBy") val updateChildBys = prop(UpdateChildBy).multi(true).nonFluent("updateChildBy") val removeChildBys = prop(RemoveChildBy).multi(true).nonFluent("removeChildBy") val events = prop(BusinessEvent).multi(true).nonFluent("event") val created = prop(Created).multi(true).nonFluent("created") val updated = prop(Updated).multi(true).nonFluent("updated") val deleted = prop(Deleted).multi(true).nonFluent("deleted") val childAdded = prop(ChildAdded).multi(true).nonFluent("childAdded") val childUpdated = prop(ChildUpdated).multi(true).nonFluent("childUpdated") val childRemoved = prop(ChildRemoved).multi(true).nonFluent("childRemoved") val checks = prop(l.Predicate).multi(true).nonFluent("check") val handlers = prop(AggregateHandler).multi(true).nonFluent("handler") val projectors = prop(Projector).multi(true).nonFluent("projector") val saga = prop(Saga).multi(true).nonFluent("saga") } object Config : CompilationUnit({ superUnit(l.Values) }) { val prefix = propS { doc("Prefix of all properties in global configuration") } } object Widget : CompilationUnit({ superUnit(l.CompilationUnit) }) }
apache-2.0
df2b0b71adf0ab26747b898c0d750a59
42.757732
118
0.674953
4.237644
false
false
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/bookmarks/dialogs/AddBookmarkDialog.kt
1
1785
package de.ph1b.audiobook.features.bookmarks.dialogs import android.app.Dialog import android.os.Bundle import android.text.InputType import android.view.inputmethod.EditorInfo import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.bluelinelabs.conductor.Controller import de.ph1b.audiobook.R import de.ph1b.audiobook.common.conductor.DialogController class AddBookmarkDialog : DialogController() { override fun onCreateDialog(savedViewState: Bundle?): Dialog { val inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT val dialog = MaterialDialog(activity!!).apply { title(R.string.bookmark) @Suppress("CheckResult") input(hintRes = R.string.bookmark_edit_hint, allowEmpty = true, inputType = inputType) { _, charSequence -> val title = charSequence.toString() val callback = targetController as Callback callback.onBookmarkNameChosen(title) } positiveButton(R.string.dialog_confirm) } val editText = dialog.getInputField() editText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val title = editText.text.toString() val callback = targetController as Callback callback.onBookmarkNameChosen(title) dismissDialog() true } else false } return dialog } interface Callback { fun onBookmarkNameChosen(name: String) } companion object { operator fun <T> invoke(target: T) where T : Controller, T : Callback = AddBookmarkDialog().apply { targetController = target } } }
lgpl-3.0
dc903cf40bd62faff87a3fe3e93f56be
32.055556
113
0.721569
4.530457
false
false
false
false
fabmax/calculator
app/src/main/kotlin/de/fabmax/calc/animFont/AnimateableChar.kt
1
26330
package de.fabmax.calc.animFont import android.util.Log import de.fabmax.lightgl.util.* import java.util.* /** * Animateable character in the style of the Google I/O 2015 web countdown. Not all characters are * supported (but all those needed for the math functions). */ open class AnimateableChar { val name: String protected val mPath: FloatArray protected val mStepLens: FloatArray protected var mIsStatic = true private var mMesh: MeshData? = null protected var mPathLength: Float = 0.toFloat() open var charAdvance: Float = 0.toFloat() protected set private val mTmpVert = FloatArray(3) protected constructor(name: String, nVerts: Int) { mPath = FloatArray(nVerts * 3) mStepLens = FloatArray(nVerts) mPathLength = 0f charAdvance = 0f this.name = name } constructor(name: String, pathDef: FloatList, charWidth: Float) { mPath = pathDef.asArray() mStepLens = FloatArray(mPath.size / 3) charAdvance = charWidth this.name = name updatePathLength() } protected fun updatePathLength() { mPathLength = 0f var x0 = mPath[0] var y0 = mPath[1] var z0 = mPath[2] var i = 3 var j = 0 while (i < mPath.size) { val x1 = mPath[i] val y1 = mPath[i + 1] val z1 = mPath[i + 2] mStepLens[j] = Math.sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1) + (z0 - z1) * (z0 - z1).toDouble()).toFloat() mPathLength += mStepLens[j] x0 = x1 y0 = y1 z0 = z1 i += 3 j++ } } fun draw(painter: Painter) { if (mIsStatic && mMesh != null && !mMesh!!.isEmpty) { painter.drawMeshData(mMesh) } else { if (mMesh == null) { painter.commit() } var i = 0 while (i < mPath.size - 3) { painter.drawLine(mPath[i], mPath[i + 1], mPath[i + 3], mPath[i + 4]) i += 3 } if (mMesh == null) { mMesh = painter.meshBuilder.build() } } } fun draw(painter: Painter, defaultColor: Color, offset: Float, secLen: Float, secColors: Array<Color>) { var color = defaultColor var remaining = offset var secIdx = -1 // determine section (color) to start with for (i in secColors.indices) { val l = offset + secLen * (i + 1) if (l > 1) { secIdx = i color = secColors[secIdx] remaining = l - 1 break } } var firstSi = secIdx remaining *= mPathLength mTmpVert[0] = mPath[0] mTmpVert[1] = mPath[1] mTmpVert[2] = mPath[2] // draw path by sections with varying colors painter.setColor(color) var stepLen = mStepLens[0] //target.addVertex(path[0], path[1], path[2], color) var i = 3 while (i < mPath.size) { if (remaining < stepLen) { // section (color) change color = defaultColor var nextLen = mPathLength secIdx++ if (secIdx >= secColors.size && firstSi != -1) { // section overflow (we did not start with the first section) firstSi = -1 secIdx = -1 nextLen = (1 - secColors.size * secLen) * mPathLength } else if (secIdx < secColors.size) { // select next section color = secColors[secIdx] nextLen = secLen * mPathLength } // insert a vertex at the exact section end position split(painter, mTmpVert, i, remaining / stepLen) painter.setColor(color) // compute remaining length of this step val dx = mPath[i] - mTmpVert[0] val dy = mPath[i + 1] - mTmpVert[1] val dz = mPath[i + 2] - mTmpVert[2] stepLen = Math.sqrt(dx * dx + dy * dy + dz * dz.toDouble()).toFloat() // set next section values remaining = nextLen // we inserted a vertex, next path vertex remains the same i -= 3 } else { // extend path with current color //target.extendLine(path[i], path[i + 1], path[i + 2], color) painter.drawLine(mTmpVert[0], mTmpVert[1], mPath[i], mPath[i+1]) mTmpVert[0] = mPath[i] mTmpVert[1] = mPath[i + 1] mTmpVert[2] = mPath[i + 2] remaining -= stepLen stepLen = mStepLens[i / 3] } i += 3 } } fun blend(other: AnimateableChar, weight: Float, target: MutableChar) { val w = weight val trgt: AnimateableChar = target if (w > 0.9999f) { target.setPath(this) target.setCharWidth(charAdvance) } else if (weight < 0.0001f) { target.setPath(other) target.setCharWidth(other.charAdvance) } else { for (i in mPath.indices) { trgt.mPath[i] = mPath[i] * w + other.mPath[i] * (1 - w) } target.setCharWidth(charAdvance * w + other.charAdvance * (1 - w)) } trgt.updatePathLength() } private fun split(painter: Painter, vert: FloatArray, iNext: Int, pos: Float) { var p = pos if (p < 0 || p > 1) { System.err.println(p) } p = GlMath.clamp(p, 0f, 1f) val x0 = vert[0] val y0 = vert[1] val z0 = vert[2] val x2 = mPath[iNext] val y2 = mPath[iNext + 1] val z2 = mPath[iNext + 2] vert[0] = x0 * (1 - p) + x2 * p vert[1] = y0 * (1 - p) + y2 * p vert[2] = z0 * (1 - p) + z2 * p painter.drawLine(x0, y0, vert[0], vert[1]) } companion object { val N_VERTS = 60 val NULL_CHAR = makeNull(0f) val TIMES = '\u00D7' val DIVISION = '\u00F7' val SQRT = '\u221A' val PI = '\u03C0' private val CHARS = object : HashMap<Char, AnimateableChar>() { init { put(' ', makeNull(1f)) put('0', make0()) put('1', make1()) put('2', make2()) put('3', make3()) put('4', make4()) put('5', make5()) put('6', make6()) put('7', make7()) put('8', make8()) put('9', make9()) put('.', makeComma()) put(',', makeComma()) put('+', makePlus()) put('-', makeMinus()) put(TIMES, makeTimes()) put(DIVISION, makeSlash()) put('/', makeSlash()) put('^', makePow()) put('(', makeParenOpen()) put(')', makeParenClose()) put('a', make_a()) put('c', makeC(true)) put('e', make_e()) put('g', make_g()) put('i', makeI(true)) put('l', make_l()) put('n', make_n()) put('o', makeO(true)) put('r', make_r()) put('s', makeS(true)) put('t', make_t()) put(PI, makePi()) put(SQRT, makeSqrt()) } } fun getChar(c: Char): AnimateableChar { val key = c if (CHARS.containsKey(key)) { return CHARS[c]!! } else { Log.e("AnimChar", "Char not mapped: " + c) return NULL_CHAR } } private fun makeNull(width: Float): AnimateableChar { val coords = FloatList() for (i in 0..N_VERTS * 3 - 1) { coords.add(0f) } return AnimateableChar("null", coords, width) } private fun make0(): AnimateableChar { val coords = FloatList() sweep(coords, 0f, 0f, 1f, -90.0, 360.0, N_VERTS) return AnimateableChar("0", coords, 2.2f) } private fun make1(): AnimateableChar { val coords = FloatList() line(coords, -.2f, -1f, .2f, -1f, N_VERTS / 6) line(coords, .2f, -1f, .2f, 1f, N_VERTS / 3) line(coords, .2f, 1f, -.2f, 1f, N_VERTS / 3) line(coords, -.2f, 1f, -.2f, -1f, N_VERTS / 6) return AnimateableChar("1", coords, 2.2f) } private fun make2(): AnimateableChar { val coords = FloatList() line(coords, 0f, -1f, .6f, -1f, 4) line(coords, .6f, -1f, .4f, -.8f, 2) line(coords, .4f, -.8f, -.6f, -.8f, 8) sweep(coords, -0.12f, 0.48f, .52f, -35.0, 190.0, N_VERTS / 2 - 9) sweep(coords, 0.08f, 0.28f, .52f, 155.0, -190.0, N_VERTS / 2 - 9) line(coords, -.4f, -1f, -0f, -1f, 4) return AnimateableChar("2", coords, 2.2f) } private fun make3(): AnimateableChar { val coords = FloatList() sweep(coords, -0.12f, -0.3f, .5f, -160.0, 225.0, N_VERTS / 4) sweep(coords, -0.12f, 0.55f, .45f, -55.0, 225.0, N_VERTS / 4) sweep(coords, 0.08f, 0.35f, .45f, 170.0, -225.0, N_VERTS / 4) sweep(coords, 0.08f, -0.5f, .5f, 65.0, -225.0, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("3", coords, 2.2f) } private fun make4(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -.7f, .65f, -.7f, N_VERTS / 6) line(coords, .45f, -.5f, -.6f, -.5f, N_VERTS / 6) line(coords, -.6f, -.35f, .1f, 1f, N_VERTS / 6) line(coords, .3f, 1f, .3f, -.8f, N_VERTS / 6) line(coords, .5f, -1f, .5f, .8f, N_VERTS / 6) line(coords, .3f, .8f, -.4f, -.55f, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("4", coords, 2.2f) } private fun make5(): AnimateableChar { val coords = FloatList() sweep(coords, -0.12f, -0.25f, .55f, -160.0, 300.0, N_VERTS / 4) line(coords, -.3f, 1f, .4f, 1f, N_VERTS / 4) line(coords, .6f, .8f, -.1f, .8f, N_VERTS / 4) sweep(coords, 0.08f, -0.45f, .55f, 140.0, -300.0, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("5", coords, 2.2f) } private fun make6(): AnimateableChar { val coords = FloatList() sweep(coords, 0.1f, -0.45f, .55f, -210.0, 310.0, N_VERTS / 2 - 5) sweep(coords, -0.1f, -0.25f, .55f, 100.0, -310.0, N_VERTS / 2 - 5) line(coords, .15f, 1f, .35f, .8f, 9) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("6", coords, 2.2f) } private fun make7(): AnimateableChar { val coords = FloatList() line(coords, .0f, -1f, .6f, .65f, N_VERTS / 4) line(coords, .6f, .8f, -.4f, .8f, N_VERTS / 4) line(coords, -.6f, 1f, .4f, 1f, N_VERTS / 4) line(coords, .4f, .85f, -.2f, -.8f, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("7", coords, 2.2f) } private fun make8(): AnimateableChar { val coords = FloatList() sweep(coords, 0f, -0.4f, .58f, 125.0, 290.0, N_VERTS / 2) sweep(coords, 0f, 0.48f, .52f, -45.0, 270.0, N_VERTS / 2 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("8", coords, 2.2f) } private fun make9(): AnimateableChar { val coords = FloatList() line(coords, -.15f, -1f, -.35f, -.8f, 9) sweep(coords, -0.1f, 0.45f, .55f, -30.0, 310.0, N_VERTS / 2 - 5) sweep(coords, 0.1f, 0.25f, .55f, -80.0, -310.0, N_VERTS / 2 - 5) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("9", coords, 2.2f) } private fun makeComma(): AnimateableChar { val coords = FloatList() line(coords, 0f, -.9f, 0f, -1f, 2) line(coords, 0f, -1f, .15f, -1.2f, 2) return AnimateableChar(",", coords, 0f) } private fun makePlus(): AnimateableChar { val coords = FloatList() line(coords, -.1f, -.4f, .1f, -.6f, N_VERTS / 5) line(coords, .1f, -.1f, .6f, -.1f, N_VERTS / 5) line(coords, .4f, .1f, -.6f, .1f, N_VERTS / 5) line(coords, -.4f, -.1f, .1f, -.1f, N_VERTS / 5) line(coords, .1f, .4f, -.1f, .6f, N_VERTS / 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("+", coords, 1.5f) } private fun makeMinus(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -.1f, .6f, -.1f, N_VERTS / 2) line(coords, .4f, .1f, -.6f, .1f, N_VERTS / 2 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("-", coords, 1.5f) } private fun makeTimes(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -.6f, 0f, -.2f, N_VERTS / 6) line(coords, .4f, -.6f, .6f, -.4f, N_VERTS / 6) line(coords, .2f, 0f, .6f, .4f, N_VERTS / 6) line(coords, .4f, .6f, 0f, .2f, N_VERTS / 6) line(coords, -.4f, .6f, -.6f, .4f, N_VERTS / 6) line(coords, -.2f, 0f, -.6f, -.4f, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) scale(coords, .8f) return AnimateableChar("*", coords, 1.5f) } private fun makeSlash(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -1f, .4f, 1f, N_VERTS) return AnimateableChar("/", coords, 1f) } private fun makePow(): AnimateableChar { val coords = FloatList() line(coords, -.25f, .3f, .15f, .8f, N_VERTS / 4) line(coords, .15f, .8f, .55f, .3f, N_VERTS / 4) line(coords, .3f, .5f, -.1f, 1f, N_VERTS / 4) line(coords, -.1f, 1f, -.5f, .5f, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("^", coords, 1.3f) } private fun makeParenOpen(): AnimateableChar { val coords = FloatList() sweep(coords, 1f, .1f, 1.28f, -135.0, -90.0, N_VERTS / 2) sweep(coords, 1.1f, -.1f, 1.28f, 135.0, 90.0, N_VERTS / 2 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar("(", coords, .85f) } private fun makeParenClose(): AnimateableChar { val coords = FloatList() sweep(coords, -1f, -.1f, 1.28f, -45.0, 90.0, N_VERTS / 2) sweep(coords, -1.1f, .1f, 1.28f, 45.0, -90.0, N_VERTS / 2 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) return AnimateableChar(")", coords, .85f) } private fun makeS(small: Boolean): AnimateableChar { val coords = FloatList() line(coords, -.55f, -.8f, -.35f, -1f, N_VERTS / 6) sweep(coords, .1f, -.55f, .45f, -90.0, 180.0, N_VERTS / 6) sweep(coords, .1f, .35f, .45f, -90.0, -180.0, N_VERTS / 6) line(coords, .55f, .8f, .35f, 1f, N_VERTS / 6) sweep(coords, -.1f, .55f, .45f, 90.0, 180.0, N_VERTS / 6) sweep(coords, -.1f, -.35f, .45f, 90.0, -180.0, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 1.1f if (small) { transform(coords, .7f, -.3f) w *= 0.7f } return AnimateableChar("s", coords, w + 0.5f) } private fun makeI(small: Boolean): AnimateableChar { val coords = FloatList() line(coords, -.2f, -1f, .2f, -1f, N_VERTS / 6) line(coords, .2f, -1f, .2f, 1f, N_VERTS / 3) line(coords, .2f, 1f, -.2f, 1f, N_VERTS / 3) line(coords, -.2f, 1f, -.2f, -1f, N_VERTS / 6) var w = .4f if (small) { transform(coords, .7f, -.3f) w *= 0.7f } return AnimateableChar("i", coords, w + 0.5f) } private fun make_n(): AnimateableChar { val coords = FloatList() line(coords, -.65f, -.8f, -.45f, -1f, N_VERTS / 4) sweep(coords, .1f, .25f, .55f, 180.0, -180.0, N_VERTS / 4) line(coords, .65f, -1f, .45f, -.8f, N_VERTS / 4) sweep(coords, -.1f, .45f, .55f, 0.0, 180.0, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 1.3f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("n", coords, w + 0.5f) } private fun makeC(small: Boolean): AnimateableChar { val coords = FloatList() line(coords, .6f, -1f, .4f, -.8f, N_VERTS / 6) sweep(coords, .1f, -.1f, .7f, -90.0, -90.0, N_VERTS / 6) sweep(coords, .1f, .3f, .7f, -180.0, -90.0, N_VERTS / 6) line(coords, .4f, 1f, .6f, .8f, N_VERTS / 6) sweep(coords, .3f, .1f, .7f, 90.0, 90.0, N_VERTS / 6) sweep(coords, .3f, -.3f, .7f, 180.0, 90.0, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 1f if (small) { transform(coords, .7f, -.3f) w *= 0.7f } return AnimateableChar("c", coords, w + 0.5f) } private fun makeO(small: Boolean): AnimateableChar { val coords = FloatList() sweep(coords, 0f, 0f, 1f, -90.0, 360.0, N_VERTS) var w = 2f if (small) { transform(coords, .7f, -.3f) w *= 0.7f } return AnimateableChar("o", coords, w + 0.25f) } private fun make_a(): AnimateableChar { val coords = FloatList() sweep(coords, -.1f, .1f, .9f, -45.0, -225.0, N_VERTS / 4) line(coords, .8f, 1f, .8f, -.8f, N_VERTS / 4) line(coords, 1f, -1f, 1f, .8f, N_VERTS / 4) sweep(coords, .1f, -.1f, .9f, 90.0, 225.0, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 2f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("a", coords, w + 0.25f) } private fun make_e(): AnimateableChar { val coords = FloatList() sweep(coords, 0f, -.05f, .75f, -48.0, -132.0, N_VERTS / 6) sweep(coords, -.1f, .35f, .65f, 180.0, -180.0, N_VERTS / 6) line(coords, .55f, .2f, -.6f, .2f, N_VERTS / 6) line(coords, -.4f, 0f, .75f, 0f, N_VERTS / 6) sweep(coords, .1f, .15f, .65f, 0.0, 180.0, N_VERTS / 6) sweep(coords, .2f, -.25f, .75f, -180.0, 132.0, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 1.3f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("e", coords, w + 0.25f) } private fun make_r(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -1f, -.4f, .3f, N_VERTS / 4) sweep(coords, .1f, .3f, .5f, -180.0, -180.0, N_VERTS / 4) sweep(coords, -.1f, .5f, .5f, 0.0, 180.0, N_VERTS / 4) line(coords, -.6f, .5f, -.6f, -.8f, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 1.3f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("r", coords, w + 0.25f) } private fun make_l(): AnimateableChar { val coords = FloatList() sweep(coords, .2f, -.3f, .5f, -90.0, -90.0, N_VERTS / 4) line(coords, -.3f, -.3f, -.3f, 1f, N_VERTS / 4) line(coords, -.1f, .8f, -.1f, -.5f, N_VERTS / 4) sweep(coords, .4f, -.5f, .5f, 180.0, 90.0, N_VERTS / 4 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) val w = .7f return AnimateableChar("l", coords, w + 0.25f) } private fun make_g(): AnimateableChar { val coords = FloatList() sweep(coords, -.1f, .1f, .9f, -45.0, -225.0, N_VERTS / 6) line(coords, .8f, 1f, .8f, -.8f, N_VERTS / 6) sweep(coords, -.1f, -1f, .9f, 0.0, -180.0, N_VERTS / 6) sweep(coords, .1f, -1.2f, .9f, 180.0, 180.0, N_VERTS / 6) line(coords, 1f, -1f, 1f, .8f, N_VERTS / 6) sweep(coords, .1f, -.1f, .9f, 90.0, 225.0, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 2f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("g", coords, w + 0.25f) } private fun make_t(): AnimateableChar { val coords = FloatList() sweep(coords, .6f, -.5f, .5f, 180.0, 90.0, N_VERTS / 6) sweep(coords, .4f, -.3f, .5f, -90.0, -90.0, N_VERTS / 6) line(coords, -.1f, .4f, -.6f, .4f, N_VERTS / 6) line(coords, -.4f, .2f, .6f, .2f, N_VERTS / 6) line(coords, .4f, .4f, -.1f, .4f, N_VERTS / 6) line(coords, -.1f, 1f, .1f, .8f, N_VERTS - N_VERTS / 6 * 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) val w = 1.2f return AnimateableChar("t", coords, w + 0.25f) } private fun makePi(): AnimateableChar { val coords = FloatList() line(coords, -.4f, -1f, -.6f, -.8f, N_VERTS / 8) line(coords, -.6f, 1f, .4f, 1f, N_VERTS / 8) line(coords, .4f, -.8f, .6f, -1f, N_VERTS / 8) line(coords, .6f, .8f, 1f, .8f, N_VERTS / 8) line(coords, .8f, 1f, .4f, 1f, N_VERTS / 8) line(coords, .6f, .8f, -.4f, .8f, N_VERTS / 8) line(coords, -.6f, 1f, -1f, 1f, N_VERTS / 8) line(coords, -.8f, .8f, -.4f, .8f, N_VERTS - N_VERTS / 8 * 7 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) var w = 2f transform(coords, .7f, -.3f) w *= 0.7f return AnimateableChar("pi", coords, w + 0.25f) } private fun makeSqrt(): AnimateableChar { val coords = FloatList() line(coords, 0f, -1f, .4f, .8f, N_VERTS / 5) line(coords, .8f, .8f, .6f, 1f, N_VERTS / 5) line(coords, .2f, 1f, -.2f, -.8f, N_VERTS / 5) line(coords, -.5f, 0f, -.8f, 0f, N_VERTS / 5) line(coords, -.6f, -.2f, -.3f, -.2f, N_VERTS / 5 - 1) coords.add(coords.get(0)) coords.add(coords.get(1)) coords.add(coords.get(2)) val w = 1.6f return AnimateableChar("sqrt", coords, w + 0.25f) } private fun scale(list: FloatList, fac: Float) { transform(list, fac, 0f) } private fun transform(list: FloatList, fac: Float, tY: Float) { var i = 0 while (i < list.size()) { list.set(i, list.get(i) * fac) list.set(i + 1, list.get(i + 1) * fac + tY) list.set(i + 2, list.get(i + 2) * fac) i += 3 } } private fun line(list: FloatList, x0: Float, y0: Float, x1: Float, y1: Float, n: Int) { for (i in 0..n - 1) { list.add(x0 + (x1 - x0) * i / (n - 1)) list.add(y0 + (y1 - y0) * i / (n - 1)) list.add(0f) } } private fun sweep(list: FloatList, cx: Float, cy: Float, r: Float, start: Double, sweep: Double, n: Int) { var startRad = start var sweepRad = sweep startRad = Math.toRadians(startRad) sweepRad = Math.toRadians(sweepRad) for (i in 0..n - 1) { val x = Math.cos(startRad + sweepRad * i / (n - 1)).toFloat() * r + cx val y = Math.sin(startRad + sweepRad * i / (n - 1)).toFloat() * r + cy list.add(x) list.add(y) list.add(0f) } } } }
apache-2.0
2bc0e5ab7d85e94089e3a72d5b5f8ca2
36.507123
128
0.463122
3.054879
false
false
false
false
AlmasB/FXGLGames
OutRun/src/main/kotlin/com/almasb/fxglgames/outrun/OutRunApp.kt
1
7425
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2016 AlmasB ([email protected]) * * 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.almasb.fxglgames.outrun import com.almasb.fxgl.animation.Interpolators import com.almasb.fxgl.app.GameApplication import com.almasb.fxgl.app.GameSettings import com.almasb.fxgl.dsl.* import com.almasb.fxgl.dsl.FXGL.Companion.centerTextBind import com.almasb.fxgl.dsl.FXGL.Companion.loopBGM import com.almasb.fxgl.dsl.components.Effect import com.almasb.fxgl.dsl.components.EffectComponent import com.almasb.fxgl.entity.Entity import com.almasb.fxgl.entity.level.text.TextLevelLoader import com.almasb.fxgl.ui.ProgressBar import com.almasb.fxglgames.outrun.EntityType.* import javafx.beans.property.SimpleIntegerProperty import javafx.geometry.Pos import javafx.scene.input.KeyCode import javafx.scene.layout.VBox import javafx.scene.paint.Color import javafx.scene.text.Text import javafx.util.Duration /** * An example racing game in FXGL. * * BGM music from https://freesound.org/people/FoolBoyMedia/sounds/244088/ * * @author Almas Baimagambetov ([email protected]) */ class OutRunApp : GameApplication() { override fun initSettings(settings: GameSettings) { with(settings) { width = 600 height = 800; title = "OutRun" version = "0.3.5" } } private lateinit var playerComponent: PlayerComponent override fun initInput() { onKey(KeyCode.W, "Boost") { playerComponent.boost() } onKey(KeyCode.A, "Move Left") { playerComponent.left() } onKey(KeyCode.D, "Move Right") { playerComponent.right() } } override fun initGameVars(vars: MutableMap<String, Any>) { vars["time"] = 0.0 } override fun onPreInit() { loopBGM("bgm.mp3") } override fun initGame() { getGameWorld().addEntityFactory(OutRunFactory()) val level = getAssetLoader().loadLevel("level0.txt", TextLevelLoader(40, 40, '0')) getGameWorld().setLevel(level) val player = spawn("player", getAppWidth() / 2 - 40.0, level.height.toDouble()) playerComponent = player.getComponent(PlayerComponent::class.java) spawn("enemy", getAppWidth() / 2 + 40.0, level.height.toDouble()) val bg = spawn("background") bg.yProperty().bind(getGameScene().viewport.yProperty()) getGameScene().viewport.setBounds(0, 0, 600, level.height) getGameScene().viewport.bindToEntity(player, getAppWidth() / 2.0, getAppHeight() - 80.0) } override fun initPhysics() { onCollisionBegin(PLAYER, OBSTACLE) { _, wall -> // reset player to last checkpoint playerComponent.reset() wall.getComponent(ObstacleComponent::class.java).hit() } onCollisionBegin(ENEMY, OBSTACLE) { enemy, wall -> // reset enemy to last checkpoint enemy.getComponent(EnemyComponent::class.java).reset() wall.getComponent(ObstacleComponent::class.java).hit() } onCollisionBegin(PLAYER, POWERUP) { player, boost -> boost.removeFromWorld() player.getComponent(EffectComponent::class.java).startEffect(object : Effect(Duration.seconds(1.0)) { override fun onStart(entity: Entity) { playerComponent.applyExtraBoost() } override fun onEnd(entity: Entity) { playerComponent.removeExtraBoost() } }) } onCollisionBegin(PLAYER, FINISH) { _, _ -> showMessage("Demo Over. Your Time: %.2f s\n".format(getd("time")) + "Thanks for playing!", FXGL.getGameController()::exit) } onCollisionBegin(PLAYER, ENEMY) { player, enemy -> player.translateX(-30.0) enemy.translateX(30.0) } } private lateinit var ui: Text override fun initUI() { val label = getUIFactoryService().newText("", 72.0) centerTextBind(label) val count = SimpleIntegerProperty(3) label.textProperty().bind(count.asString()) addUINode(label) animationBuilder() .duration(Duration.seconds(1.0)) .repeat(3) .interpolator(Interpolators.CIRCULAR.EASE_IN()) .fadeIn(label) .buildAndPlay() val timerAction = run({ count.set(count.get() - 1) }, Duration.seconds(1.0)) count.addListener { _, _, newValue -> if (newValue.toInt() == 0) { timerAction.expire() removeUINode(label) } } // BOOST val boostBar = ProgressBar(false); boostBar.setWidth(100.0) boostBar.setHeight(15.0) boostBar.setFill(Color.GREEN.brighter()) boostBar.setTraceFill(Color.GREEN.brighter()) boostBar.translateX = getAppWidth() - 200.0 boostBar.translateY = 25.0 boostBar.isLabelVisible = false boostBar.setMaxValue(100.0) boostBar.currentValueProperty().bind(playerComponent.boost) addUINode(boostBar) // UI text ui = getUIFactoryService().newText("", 16.0) ui.translateX = 50.0 ui.translateY = 50.0 addUINode(ui) } private var firstTime = true override fun onUpdate(tpf: Double) { if (firstTime) { val flow = getUIFactoryService().newTextFlow() flow.append("OutRun Demo\n", Color.WHITE) .append(KeyCode.W, Color.GREEN).append(" - Boost\n", Color.WHITE) .append(KeyCode.A, Color.GREEN).append(" - Move Left\n", Color.WHITE) .append(KeyCode.D, Color.GREEN).append(" - Move Right", Color.WHITE) val vbox = VBox(flow) vbox.translateX = 200.0 vbox.alignment = Pos.CENTER getDisplay().showBox("", vbox, getUIFactoryService().newButton("OK")) firstTime = false } else { ui.text = "Speed: %.2f".format(playerComponent.getSpeed()) } set("time", getd("time") + tpf) } } fun main(args: Array<String>) { GameApplication.launch(OutRunApp::class.java, args); }
mit
c1dbd527c583b5c277041564624c113d
31.427948
113
0.629495
4.17604
false
false
false
false
xfournet/intellij-community
plugins/stats-collector/src/com/intellij/plugin/Startup.kt
11
1880
/* * Copyright 2000-2017 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. */ package com.intellij.plugin import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity class NotificationManager : StartupActivity { companion object { private val PLUGIN_NAME = "Completion Stats Collector" private val MESSAGE_TEXT = "Data about your code completion usage will be anonymously reported. " + "No personal data or code will be sent." private val MESSAGE_SHOWN_KEY = "completion.stats.allow.message.shown" } private fun isMessageShown() = PropertiesComponent.getInstance().getBoolean(MESSAGE_SHOWN_KEY, false) private fun setMessageShown(value: Boolean) = PropertiesComponent.getInstance().setValue(MESSAGE_SHOWN_KEY, value) override fun runActivity(project: Project) { if (!isMessageShown()) { notify(project) setMessageShown(true) } } private fun notify(project: Project) { val notification = Notification(PLUGIN_NAME, PLUGIN_NAME, MESSAGE_TEXT, NotificationType.INFORMATION) notification.notify(project) } }
apache-2.0
6534adf0a828f59c85c79f4c9953f0dc
35.882353
118
0.717021
4.619165
false
false
false
false
google-developer-training/basic-android-kotlin-compose-training-sports
app/src/main/java/com/example/sports/ui/theme/Type.kt
1
1094
/* * Copyright (c) 2022 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 * * https://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.example.sports.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) )
apache-2.0
cbede4ca87a5aea8fd318c0dc72f9921
33.1875
75
0.745887
4.143939
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/view/ui/actors/RegularBar.kt
1
872
package ru.icarumbas.bagel.view.ui.actors import com.badlogic.gdx.scenes.scene2d.Actor open class RegularBar( private val barBackGround: Actor, private val bar: Actor, private val barForeground: Actor ) : Actor(){ override fun setPosition(x: Float, y: Float){ bar.setPosition(x + (width - bar.width) / 2, y) barBackGround.setPosition(x, y) barForeground.setPosition(x, y) this.x = x this.y = y } override fun setSize(width: Float, height: Float){ bar.setSize(width - (barForeground.width - bar.width) / 2, height) barBackGround.setSize(width, height) barForeground.setSize(width, height) this.width = barForeground.width this.height = barForeground.height } fun setValue(percent: Float){ bar.width = (width - 30) * percent } }
apache-2.0
d993ac1478c91a2455a25f9be9bac961
23.942857
74
0.629587
3.774892
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/GradlePackageOptionsBuilder.kt
1
1993
@file:Suppress("FunctionName") package org.jetbrains.dokka.gradle import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.kotlin.dsl.setProperty import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.DokkaConfigurationBuilder import org.jetbrains.dokka.DokkaDefaults import org.jetbrains.dokka.PackageOptionsImpl class GradlePackageOptionsBuilder( @Transient @get:Internal internal val project: Project ) : DokkaConfigurationBuilder<PackageOptionsImpl> { @Input val matchingRegex: Property<String> = project.objects.safeProperty<String>() .safeConvention(".*") @Input val includeNonPublic: Property<Boolean> = project.objects.safeProperty<Boolean>() .safeConvention(DokkaDefaults.includeNonPublic) @Input val documentedVisibilities: SetProperty<DokkaConfiguration.Visibility> = project.objects.setProperty<DokkaConfiguration.Visibility>() .convention(DokkaDefaults.documentedVisibilities) @Input val reportUndocumented: Property<Boolean> = project.objects.safeProperty<Boolean>() .safeConvention(DokkaDefaults.reportUndocumented) @Input val skipDeprecated: Property<Boolean> = project.objects.safeProperty<Boolean>() .safeConvention(DokkaDefaults.skipDeprecated) @Input val suppress: Property<Boolean> = project.objects.safeProperty<Boolean>() .safeConvention(DokkaDefaults.suppress) override fun build(): PackageOptionsImpl = PackageOptionsImpl( matchingRegex = checkNotNull(matchingRegex.getSafe()) { "prefix not specified" }, includeNonPublic = includeNonPublic.getSafe(), documentedVisibilities = documentedVisibilities.getSafe(), reportUndocumented = reportUndocumented.getSafe(), skipDeprecated = skipDeprecated.getSafe(), suppress = suppress.getSafe() ) }
apache-2.0
0bbd36b13e717a9c1459bd3da565cd90
37.326923
137
0.766683
4.994987
false
true
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/ReplaceWithErrorTypeArgsProcessor.kt
1
3042
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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.google.devtools.ksp.processor import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.* open class ReplaceWithErrorTypeArgsProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() override fun process(resolver: Resolver): List<KSAnnotated> { val decls = listOf( // Those have 2 type parameters resolver.getClassDeclarationByName("KS")!!, resolver.getClassDeclarationByName("KL")!!, resolver.getClassDeclarationByName("JS")!!, resolver.getClassDeclarationByName("JL")!!, // Those have 0 or 1 parameters resolver.getClassDeclarationByName("KS1")!!, resolver.getClassDeclarationByName("KL1")!!, resolver.getClassDeclarationByName("JS1")!!, resolver.getClassDeclarationByName("JL1")!!, resolver.getClassDeclarationByName("JSE")!!, resolver.getClassDeclarationByName("JSE.E")!!, resolver.getClassDeclarationByName("JLE")!!, resolver.getClassDeclarationByName("JLE.E")!!, resolver.getClassDeclarationByName("KSE")!!, resolver.getClassDeclarationByName("KSE.E")!!, resolver.getClassDeclarationByName("KLE")!!, resolver.getClassDeclarationByName("KLE.E")!!, ) val x = resolver.getPropertyDeclarationByName(resolver.getKSNameFromString("x"), true)!! val xargs = x.type.element!!.typeArguments val y = resolver.getPropertyDeclarationByName(resolver.getKSNameFromString("y"), true)!! val yargs = y.type.element!!.typeArguments for (decl in decls) { val declName = decl.qualifiedName!!.asString() results.add("$declName.star.replace($xargs): ${decl.asStarProjectedType().replace(xargs)}") results.add("$declName.star.replace($yargs): ${decl.asStarProjectedType().replace(yargs)}") results.add("$declName.asType($xargs): ${decl.asType(xargs)}") results.add("$declName.asType($yargs): ${decl.asType(yargs)}") results.add("$declName.asType(emptyList()): ${decl.asType(emptyList())}") } return emptyList() } override fun toResult(): List<String> { return results } }
apache-2.0
7e593c1128a0dced2436eb7c9c6e4bb1
44.402985
103
0.671598
4.716279
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/mappers/UserToTraktUser.kt
1
1141
/* * Copyright 2018 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 app.tivi.data.mappers import app.tivi.data.entities.TraktUser import com.uwetrottmann.trakt5.entities.User import javax.inject.Inject import javax.inject.Singleton @Singleton class UserToTraktUser @Inject constructor() : Mapper<User, TraktUser> { override suspend fun map(from: User) = TraktUser( username = from.username!!, name = from.name, location = from.location, about = from.about, avatarUrl = from.images?.avatar?.full, joined = from.joined_at, vip = from.vip ) }
apache-2.0
9e6e659bafa64c2e2a431135427d0da9
31.6
75
0.71078
4.031802
false
false
false
false
chrisbanes/tivi
ui/showdetails/src/main/java/app/tivi/showdetails/details/ShowDetailsViewState.kt
1
1639
/* * Copyright 2018 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 app.tivi.showdetails.details import androidx.compose.runtime.Immutable import app.tivi.api.UiMessage import app.tivi.data.entities.ShowTmdbImage import app.tivi.data.entities.TiviShow import app.tivi.data.resultentities.EpisodeWithSeason import app.tivi.data.resultentities.RelatedShowEntryWithShow import app.tivi.data.resultentities.SeasonWithEpisodesAndWatches import app.tivi.data.views.FollowedShowsWatchStats @Immutable internal data class ShowDetailsViewState( val isFollowed: Boolean = false, val show: TiviShow = TiviShow.EMPTY_SHOW, val posterImage: ShowTmdbImage? = null, val backdropImage: ShowTmdbImage? = null, val relatedShows: List<RelatedShowEntryWithShow> = emptyList(), val nextEpisodeToWatch: EpisodeWithSeason? = null, val watchStats: FollowedShowsWatchStats? = null, val seasons: List<SeasonWithEpisodesAndWatches> = emptyList(), val refreshing: Boolean = false, val message: UiMessage? = null ) { companion object { val Empty = ShowDetailsViewState() } }
apache-2.0
52b708450a1ae807a5b031266562d7d7
36.25
75
0.764491
4.128463
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/RemoveParenthesesFromExprIntention.kt
2
1311
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentOfType class RemoveParenthesesFromExprIntention : RsElementBaseIntentionAction<RsParenExpr>() { override fun getText(): String = "Remove parentheses from expression" override fun getFamilyName(): String = text fun isAvailable(expr: RsParenExpr?): Boolean { if (expr?.parentOfType<RsCondition>() == null && expr?.parentOfType<RsMatchExpr>() == null) return true val child = expr.children.singleOrNull() return when (child) { is RsStructLiteral -> false is RsBinaryExpr -> child.exprList.all { it !is RsStructLiteral } else -> true } } override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsParenExpr? { val parenExpr = element.parentOfType<RsParenExpr>() return if (isAvailable(parenExpr)) parenExpr else null } override fun invoke(project: Project, editor: Editor, ctx: RsParenExpr) { ctx.replace(ctx.expr) } }
mit
750f817fbd5bffe3f5e8558f4166f4a4
35.416667
111
0.700229
4.474403
false
false
false
false
KotlinBy/awesome-kotlin
src/main/kotlin/link/kotlin/scripts/PagesGenerator.kt
1
5224
package link.kotlin.scripts import link.kotlin.scripts.dsl.Article import link.kotlin.scripts.dsl.ArticleFeature import link.kotlin.scripts.dsl.ArticleFeature.highlightjs import link.kotlin.scripts.dsl.ArticleFeature.mathjax import link.kotlin.scripts.dsl.LinkType.article import link.kotlin.scripts.dsl.LanguageCodes.EN import link.kotlin.scripts.utils.writeFile import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.format.FormatStyle interface PagesGenerator { fun generate(articles: List<Article>, dist: String) companion object } private class DefaultPagesGenerator : PagesGenerator { override fun generate(articles: List<Article>, dist: String) { val articleBody = articles .groupBy { formatDate(it.date) } .map { """<div>${it.key}</div><ul>${getGroupLinks(it.value)}</ul>""" } .joinToString(separator = "\n") val article = Article( title = "Articles Index", url = "https://kotlin.link/articles/", body = articleBody, author = "Ruslan Ibragimov", date = LocalDate.now(), type = article, categories = listOf("Kotlin"), features = listOf(), filename = "index.html", lang = EN, description = articleBody ) (articles + article).forEach { writeFile("$dist/articles/${it.filename}", getHtml(it)) } } } private fun getGroupLinks(group: List<Article>): String { return group.joinToString(separator = "\n") { """<li><a href="./${it.filename}">${it.title}</a></li>""" } } internal val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) private fun formatDate(date: LocalDate): String { return date.format(formatter) } private fun formatDateTime(date: LocalDate): String { return date.format(DateTimeFormatter.ISO_DATE) + "T12:00:00+0000" } private fun getHtml(article: Article): String { return """ <!DOCTYPE html> <html lang="${article.lang.name}"> <head> <meta charset="utf-8"> <title>${article.title} – Kotlin.Link</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="format-detection" content="telephone=no"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="MobileOptimized" content="176"/> <meta name="HandheldFriendly" content="True"/> <meta name="robots" content="index, follow"/> <meta property="og:site_name" content="Kotlin.Link"> <meta property="og:type" content="article"> <meta property="og:title" content="${article.title}"> <meta property="og:description" content=""> <meta property="og:image" content=""> <meta property="article:published_time" content="${formatDateTime(article.date)}"> <meta property="article:modified_time" content="${formatDateTime(article.date)}"> <meta property="article:author" content="${article.author}"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="${article.title}"> <meta name="twitter:description" content=""> <meta name="twitter:image" content=""> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"> <link rel="canonical" href="${article.url}"/> <link rel="alternate" type="application/rss+xml" title="Kotlin.Link - 20 latest" href="/rss.xml"/> <link rel="alternate" type="application/rss+xml" title="Kotlin.Link - full archive" href="/rss-full.xml"/> <link href="/styles.css" rel="stylesheet"> ${getFeatures(article.features)} </head> <body> <div class="kt_page_wrap"> <div class="kt_page"> <main class="kt_article"> <header class="kt_article_header"> <h1 dir="auto">${article.title}</h1> <address dir="auto"> <a href="${article.url}" rel="author" title="Article Origin">${article.author}</a> <time datetime="${formatDateTime(article.date)}">${formatDate(article.date)}</time> </address> </header> <article id="_kt_editor" class="kt_article_content"> <h1>${article.title}<br></h1> <address>${article.author}<br></address> ${article.body} <hr/> </article> <aside class="kt_article_buttons"> <a href="/articles/" class="button edit_button">Articles</a> </aside> </main> </div> </div> </body> </html> """ } fun getFeatures(features: List<ArticleFeature>): String { return features.joinToString(separator = "\n") { when (it) { mathjax -> """<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>""" highlightjs -> """ <link rel="stylesheet" href="/github.css"> <script src="/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> """ } } } fun PagesGenerator.Companion.default(): PagesGenerator { return DefaultPagesGenerator() }
apache-2.0
d122517c5f6f761d4aa3a1a52a7e096d
36.84058
131
0.620835
3.962064
false
false
false
false
abdodaoud/Merlin
app/src/main/java/com/abdodaoud/merlin/extensions/DelegatesExtensions.kt
1
2240
package com.abdodaoud.merlin.extensions import android.content.Context import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty object DelegatesExtensions { fun <T> notNullSingleValue(): ReadWriteProperty<Any?, T> = NotNullSingleValueVar() fun preference(context: Context, name: String, default: Long) = Preference(context, name, default) } private class NotNullSingleValueVar<T>() : ReadWriteProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { return value ?: throw IllegalStateException("${property.name} not initialized") } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = if (this.value == null) value else throw IllegalStateException("${property.name} already initialized") } } class Preference<T>(val context: Context, val name: String, val default: T) : ReadWriteProperty<Any?, T> { val prefs by lazy { context.getSharedPreferences("default", Context.MODE_PRIVATE) } override fun getValue(thisRef: Any?, property: KProperty<*>): T { return findPreference(name, default) } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { putPreference(name, value) } private fun <U> findPreference(name: String, default: U): U = with(prefs) { val res: Any = when (default) { is Long -> getLong(name, default) is String -> getString(name, default) is Int -> getInt(name, default) is Boolean -> getBoolean(name, default) is Float -> getFloat(name, default) else -> throw IllegalArgumentException("This type can be saved into Preferences") } res as U } private fun <U> putPreference(name: String, value: U) = with(prefs.edit()) { when (value) { is Long -> putLong(name, value) is String -> putString(name, value) is Int -> putInt(name, value) is Boolean -> putBoolean(name, value) is Float -> putFloat(name, value) else -> throw IllegalArgumentException("This type can be saved into Preferences") }.apply() } }
mit
4ce4834ba14a9b23cb840b9a4ecd46ce
35.737705
106
0.644643
4.462151
false
false
false
false
MaisonWan/AppFileExplorer
FileExplorer/src/main/java/com/domker/app/explorer/file/FileInfo.kt
1
1120
package com.domker.app.explorer.file import android.content.Context import android.text.format.Formatter import java.io.File import java.text.SimpleDateFormat import java.util.* /** * 封装文件信息的实体类 * Created by Maison on 2017/8/31. */ data class FileInfo(val file: File) { private val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") /** * 返回文件类型 */ val fileType: FileType get() = FileType.getFileType(this) /** * 文件路径 */ val filePath: String get() = file.absolutePath /** * 是否是跳转到上层目录的标示 */ var isJumpParentPath: Boolean = false /** * 文件名称 */ val fileName: String get() = file.name /** * 获取文件的时间 */ fun getFileDate() = if (isJumpParentPath) "" else formatter.format(Date(file.lastModified()))!! /** * 是否是文件 */ fun isFile() = file.isFile /** * 获取文件尺寸 */ fun getFileSize(context: Context) = Formatter.formatFileSize(context, file.length())!! }
apache-2.0
32101c2778619a6eccd65b0513e0315f
17.703704
99
0.59802
3.672727
false
false
false
false
http4k/http4k
http4k-realtime-core/src/test/kotlin/org/http4k/sse/SseFilterTest.kt
1
2142
package org.http4k.sse import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Uri import org.http4k.routing.bind import org.http4k.routing.path import org.http4k.routing.sse import org.junit.jupiter.api.Test class SseFilterTest { private val messages = mutableListOf<String>() private val inner = SseFilter { next -> { messages += "inner filter in" next(it) messages += "inner filter out" } } private val first = SseFilter { next -> { messages += "first filter in" next(object : Sse by it { override val connectRequest: Request = it.connectRequest.header("foo", "newHeader") }) messages += "first filter out" } } private val second = SseFilter { next -> { messages += "second filter in" next(it) messages += "second filter out" } } private val sse = sse("/{foobar}" bind inner.then { messages += it.connectRequest.path("foobar")!! messages += it.connectRequest.header("foo")!! }) @Test fun `can manipulate value on way in and out of service`() { val svc = first.then(second).then(sse) val request = Request(GET, Uri.of("/path")) svc(request)(object : Sse { override val connectRequest: Request = request override fun send(message: SseMessage) { } override fun close() { } override fun onClose(fn: () -> Unit) { } } ) assertThat( messages, equalTo( listOf( "first filter in", "second filter in", "inner filter in", "path", "newHeader", "inner filter out", "second filter out", "first filter out" ) ) ) } }
apache-2.0
730d10bf93fd343daf4c4b64ffed971c
25.121951
99
0.515873
4.4625
false
false
false
false
orbit/orbit
src/orbit-util/src/main/kotlin/orbit/util/misc/ControlFlowUtills.kt
1
1833
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.util.misc import kotlinx.coroutines.delay import mu.KLogger /** * A suspending function that makes multiple attempts to successfully execute a code block. * Supports variable delays, logging and back off. * The result of the computation on the first successful execution or the exception thrown on the last failing execution * is propagated to the caller. * * @param maxAttempts The maximum number of attempts before failing. * @param initialDelay The initial delay after the first failure. * @param maxDelay The maximum amount of time to wait between attempts. * @param factor The factor to increase the wait time by after each attempt. * @param logger The logger to log attempt info to. No logging occurs if null. * @param body The code body to attempt to run. * @throws Throwable Any exception that is thrown on the last attempt. * @return The result of the computation. */ suspend inline fun <T> attempt( maxAttempts: Int = 5, initialDelay: Long = 1000, maxDelay: Long = Long.MAX_VALUE, factor: Double = 1.0, logger: KLogger? = null, body: () -> T ): T { var currentDelay = initialDelay for (i in 0 until maxAttempts - 1) { try { return body() } catch (t: Throwable) { logger?.warn(t) { "Attempt ${i + 1}/$maxAttempts failed. Retrying in ${currentDelay}ms." } } delay(currentDelay) currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay) } try { return body() } catch (t: Throwable) { logger?.warn(t) { "Attempt $maxAttempts/$maxAttempts failed. No more retries." } throw t } }
bsd-3-clause
753a3608f8f743ac6c26c5421abec746
34.269231
120
0.67976
4.137698
false
false
false
false
vitoling/HiWeather
src/main/kotlin/com/vito/work/weather/dto/StationAQI.kt
1
770
package com.vito.work.weather.dto import java.sql.Timestamp import java.time.LocalDateTime import javax.persistence.* /** * Created by lingzhiyuan. * Date : 16/4/17. * Time : 下午4:53. * Description: * */ @Entity @Table(name = "aqi_station") data class StationAQI( @Id @GeneratedValue(strategy = javax.persistence.GenerationType.AUTO) var id: Long = 0L, var station: Long = 0L, @Transient var station_name: String = "", var datetime: Timestamp = Timestamp.valueOf(LocalDateTime.now()), var value: Int = 0, // 数值 var PM25: Int = 0, //pm2.5 数值 var PM10: Int = 0, var O3: Int = 0, // 臭氧数值 var major: Int = 0 // 主要污染物 )
gpl-3.0
709cbd2d912cdcf39d2a968656808acd
22.903226
73
0.581081
3.363636
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/utils/ImageUtil.kt
1
2784
package im.fdx.v2ex.utils import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.util.Base64 import androidx.core.content.FileProvider import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import im.fdx.v2ex.BuildConfig import im.fdx.v2ex.GlideApp import im.fdx.v2ex.myApp import org.jetbrains.anko.toast object ImageUtil { fun shareImage(context: Context, url:String) { downloadImage(url) { val intent = Intent(Intent.ACTION_SEND) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra(Intent.EXTRA_STREAM, it) intent.type = "image/*" context.startActivity(Intent.createChooser(intent, "Share image via")) } } fun downloadImage(context: Context, url: String){ downloadImage(url) { context.toast( "已保存图片在 " + it.toString()) } } private fun downloadImage(url: String, ready : (Uri) ->Unit) { GlideApp.with(myApp) .asBitmap() .load(url) .into(object : SimpleTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { val uri = saveBitmap(url,resource) uri?.let { ready(it) } } }) } fun saveBitmap(url :String ,bitmap: Bitmap) : Uri? { var outStream: FileOutputStream? = null // Write to app data try { val dataPath = myApp.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val dir = File(dataPath!!.absolutePath + "/image") dir.mkdirs() val encodeToString = Base64.encodeToString(url.toByteArray(), Base64.DEFAULT) val fileName = String.format("%s.jpg", encodeToString) val outFile = File(dir, fileName) outStream = FileOutputStream(outFile) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream) outStream.flush() outStream.close() val uri = FileProvider.getUriForFile( myApp, "im.fdx.v2ex${if (BuildConfig.DEBUG) ".debug" else ""}.provider", outFile ) return uri } catch (e: FileNotFoundException) { print("FNF") e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { } return null } }
apache-2.0
37747bde1ced3e9d1a3c666a1fd03d13
29.811111
104
0.599928
4.536825
false
false
false
false
MusikPolice/funopoly
src/main/kotlin/ca/jonathanfritz/funopoly/game/board/Event.kt
1
2490
package ca.jonathanfritz.funopoly.game.board import ca.jonathanfritz.funopoly.game.Bank import ca.jonathanfritz.funopoly.game.Player sealed class Event: BoardSpace { object Go: Event() { override fun getGroup() = BoardSpace.Group.Go override fun doLanding(player: Player, bank: Bank, board: Board) { // typically, nothing happens when a player lands on Go // award $200 if landing on or passing go https://boardgames.stackexchange.com/a/12255 // TODO: optional double cash on go? } } object CommunityChest: Event() { override fun getGroup() = BoardSpace.Group.CommunityChest override fun doLanding(player: Player, bank: Bank, board: Board) { val card = bank.communityChest.draw() TODO("Not yet implemented") } } object IncomeTax: Event() { override fun getGroup() = BoardSpace.Group.Penalty override fun doLanding(player: Player, bank: Bank, board: Board) { TODO("Not yet implemented") } } object Chance: Event() { override fun getGroup() = BoardSpace.Group.Chance override fun doLanding(player: Player, bank: Bank, board: Board) { val card = bank.chance.draw() println("${player.name} drew ${card::class.simpleName} Chance card") card.doAction(player, bank, board) } } object Jail : Event() { override fun getGroup() = BoardSpace.Group.Jail override fun doLanding(player: Player, bank: Bank, board: Board) { // typically, nothing happens when a player lands on jail } } object FreeParking : Event() { override fun getGroup() = BoardSpace.Group.FreeParking override fun doLanding(player: Player, bank: Bank, board: Board) { // typically, nothing happens when a player lands on Free Parking // TODO: house rule that grants the player a pot of money from purchases } } object GoToJail : Event() { override fun getGroup() = BoardSpace.Group.GoToJail override fun doLanding(player: Player, bank: Bank, board: Board) { player.setBoardSpace(board, GoToJail::class) } } object LuxuryTax : Event() { override fun getGroup() = BoardSpace.Group.Penalty override fun doLanding(player: Player, bank: Bank, board: Board) { bank.transferFrom(75, player) } } }
gpl-3.0
21a9d2a2d29845e4c4bd74521bfda3d1
30.518987
98
0.619277
4.191919
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/service/bootstrap/BootstrapWorker.kt
1
4842
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.service.bootstrap import android.content.Context import androidx.work.CoroutineWorker import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.WorkerParameters import org.akvo.flow.BuildConfig.AWS_BUCKET import org.akvo.flow.BuildConfig.INSTANCE_URL import org.akvo.flow.R import org.akvo.flow.app.FlowApp import org.akvo.flow.domain.interactor.bootstrap.BootstrapProcessor import org.akvo.flow.domain.interactor.bootstrap.ProcessingResult import org.akvo.flow.util.ConstantUtil import org.akvo.flow.util.NotificationHelper import java.util.concurrent.TimeUnit import javax.inject.Inject /** * Service that will check a well-known location on the device's SD card for a * zip file that contains data that should be loaded on the device. * * The zip file can contain any number of directories which can each * contain ONE survey (the survey xml and any help media). The name of the * directory must be the surveyID and the name of the survey file will be used * for the survey name. The system will iterate through each directory and * install the survey and help media contained therein. * * If the survey is already present on the device, the survey in the ZIP file will overwrite the * data already on the device. * * If there are multiple zip files in the directory, this utility will process them in * lexicographical order by file name; Any fileswith a name starting with . will be skipped (to * prevent inadvertent processing of MAC OSX metadata files). * */ class BootstrapWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) { @Inject lateinit var zipFileLister: ZipFileLister @Inject lateinit var bootstrapProcessor: BootstrapProcessor init { val application = context.applicationContext as FlowApp application.getApplicationComponent().inject(this) } override suspend fun doWork(): Result { val zipFiles = zipFileLister.listSortedZipFiles() if (zipFiles.isEmpty()) { return Result.success() } displayBootstrapStartNotification() when (bootstrapProcessor.execute(zipFiles, INSTANCE_URL, AWS_BUCKET)) { is ProcessingResult.ProcessingErrorWrongDashboard -> { displayErrorNotification(applicationContext.getString(R.string.bootstrap_invalid_app_title), applicationContext.getString(R.string.bootstrap_invalid_app_message)) } is ProcessingResult.ProcessingError -> { displayErrorNotification(applicationContext.getString(R.string.bootstraperror), "") } else -> { displayNotification(applicationContext.getString(R.string.bootstrapcomplete)) } } return Result.success() } private fun displayBootstrapStartNotification() { val startMessage = applicationContext.getString(R.string.bootstrapstart) displayNotification(startMessage) } private fun displayErrorNotification(errorTitle: String, errorMessage: String) { NotificationHelper.displayErrorNotification(errorTitle, errorMessage, applicationContext, ConstantUtil.NOTIFICATION_BOOTSTRAP) } private fun displayNotification(message: String) { NotificationHelper.displayNotification(message, "", applicationContext, ConstantUtil.NOTIFICATION_BOOTSTRAP) } companion object { private const val TAG = "BootstrapWorker" @JvmStatic fun scheduleWork(context: Context) { val surveyDownloadRequest = OneTimeWorkRequest.Builder(BootstrapWorker::class.java) .setInitialDelay(0, TimeUnit.SECONDS) .addTag(TAG) .build() WorkManager.getInstance(context.applicationContext) .enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, surveyDownloadRequest) } } }
gpl-3.0
a2a573c5262c85924e97e0c0b6962b8a
37.736
108
0.713961
4.876133
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/custom/passphrase/keyboard/PassphraseKeyboard.kt
1
10351
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.custom.passphrase.keyboard import android.content.Context import android.os.Bundle import android.os.Parcelable import android.support.v7.app.AppCompatActivity import android.util.AttributeSet import android.view.Gravity import android.view.KeyEvent import android.view.View import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView import com.google.android.flexbox.FlexboxLayout import com.toshi.R import com.toshi.extensions.getColorById import com.toshi.extensions.getPxSize import com.toshi.extensions.isVisible import com.toshi.extensions.next import com.toshi.view.custom.ForegroundImageView import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout.Companion.FIRST_ROW import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout.Companion.FOURTH_ROW import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout.Companion.SECOND_ROW import com.toshi.view.custom.passphrase.keyboard.keyboardLayouts.KeyboardLayout.Companion.THIRD_ROW class PassphraseKeyboard : LinearLayout { companion object { const val KEYBOARD_LAYOUT = "keyboardLayout" const val SUPER_STATE = "superState" } private val builder by lazy { PassphraseKeyboardKeyBuilder() } private var keyboardLayout = KeyboardLayout.Layout.QWERTY constructor(context: Context): super(context) { init() } constructor(context: Context, attrs: AttributeSet): super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyle: Int): super(context, attrs, defStyle) { init() } private fun init() { orientation = VERTICAL setBackgroundColor(getColorById(R.color.sectioned_recyclerview_background)) updateKeyboard() } private fun updateKeyboard(keyboardLayout: KeyboardLayout = KeyboardLayout.Qwerty()) { removeAllViews() addRows(keyboardLayout) } private fun addRows(keyboardLayout: KeyboardLayout) { keyboardLayout.getLayout().forEachIndexed { index, row -> when (index) { FIRST_ROW -> addFirstRow(keyboardLayout, row.list) SECOND_ROW -> addSecondRow(keyboardLayout, row.list) THIRD_ROW -> addThirdRow(keyboardLayout, row.list) FOURTH_ROW -> addFourthRow(keyboardLayout, row.list) } } } private fun addFirstRow(keyboardLayout: KeyboardLayout, keys: List<Any>) { val firstRow = createAndAddFlexBoxLayout(isFirstRow = true) keys.forEach { val view = addViewsToParent(firstRow, it) val isLastItemOnRow = keyboardLayout.isLastChatOnRow(it) builder.setLayoutParams(isLastItemOnRow, view ?: return, it) } } private fun addSecondRow(keyboardLayout: KeyboardLayout, keys: List<Any>) { val secondRow = createAndAddFlexBoxLayout(isSecondRow = true) keys.forEach { val view = addViewsToParent(secondRow, it) val isLastItemOnRow = keyboardLayout.isLastChatOnRow(it) builder.setLayoutParams(isLastItemOnRow, view ?: return, it) } } private fun addThirdRow(keyboardLayout: KeyboardLayout, keys: List<Any>) { val thirdRow = createAndAddFlexBoxLayout() keys.forEach { val view = addViewsToParent(thirdRow, it) val isLastItemOnRow = keyboardLayout.isLastChatOnRow(it) builder.setLayoutParams(isLastItemOnRow, view ?: return, it) } } private fun addFourthRow(keyboardLayout: KeyboardLayout, keys: List<Any>) { val fourthRow = createAndAddFlexBoxLayout(isLastRow = true) keys.forEach { val view = addViewsToParent(fourthRow, it) val isLastItemOnRow = keyboardLayout.isLastChatOnRow(it) builder.setLayoutParams(isLastItemOnRow, view ?: return, it) } } private fun createAndAddFlexBoxLayout(isFirstRow: Boolean = false, isSecondRow: Boolean = false, isLastRow: Boolean = false): FlexboxLayout { val view = FlexboxLayout(context).apply { clipToPadding = false gravity = Gravity.CENTER addPaddingToFlexboxLayout(this, isFirstRow, isSecondRow, isLastRow) } addView(view) return view } private fun addPaddingToFlexboxLayout(flexboxLayout: FlexboxLayout, isFirstRow: Boolean, isSecondRow: Boolean, isLastRow: Boolean) { val topPadding = if (isFirstRow) getPxSize(R.dimen.margin_three_quarters) else 0 // Add extra padding on the second row because the second row has less keys than the first row val sidePadding = if (isSecondRow) getPxSize(R.dimen.margin_half) + (getPxSize(R.dimen.keyboard_key_width) / 2) else getPxSize(R.dimen.margin_half) val bottomPadding = if (isLastRow) getPxSize(R.dimen.margin_three_quarters) else getPxSize(R.dimen.margin_half) flexboxLayout.setPadding(sidePadding, topPadding, sidePadding, bottomPadding) } private fun addViewsToParent(parent: FlexboxLayout, key: Any): View? { val view = when (key) { is String -> createTextView(key) is KeyboardLayout.Action -> createImageButton(key) else -> null } parent.addView(view ?: return null) return view } private fun createTextView(key: String): TextView { return builder.createTextView(context, key).apply { setOnClickListener { val text = (it as TextView).text handleInput(text) } } } private fun createImageButton(action: KeyboardLayout.Action): View? { return when (action) { KeyboardLayout.Action.BACKSPACE -> createBackSpaceView() KeyboardLayout.Action.SHIFT -> createShiftView() KeyboardLayout.Action.LANGUAGE -> createLanguageView() KeyboardLayout.Action.SPACEBAR -> createSpaceBarView() KeyboardLayout.Action.RETURN -> createReturnView() } } private fun createBackSpaceView(): ForegroundImageView { return builder.createBackSpaceView(context).apply { setOnClickListener { handleInput(KeyboardLayout.Action.BACKSPACE) } } } private fun createShiftView() = builder.createShiftView(context) private fun createLanguageView(): ForegroundImageView { return builder.createLanguageView(context).apply { setOnClickListener { changeKeyboardLayout() } } } private fun changeKeyboardLayout() { keyboardLayout = keyboardLayout.next() updateKeyboard(KeyboardLayout.getLayout(keyboardLayout)) } private fun createSpaceBarView(): TextView { return builder.createSpaceBarView(context).apply { setOnClickListener { handleInput(KeyboardLayout.Action.SPACEBAR) } } } private fun createReturnView() = builder.createReturnView(context) private fun handleInput(input: Any) { val focusCurrent = (context as AppCompatActivity).window.currentFocus if (focusCurrent == null || focusCurrent.javaClass is EditText) return val editText = focusCurrent as EditText when (input) { is CharSequence -> handleText(editText, input) is KeyboardLayout.Action -> handleAction(editText, input) } } private fun handleText(editText: EditText, charSequence: CharSequence) { val editable = editText.text val start = editText.selectionStart editable.insert(start, charSequence) } private fun handleAction(editText: EditText, action: KeyboardLayout.Action) { when (action) { KeyboardLayout.Action.BACKSPACE -> handleBackSpace(editText) KeyboardLayout.Action.SPACEBAR -> addWhiteSpace(editText) else -> { /*Don't do anything with these actions*/ } } } private fun handleBackSpace(editText: EditText) { val editable = editText.text val lastIndex = editable.length if (lastIndex <= 0) dispatchDeleteKeyEvent(editText) else editable.delete(lastIndex - 1, lastIndex) } private fun dispatchDeleteKeyEvent(editText: EditText) { val keyEvent = KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0) editText.dispatchKeyEvent(keyEvent) } private fun addWhiteSpace(editText: EditText) { val editable = editText.text val start = editText.selectionStart editable.insert(start, " ") } fun showKeyboard() = isVisible(true) fun hideKeyboard() = isVisible(false) public override fun onRestoreInstanceState(state: Parcelable?) { if (state is Bundle) { val bundle = state as Bundle? keyboardLayout = bundle?.getSerializable(KEYBOARD_LAYOUT) as? KeyboardLayout.Layout ?: KeyboardLayout.Layout.QWERTY } super.onRestoreInstanceState(state) } override fun onSaveInstanceState(): Parcelable { val bundle = Bundle() bundle.putSerializable(KEYBOARD_LAYOUT, keyboardLayout) bundle.putParcelable(SUPER_STATE, super.onSaveInstanceState()) return bundle } }
gpl-3.0
41da63667dadc0cf2112166ca71940b3
38.212121
119
0.668341
4.732968
false
false
false
false
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/api/AbstractApiService.kt
1
2920
package com.samourai.wallet.api import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import java.io.IOException import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.SSLContext import javax.net.ssl.SSLSession import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException /** * samourai-wallet-android * */ /** * Abstract */ abstract class AbstractApiService { abstract fun buildClient(url: HttpUrl): OkHttpClient companion object { val JSON: MediaType = "application/json; charset=utf-8".toMediaType() } suspend fun executeRequest(request: Request): Response { val client = buildClient(request.url) return client.newCall(request).await() } /** * Only for .onion endpoints */ @Throws(Exception::class) fun getHostNameVerifier(clientBuilder: OkHttpClient.Builder) { // Create a trust manager that does not validate certificate chains val trustAllCerts = arrayOf<TrustManager>( object : X509TrustManager { override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {} override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {} override fun getAcceptedIssuers(): Array<X509Certificate> { return arrayOf() } } ) // Install the all-trusting trust manager val sslContext = SSLContext.getInstance("SSL") sslContext.init(null, trustAllCerts, SecureRandom()) // Create an ssl socket factory with our all-trusting manager val sslSocketFactory = sslContext.socketFactory clientBuilder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager) clientBuilder.hostnameVerifier { hostname: String?, session: SSLSession? -> true } } private suspend fun Call.await(): Response { return suspendCancellableCoroutine { continuation -> enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { continuation.resume(response) } override fun onFailure(call: Call, e: IOException) { // Don't bother with resuming the continuation if it is already cancelled. if (continuation.isCancelled) return continuation.resumeWithException(e) } }) continuation.invokeOnCancellation { try { cancel() } catch (ex: Throwable) { //Ignore cancel exception } } } } }
unlicense
4f23e8fef082ba108b88df1e5d9302e4
31.087912
103
0.632534
5.299456
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/controls/UploadButtonFragment.kt
1
4551
package de.westnordost.streetcomplete.controls import android.content.SharedPreferences import android.net.ConnectivityManager import android.os.Bundle import android.view.View import androidx.core.content.getSystemService import androidx.core.view.isGone import androidx.fragment.app.Fragment import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.Prefs import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.UnsyncedChangesCountSource import de.westnordost.streetcomplete.data.upload.UploadController import de.westnordost.streetcomplete.data.upload.UploadProgressListener import de.westnordost.streetcomplete.data.user.UserLoginStatusSource import de.westnordost.streetcomplete.ktx.toast import de.westnordost.streetcomplete.ktx.viewLifecycleScope import de.westnordost.streetcomplete.view.dialogs.RequestLoginDialog import kotlinx.coroutines.launch import javax.inject.Inject /** Fragment that shows the upload button, including upload progress etc. */ class UploadButtonFragment : Fragment(R.layout.fragment_upload_button) { @Inject internal lateinit var uploadController: UploadController @Inject internal lateinit var userLoginStatusSource: UserLoginStatusSource @Inject internal lateinit var unsyncedChangesCountSource: UnsyncedChangesCountSource @Inject internal lateinit var prefs: SharedPreferences private val uploadButton get() = view as UploadButton private val unsyncedChangesCountListener = object : UnsyncedChangesCountSource.Listener { override fun onIncreased() { viewLifecycleScope.launch { updateCount() }} override fun onDecreased() { viewLifecycleScope.launch { updateCount() }} } private val uploadProgressListener = object : UploadProgressListener { override fun onStarted() { viewLifecycleScope.launch { updateProgress(true) } } override fun onFinished() { viewLifecycleScope.launch { updateProgress(false) } } } /* --------------------------------------- Lifecycle ---------------------------------------- */ init { Injector.applicationComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) uploadButton.setOnClickListener { if (isConnected()) { uploadChanges() } else { context?.toast(R.string.offline) } } } override fun onStart() { super.onStart() /* Only show the button if autosync is off */ uploadButton.isGone = isAutosync if (!isAutosync) { viewLifecycleScope.launch { updateCount() } updateProgress(uploadController.isUploadInProgress) unsyncedChangesCountSource.addListener(unsyncedChangesCountListener) uploadController.addUploadProgressListener(uploadProgressListener) } } override fun onStop() { super.onStop() uploadController.removeUploadProgressListener(uploadProgressListener) unsyncedChangesCountSource.removeListener(unsyncedChangesCountListener) } // --------------------------------------------------------------------------------------------- private val isAutosync: Boolean get() = Prefs.Autosync.valueOf(prefs.getString(Prefs.AUTOSYNC, "ON")!!) == Prefs.Autosync.ON private suspend fun updateCount() { uploadButton.uploadableCount = unsyncedChangesCountSource.getCount() } private fun updateProgress(isUploadInProgress: Boolean) { if (isUploadInProgress) { uploadButton.isEnabled = false uploadButton.showProgress = true } else { uploadButton.isEnabled = true uploadButton.showProgress = false } } private fun uploadChanges() { // because the app should ask for permission even if there is nothing to upload right now if (!userLoginStatusSource.isLoggedIn) { context?.let { RequestLoginDialog(it).show() } } else { uploadController.upload() } } /** Does not necessarily mean that the user has internet. But if he is not connected, he will * not have internet */ private fun isConnected(): Boolean { val connectivityManager = context?.getSystemService<ConnectivityManager>() val activeNetworkInfo = connectivityManager?.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } }
gpl-3.0
676e477984a43f39e81d8d16575c3534
38.921053
100
0.695232
5.354118
false
false
false
false
toxxmeister/BLEacon
library/src/main/java/de/troido/bleacon/config/advertise/BleAdSettings.kt
1
662
package de.troido.bleacon.config.advertise import android.bluetooth.le.AdvertiseSettings @JvmOverloads fun adSettings(advertiseMode: Int = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER, isConnectable: Boolean = true, txPowerLevel: Int = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM, timeout: Int = 0): AdvertiseSettings = AdvertiseSettings.Builder() .apply { setAdvertiseMode(advertiseMode) setConnectable(isConnectable) setTxPowerLevel(txPowerLevel) setTimeout(timeout) } .build()
apache-2.0
9d91ffca0836f61f5282044f3f9d238f
35.777778
79
0.599698
5.171875
false
true
false
false
CajetanP/coding-exercises
Others/Kotlin/kotlin-koans/src/i_introduction/_5_String_Templates/n05StringTemplates.kt
1
1209
package i_introduction._5_String_Templates import util.TODO import util.doc5 fun example1(a: Any, b: Any) = "This is some text in which variables ($a, $b) appear." fun example2(a: Any, b: Any) = "You can write it in a Java way as well. Like this: " + a + ", " + b + "!" fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}" fun example4() = """ You can use raw strings to write multiline text. There is no escaping here, so raw strings are useful for writing regex patterns, you don't need to escape a backslash by a backslash. String template entries (${42}) are allowed here. """ fun getPattern() = """\d{2}\.\d{2}\.\d{4}""" fun example() = "13.06.1992".matches(getPattern().toRegex()) //true val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" fun todoTask5(): Nothing = TODO( """ Task 5. Copy the body of 'getPattern()' to the 'task5()' function below and rewrite it in such a way that it matches format: '13 JUN 1992'. Use the 'month' variable. """, documentation = doc5(), references = { getPattern(); month }) fun task5(): String { return """\d{2} $month \d{4}""" }
mit
b1f771b5ea7dba171a28ebddb8cef0f0
29.225
91
0.622829
3.276423
false
false
false
false
brianmadden/krawler
src/main/kotlin/io/thelandscape/krawler/http/Requests.kt
1
10302
/** * Created by @brianmadden on 10/21/16. * * Copyright (c) <2016> <H, llc> * 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 io.thelandscape.krawler.http import io.thelandscape.krawler.crawler.KrawlConfig import io.thelandscape.krawler.robots.RobotsTxt import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import org.apache.http.HttpRequest import org.apache.http.HttpResponse import org.apache.http.client.config.CookieSpecs import org.apache.http.client.config.RequestConfig import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpHead import org.apache.http.client.methods.HttpUriRequest import org.apache.http.client.protocol.HttpClientContext import org.apache.http.conn.ssl.NoopHostnameVerifier import org.apache.http.conn.ssl.TrustStrategy import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.DefaultRedirectStrategy import org.apache.http.impl.client.HttpClients import org.apache.http.impl.conn.PoolingHttpClientConnectionManager import org.apache.http.protocol.HttpContext import org.apache.http.ssl.SSLContextBuilder import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.security.cert.X509Certificate import java.time.Instant interface RequestProviderIf { /** * Method to check the status code of a URL */ suspend fun checkUrl(url: KrawlUrl): RequestResponse /** * Method to get the contents of a URL */ suspend fun getUrl(url: KrawlUrl): RequestResponse /** * Method to get a robots.txt from a KrawlUrl */ suspend fun fetchRobotsTxt(url: KrawlUrl): RequestResponse } internal class HistoryTrackingRedirectStrategy: DefaultRedirectStrategy() { override fun getRedirect(request: HttpRequest, response: HttpResponse, context: HttpContext): HttpUriRequest { val newRequest = super.getRedirect(request, response, context) val node: RedirectHistoryNode = RedirectHistoryNode(request.requestLine.uri, response.statusLine.statusCode, newRequest.uri.toASCIIString()) val redirectHistory: List<RedirectHistoryNode> = context.getAttribute("fullRedirectHistory") as List<RedirectHistoryNode>? ?: listOf<RedirectHistoryNode>() context.setAttribute("fullRedirectHistory", redirectHistory + listOf(node)) return newRequest } } private val pcm: PoolingHttpClientConnectionManager = PoolingHttpClientConnectionManager() class Requests(private val krawlConfig: KrawlConfig, private var httpClient: CloseableHttpClient? = null) : RequestProviderIf { private val logger: Logger = LogManager.getLogger() init { if (httpClient == null) { val requestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .setExpectContinueEnabled(false) .setContentCompressionEnabled(krawlConfig.allowContentCompression) .setRedirectsEnabled(krawlConfig.followRedirects && krawlConfig.useFastRedirectStrategy) .setConnectionRequestTimeout(krawlConfig.connectionRequestTimeout) .setConnectTimeout(krawlConfig.connectTimeout) .setSocketTimeout(krawlConfig.socketTimeout) .build() val trustStrat = TrustStrategy { _: Array<X509Certificate>, _: String -> true } val sslContext = SSLContextBuilder.create() .loadTrustMaterial(null, trustStrat) .build() val redirectStrategy = HistoryTrackingRedirectStrategy() httpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setSSLContext(sslContext) .setSSLHostnameVerifier(NoopHostnameVerifier()) .setRedirectStrategy(redirectStrategy) .setUserAgent(krawlConfig.userAgent) .setConnectionManager(pcm) .build() } } /** Fetch the robots.txt file from a domain * @param url [KrawlUrl]: The URL to fetch robots from * * @return [Deferred<RequestResponse>]: The parsed robots.txt or, or ErrorResponse on error */ override suspend fun fetchRobotsTxt(url: KrawlUrl): RequestResponse { return asyncFetchRobotsTxt(url).await() } internal fun asyncFetchRobotsTxt(url: KrawlUrl): Deferred<RequestResponse> { val robotsRequest = KrawlUrl.new("${url.hierarchicalPart}/robots.txt") return asyncMakeRequest(robotsRequest, ::HttpGet, ::RobotsTxt) } /** Check a URL and return it's status code * @param url KrawlUrl: the url to check * * @return [Deferred<RequestResponse>]: KrawlDocument containing the status code, or ErrorResponse on error */ override suspend fun checkUrl(url: KrawlUrl): RequestResponse { return asyncMakeRequest(url, ::HttpHead, ::KrawlDocument).await() } /** Get the contents of a URL * @param url KrawlUrl: the URL to get the contents of * * @return [RequestResponse]: The parsed HttpResponse returned by the GET request */ override suspend fun getUrl(url: KrawlUrl): RequestResponse { return asyncMakeRequest(url, ::HttpGet, ::KrawlDocument).await() } // Hash map to track requests and respect politeness private val requestTracker: RequestTracker = RequestTracker() /** Convenience function for building, & issuing the HttpRequest * @param url KrawlUrl: Url to make request to * @param reqFun: Function used to construct the request * @param retFun: Function used to construct the response object */ private fun asyncMakeRequest(url: KrawlUrl, reqFun: (String) -> HttpUriRequest, retFun: (KrawlUrl, HttpResponse, HttpClientContext) -> RequestResponse) : Deferred<RequestResponse> = GlobalScope.async(Dispatchers.Default) { val httpContext = HttpClientContext() httpContext.setAttribute("fullRedirectHistory", listOf<RedirectHistoryNode>()) val req: HttpUriRequest = reqFun(url.canonicalForm) val host: String = url.host // Handle politeness if (krawlConfig.politenessDelay > 0) { val myLock = requestTracker.getLock(host) myLock.lock() try { val reqDelta = Instant.now().toEpochMilli() - requestTracker.getTimestamp(host) if (reqDelta >= 0 && reqDelta < krawlConfig.politenessDelay) { // Sleep until the remainder of the politeness delay has elapsed logger.debug("Sleeping for ${krawlConfig.politenessDelay - reqDelta} ms for politeness.") delay(krawlConfig.politenessDelay - reqDelta) } // Set last request time for politeness requestTracker.setTimestamp(host, Instant.now().toEpochMilli()) } finally { myLock.unlock() } } val resp: RequestResponse = try { val response: HttpResponse? = httpClient!!.execute(req, httpContext) if (response == null) ErrorResponse(url) else retFun(url, response, httpContext) } catch (e: Throwable) { ErrorResponse(url, e.toString()) } resp } } /** * Class to track requests timestamps, and the locks that will be used to synchronize the timestamp * access. */ class RequestTracker { private val lockMapLock: Mutex = Mutex() private val lockMap: MutableMap<String, Mutex> = mutableMapOf() private val timestampMap: MutableMap<String, Long> = mutableMapOf() /** * Gets the lock associated with a specific host that will be used to synchronize the politeness * delay code section. * * Note: This operation -IS- threadsafe. * * @param host String: The host that this lock will be associated with. * @return the [Mutex] object that will lock the synchronized section */ suspend fun getLock(host: String): Mutex { lockMapLock.lock() return try { lockMap[host] ?: lockMap.getOrPut(host, { Mutex() }) } finally { lockMapLock.unlock() } } /** * Gets the timestamp associated with a specific host, to determine when the next request is safe * to send. * * Note: This operation is -NOT- threadsafe and should only be used in a synchronized block. * * @param host String: The host associated with this timestamp * @return Long representing the timestamp in milliseconds since the epoch */ fun getTimestamp(host: String): Long { return timestampMap.getOrPut(host, { 0 }) } /** * Sets the timestamp associated with a specific host. * * Note: This operation is -NOT- threadsafe and should only be used in a synchronized block. * * @param host String: The host associated with this timestamp * @param value Long: The timestamp in milliseconds since the epoch * @return [Unit] */ fun setTimestamp(host: String, value: Long) = timestampMap.put(host, value) }
mit
205bd4519b0ce408cdad46fb154bb18d
40.208
122
0.681518
4.6806
false
true
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/CertificatesServiceTest.kt
1
39897
// Copyright 2021 The Cross-Media Measurement Authors // // 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 org.wfanet.measurement.kingdom.service.internal.testing import com.google.common.truth.Truth.assertThat import com.google.common.truth.extensions.proto.ProtoTruth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.timestamp import io.grpc.Status import io.grpc.StatusRuntimeException import java.time.Clock import java.time.Instant import kotlin.random.Random import kotlin.test.assertFailsWith import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.identity.RandomIdGenerator import org.wfanet.measurement.common.toProtoTime import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.internal.kingdom.CertificateKt import org.wfanet.measurement.internal.kingdom.CertificateKt.details import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineImplBase import org.wfanet.measurement.internal.kingdom.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.GetCertificateRequestKt import org.wfanet.measurement.internal.kingdom.Measurement import org.wfanet.measurement.internal.kingdom.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.MeasurementKt import org.wfanet.measurement.internal.kingdom.MeasurementsGrpcKt import org.wfanet.measurement.internal.kingdom.ModelProvidersGrpcKt.ModelProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.StreamMeasurementsRequestKt import org.wfanet.measurement.internal.kingdom.cancelMeasurementRequest import org.wfanet.measurement.internal.kingdom.certificate import org.wfanet.measurement.internal.kingdom.copy import org.wfanet.measurement.internal.kingdom.getCertificateRequest import org.wfanet.measurement.internal.kingdom.measurement import org.wfanet.measurement.internal.kingdom.releaseCertificateHoldRequest import org.wfanet.measurement.internal.kingdom.revokeCertificateRequest import org.wfanet.measurement.internal.kingdom.setParticipantRequisitionParamsRequest import org.wfanet.measurement.internal.kingdom.streamMeasurementsRequest import org.wfanet.measurement.kingdom.deploy.common.testing.DuchyIdSetter private const val RANDOM_SEED = 1 private const val EXTERNAL_CERTIFICATE_ID = 123L private val EXTERNAL_DUCHY_IDS = listOf("duchy_1", "duchy_2", "duchy_3") private const val NOT_AN_ID = 13579L private val CERTIFICATE_DER = ByteString.copyFromUtf8("This is a certificate der.") private val X509_DER = ByteString.copyFromUtf8("This is a X.509 certificate in DER format.") private val CERTIFICATE = certificate { notValidBefore = timestamp { seconds = 12345 } notValidAfter = timestamp { seconds = 23456 } subjectKeyIdentifier = ByteString.copyFromUtf8("This is an SKID") details = details { x509Der = CERTIFICATE_DER } } @RunWith(JUnit4::class) abstract class CertificatesServiceTest<T : CertificatesCoroutineImplBase> { @get:Rule val duchyIdSetter = DuchyIdSetter(EXTERNAL_DUCHY_IDS) protected data class Services<T>( val certificatesService: T, val measurementConsumersService: MeasurementConsumersCoroutineImplBase, val measurementsService: MeasurementsGrpcKt.MeasurementsCoroutineImplBase, val dataProvidersService: DataProvidersCoroutineImplBase, val modelProvidersService: ModelProvidersCoroutineImplBase, val computationParticipantsService: ComputationParticipantsCoroutineImplBase, val accountsService: AccountsCoroutineImplBase ) private val clock: Clock = Clock.systemUTC() private val idGenerator = RandomIdGenerator(clock, Random(RANDOM_SEED)) private val population = Population(clock, idGenerator) protected lateinit var certificatesService: T private set protected lateinit var measurementConsumersService: MeasurementConsumersCoroutineImplBase private set protected lateinit var measurementsService: MeasurementsGrpcKt.MeasurementsCoroutineImplBase private set protected lateinit var dataProvidersService: DataProvidersCoroutineImplBase private set protected lateinit var modelProvidersService: ModelProvidersCoroutineImplBase private set protected lateinit var computationParticipantsService: ComputationParticipantsCoroutineImplBase private set protected lateinit var accountsService: AccountsCoroutineImplBase private set protected abstract fun newServices(idGenerator: IdGenerator): Services<T> @Before fun initServices() { val services = newServices(idGenerator) certificatesService = services.certificatesService measurementConsumersService = services.measurementConsumersService measurementsService = services.measurementsService dataProvidersService = services.dataProvidersService modelProvidersService = services.modelProvidersService computationParticipantsService = services.computationParticipantsService accountsService = services.accountsService } @Test fun `getCertificate throws INVALID_ARGUMENT when parent not specified`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { certificatesService.getCertificate( getCertificateRequest { externalCertificateId = EXTERNAL_CERTIFICATE_ID } ) } assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) } @Test fun `createCertificate throws INVALID_ARGUMENT when parent not specified`() = runBlocking { val certificate = CERTIFICATE.copy { clearParent() } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.createCertificate(certificate) } assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) } private fun assertGetFailsWithMissingCertificate(init: GetCertificateRequestKt.Dsl.() -> Unit) { val request = getCertificateRequest { init() externalCertificateId = EXTERNAL_CERTIFICATE_ID } val exception = assertFailsWith<StatusRuntimeException> { runBlocking { certificatesService.getCertificate(request) } } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) } @Test fun `getCertificate fails for missing certificates`() = runBlocking { assertGetFailsWithMissingCertificate { externalDuchyId = EXTERNAL_DUCHY_IDS[0] } val dataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId assertGetFailsWithMissingCertificate { externalDataProviderId = dataProviderId } val measurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId assertGetFailsWithMissingCertificate { externalMeasurementConsumerId = measurementConsumerId } val modelProviderId = population.createModelProvider(modelProvidersService).externalModelProviderId assertGetFailsWithMissingCertificate { externalModelProviderId = modelProviderId } } private fun assertCreateFailsWithMissingOwner( expectedMessage: String, init: CertificateKt.Dsl.() -> Unit ) { val certificate = CERTIFICATE.copy { init() } val exception = assertFailsWith<StatusRuntimeException> { runBlocking { certificatesService.createCertificate(certificate) } } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains(expectedMessage) } @Test fun `createCertificate fails due to owner not_found`() { assertCreateFailsWithMissingOwner("Duchy not found") { externalDuchyId = "missing-duchy-id" } assertCreateFailsWithMissingOwner("Data Provider not found") { externalDataProviderId = NOT_AN_ID } assertCreateFailsWithMissingOwner("Measurement Consumer not found") { externalMeasurementConsumerId = NOT_AN_ID } assertCreateFailsWithMissingOwner("Model Provider not found") { externalModelProviderId = NOT_AN_ID } } private fun assertCreateCertificateSucceeds(init: CertificateKt.Dsl.() -> Unit) { val requestCertificate = CERTIFICATE.copy { init() subjectKeyIdentifier = ByteString.copyFromUtf8("Some unique SKID for $parentCase") } val createdCertificate = runBlocking { certificatesService.createCertificate(requestCertificate) } val expectedCertificate = requestCertificate.copy { externalCertificateId = createdCertificate.externalCertificateId } assertThat(createdCertificate).isEqualTo(expectedCertificate) } @Test fun `createCertificate succeeds`() = runBlocking { assertCreateCertificateSucceeds { externalDuchyId = EXTERNAL_DUCHY_IDS[0] } val dataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId assertCreateCertificateSucceeds { externalDataProviderId = dataProviderId } val measurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId assertCreateCertificateSucceeds { externalMeasurementConsumerId = measurementConsumerId } val modelProviderId = population.createModelProvider(modelProvidersService).externalModelProviderId assertCreateCertificateSucceeds { externalModelProviderId = modelProviderId } } private fun assertGetCertificateSucceeds(init: CertificateKt.Dsl.() -> Unit) = runBlocking { val requestCertificate = CERTIFICATE.copy { init() subjectKeyIdentifier = ByteString.copyFromUtf8("Some unique SKID for $parentCase") } val createdCertificate = certificatesService.createCertificate(requestCertificate) val getRequest = getCertificateRequest { externalCertificateId = createdCertificate.externalCertificateId @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") when (requestCertificate.parentCase) { Certificate.ParentCase.EXTERNAL_DATA_PROVIDER_ID -> externalDataProviderId = requestCertificate.externalDataProviderId Certificate.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID -> externalMeasurementConsumerId = requestCertificate.externalMeasurementConsumerId Certificate.ParentCase.EXTERNAL_DUCHY_ID -> externalDuchyId = requestCertificate.externalDuchyId Certificate.ParentCase.EXTERNAL_MODEL_PROVIDER_ID -> externalModelProviderId = requestCertificate.externalModelProviderId Certificate.ParentCase.PARENT_NOT_SET -> error("Invalid parentCase") } } assertThat(certificatesService.getCertificate(getRequest)).isEqualTo(createdCertificate) } @Test fun `getCertificate succeeds`() = runBlocking { assertGetCertificateSucceeds { externalDuchyId = EXTERNAL_DUCHY_IDS[0] } val dataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId assertGetCertificateSucceeds { externalDataProviderId = dataProviderId } val measurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId assertGetCertificateSucceeds { externalMeasurementConsumerId = measurementConsumerId } val modelProviderId = population.createModelProvider(modelProvidersService).externalModelProviderId assertGetCertificateSucceeds { externalModelProviderId = modelProviderId } } @Test fun `createCertificate fails due to subjectKeyIdentifier collision`() = runBlocking { val externalMeasurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId val certificate = CERTIFICATE.copy { this.externalMeasurementConsumerId = externalMeasurementConsumerId } certificatesService.createCertificate(certificate) val exception = assertFailsWith<StatusRuntimeException> { certificatesService.createCertificate(certificate) } assertThat(exception.status.code).isEqualTo(Status.Code.ALREADY_EXISTS) assertThat(exception) .hasMessageThat() .contains("Certificate with the subject key identifier (SKID) already exists.") } @Test fun `revokeCertificate throws INVALID_ARGUMENT when parent not specified`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { certificatesService.revokeCertificate( revokeCertificateRequest { revocationState = Certificate.RevocationState.REVOKED } ) } assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) } @Test fun `revokeCertificate fails due to wrong DataProviderId`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { this.externalDataProviderId = 1234L // wrong externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.revokeCertificate(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Certificate not found") } @Test fun `revokeCertificate succeeds for DataProviderCertificate`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val revokedCertificate = certificatesService.revokeCertificate(request) assertThat(revokedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(revokedCertificate.revocationState).isEqualTo(Certificate.RevocationState.REVOKED) } @Test fun `revokeCertificate for DataProvider fails pending Measurements`(): Unit = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val dataProvider = population.createDataProvider(dataProvidersService) val measurementOne = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement one", dataProvider ) val measurementTwo = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement two", dataProvider ) measurementsService.cancelMeasurement( cancelMeasurementRequest { externalMeasurementConsumerId = measurementTwo.externalMeasurementConsumerId externalMeasurementId = measurementTwo.externalMeasurementId } ) val request = revokeCertificateRequest { externalDataProviderId = dataProvider.externalDataProviderId externalCertificateId = dataProvider.certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } certificatesService.revokeCertificate(request) val measurements = measurementsService .streamMeasurements( streamMeasurementsRequest { filter = StreamMeasurementsRequestKt.filter { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId states += Measurement.State.FAILED } } ) .toList() assertThat(measurements) .comparingExpectedFieldsOnly() .containsExactly( measurement { state = Measurement.State.FAILED externalMeasurementId = measurementOne.externalMeasurementId details = measurementOne.details.copy { failure = MeasurementKt.failure { reason = Measurement.Failure.Reason.CERTIFICATE_REVOKED message = "An associated Data Provider certificate has been revoked." } } } ) } @Test fun `revokeCertificate fails due to wrong MeasurementConsumerId`() = runBlocking { val externalMeasurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId val certificate = certificatesService.createCertificate( certificate { this.externalMeasurementConsumerId = externalMeasurementConsumerId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { this.externalMeasurementConsumerId = 1234L // wrong MeasurementConsumerId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.revokeCertificate(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Certificate not found") } @Test fun `revokeCertificate succeeds for MeasurementConsumerCertificate`() = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val certificate = certificatesService.createCertificate( certificate { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val revokedCertificate = certificatesService.revokeCertificate(request) assertThat(revokedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(revokedCertificate.revocationState).isEqualTo(Certificate.RevocationState.REVOKED) } @Test fun `revokeCertificate for MeasurementConsumer fails pending Measurements`(): Unit = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val measurementOne = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement one" ) val measurementTwo = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement two" ) measurementsService.cancelMeasurement( cancelMeasurementRequest { externalMeasurementConsumerId = measurementTwo.externalMeasurementConsumerId externalMeasurementId = measurementTwo.externalMeasurementId } ) val request = revokeCertificateRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId externalCertificateId = measurementConsumer.certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } certificatesService.revokeCertificate(request) val measurements = measurementsService .streamMeasurements( streamMeasurementsRequest { filter = StreamMeasurementsRequestKt.filter { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId states += Measurement.State.FAILED } } ) .toList() assertThat(measurements) .comparingExpectedFieldsOnly() .containsExactly( measurement { state = Measurement.State.FAILED externalMeasurementId = measurementOne.externalMeasurementId details = measurementOne.details.copy { failure = MeasurementKt.failure { reason = Measurement.Failure.Reason.CERTIFICATE_REVOKED message = "The associated Measurement Consumer certificate has been revoked." } } } ) } @Test fun `revokeCertificate fails due to wrong DuchyId`() = runBlocking { val certificate = certificatesService.createCertificate( certificate { externalDuchyId = EXTERNAL_DUCHY_IDS[0] notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { this.externalDuchyId = "non-existing-duchy-id" // wrong MeasurementConsumerId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.revokeCertificate(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Duchy not found") } @Test fun `revokeCertificate succeeds for DuchyCertificate`() = runBlocking { val externalDuchyId = EXTERNAL_DUCHY_IDS[0] val certificate = certificatesService.createCertificate( certificate { this.externalDuchyId = externalDuchyId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = revokeCertificateRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } val revokedCertificate = certificatesService.revokeCertificate(request) assertThat(revokedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(revokedCertificate.revocationState).isEqualTo(Certificate.RevocationState.REVOKED) } @Test fun `revokeCertificate for Duchy fails pending Measurements`(): Unit = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val measurementOne = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement one" ) val measurementTwo = population.createComputedMeasurement( measurementsService, measurementConsumer, "measurement two" ) measurementsService.cancelMeasurement( cancelMeasurementRequest { externalMeasurementConsumerId = measurementTwo.externalMeasurementConsumerId externalMeasurementId = measurementTwo.externalMeasurementId } ) val externalDuchyId = EXTERNAL_DUCHY_IDS[0] val certificate = certificatesService.createCertificate( certificate { this.externalDuchyId = externalDuchyId notValidBefore = clock.instant().minusSeconds(1000L).toProtoTime() notValidAfter = clock.instant().plusSeconds(1000L).toProtoTime() details = details { x509Der = X509_DER } } ) computationParticipantsService.setParticipantRequisitionParams( setParticipantRequisitionParamsRequest { this.externalDuchyId = externalDuchyId externalDuchyCertificateId = certificate.externalCertificateId externalComputationId = measurementOne.externalComputationId } ) val request = revokeCertificateRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } certificatesService.revokeCertificate(request) val measurements = measurementsService .streamMeasurements( streamMeasurementsRequest { filter = StreamMeasurementsRequestKt.filter { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId states += Measurement.State.FAILED } } ) .toList() assertThat(measurements) .comparingExpectedFieldsOnly() .containsExactly( measurement { state = Measurement.State.FAILED externalMeasurementId = measurementOne.externalMeasurementId details = measurementOne.details.copy { failure = MeasurementKt.failure { reason = Measurement.Failure.Reason.CERTIFICATE_REVOKED message = "An associated Duchy certificate has been revoked." } } } ) } @Test fun `revokeCertificate throws exception when requested state illegal`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } ) val request = revokeCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.HOLD } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.revokeCertificate(request) } assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION) } @Test fun `releaseCertificateHold throws INVALID_ARGUMENT when parent not specified`() = runBlocking { val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(releaseCertificateHoldRequest {}) } assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT) } @Test fun `releaseCertificateHold fails due to wrong DataProviderId`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = releaseCertificateHoldRequest { this.externalDataProviderId = 1234L // wrong externalDataProviderId externalCertificateId = certificate.externalCertificateId } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Certificate not found") } @Test fun `releaseCertificateHold fails due to revoked DataProviderCertificate`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } ) val request = releaseCertificateHoldRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(request) } assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION) assertThat(exception).hasMessageThat().contains("Certificate is in wrong State.") } @Test fun `releaseCertificateHold succeeds for DataProviderCertificate`() = runBlocking { val externalDataProviderId = population.createDataProvider(dataProvidersService).externalDataProviderId val certificate = certificatesService.createCertificate( certificate { this.externalDataProviderId = externalDataProviderId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.HOLD } ) val request = releaseCertificateHoldRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId } val releasedCertificate = certificatesService.releaseCertificateHold(request) assertThat(releasedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { this.externalDataProviderId = externalDataProviderId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(releasedCertificate.revocationState) .isEqualTo(Certificate.RevocationState.REVOCATION_STATE_UNSPECIFIED) } @Test fun `releaseCertificateHold fails due to wrong MeasurementConsumerId`() = runBlocking { val externalMeasurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId val certificate = certificatesService.createCertificate( certificate { this.externalMeasurementConsumerId = externalMeasurementConsumerId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = releaseCertificateHoldRequest { this.externalMeasurementConsumerId = 1234L // wrong externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Certificate not found") } @Test fun `releaseCertificateHold fails due to revoked measurementConsumersCertificate`() = runBlocking { val externalMeasurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId val certificate = certificatesService.createCertificate( certificate { this.externalMeasurementConsumerId = externalMeasurementConsumerId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalMeasurementConsumerId = externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.REVOKED } ) val request = releaseCertificateHoldRequest { this.externalMeasurementConsumerId = externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(request) } assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION) assertThat(exception).hasMessageThat().contains("Certificate is in wrong State.") } @Test fun `releaseCertificateHold succeeds for MeasurementConsumerCertificate`() = runBlocking { val externalMeasurementConsumerId = population .createMeasurementConsumer(measurementConsumersService, accountsService) .externalMeasurementConsumerId val certificate = certificatesService.createCertificate( certificate { this.externalMeasurementConsumerId = externalMeasurementConsumerId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalMeasurementConsumerId = externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.HOLD } ) val request = releaseCertificateHoldRequest { this.externalMeasurementConsumerId = externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId } val releasedCertificate = certificatesService.releaseCertificateHold(request) assertThat(releasedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { this.externalMeasurementConsumerId = externalMeasurementConsumerId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(releasedCertificate.revocationState) .isEqualTo(Certificate.RevocationState.REVOCATION_STATE_UNSPECIFIED) } @Test fun `releaseCertificateHold fails due to wrong DuchyId`() = runBlocking { val certificate = certificatesService.createCertificate( certificate { externalDuchyId = EXTERNAL_DUCHY_IDS[0] notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) val request = releaseCertificateHoldRequest { this.externalDuchyId = "non-existing-duchy-id" // wrong MeasurementConsumerId externalCertificateId = certificate.externalCertificateId } val exception = assertFailsWith<StatusRuntimeException> { certificatesService.releaseCertificateHold(request) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) assertThat(exception).hasMessageThat().contains("Duchy not found") } @Test fun `releaseCertificateHold succeeds for DuchyCertificate`() = runBlocking { val externalDuchyId = EXTERNAL_DUCHY_IDS[0] val certificate = certificatesService.createCertificate( certificate { this.externalDuchyId = externalDuchyId notValidBefore = Instant.ofEpochSecond(12345).toProtoTime() notValidAfter = Instant.ofEpochSecond(23456).toProtoTime() details = details { x509Der = X509_DER } } ) certificatesService.revokeCertificate( revokeCertificateRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId revocationState = Certificate.RevocationState.HOLD } ) val request = releaseCertificateHoldRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId } val releasedCertificate = certificatesService.releaseCertificateHold(request) assertThat(releasedCertificate) .isEqualTo( certificatesService.getCertificate( getCertificateRequest { this.externalDuchyId = externalDuchyId externalCertificateId = certificate.externalCertificateId } ) ) assertThat(releasedCertificate.revocationState) .isEqualTo(Certificate.RevocationState.REVOCATION_STATE_UNSPECIFIED) } }
apache-2.0
5cd76ac319f3ab8512acc0a9b06c773b
36.745506
117
0.739053
5.725746
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/magic/PackageMagic.kt
1
3004
package nl.hannahsten.texifyidea.util.magic import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.HVINDEX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.IDXLAYOUT import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.IMAKEIDX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.INDEX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.INDEXTOOLS import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.MAKEIDX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.MULTIND import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.REPEATINDEX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.SPLITIDX import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.SPLITINDEX object PackageMagic { /** * All unicode enabling packages. */ val unicode = hashSetOf( LatexPackage.INPUTENC.with("utf8"), LatexPackage.FONTENC.with("T1") ) /** * All known packages which provide an index. */ val index = hashSetOf( MAKEIDX, MULTIND, INDEX, SPLITIDX, SPLITINDEX, IMAKEIDX, HVINDEX, IDXLAYOUT, REPEATINDEX, INDEXTOOLS ) /** * Packages which provide a glossary. */ val glossary = hashSetOf(LatexPackage.GLOSSARIES, LatexPackage.GLOSSARIESEXTRA) /** * Known conflicting packages. */ val conflictingPackages = listOf( setOf(LatexPackage.BIBLATEX, LatexPackage.NATBIB) ) /** * Maps packages to the packages it loads. * Note that when a LaTeX SDK is available, then the relative inclusions are handled for all installed packages by [nl.hannahsten.texifyidea.index.file.LatexExternalPackageInclusionCache]. * This list is just there as a sort of default for those users who do not have LaTeX packages installed for example. */ val packagesLoadingOtherPackages: Map<LatexPackage, Set<LatexPackage>> = mapOf( LatexPackage.AMSSYMB to setOf(LatexPackage.AMSFONTS), LatexPackage.MATHTOOLS to setOf(LatexPackage.AMSMATH), LatexPackage.GRAPHICX to setOf(LatexPackage.GRAPHICS), LatexPackage.XCOLOR to setOf(LatexPackage.COLOR), LatexPackage.PDFCOMMENT to setOf(LatexPackage.HYPERREF), LatexPackage.ALGORITHM2E to setOf(LatexPackage.ALGPSEUDOCODE), // This is not true, but loading any of these two (incompatible) packages is sufficient as they provide the same commands (roughly) ) /** * Maps argument specifiers to whether they are required (true) or * optional (false). */ val xparseParamSpecifiers = mapOf( 'm' to true, 'r' to true, 'R' to true, 'v' to true, 'b' to true, 'o' to false, 'd' to false, 'O' to false, 'D' to false, 's' to false, 't' to false, 'e' to false, 'E' to false ) }
mit
b36e4777b640e368562894babe402fa9
38.025974
206
0.68775
4.372635
false
false
false
false
debop/debop4k
debop4k-data-kundera/src/test/kotlin/debop4k/data/kundera/examples/model/collection/BlogPost.kt
1
790
package debop4k.data.kundera.examples.model.collection import com.google.common.collect.Sets import com.impetus.kundera.index.Index import com.impetus.kundera.index.IndexCollection import debop4k.core.uninitialized import javax.persistence.* /** * BlogPost * @author debop * @since 2017. 2. 12. */ @Entity @Table(name = "blog_posts_kotlin") @IndexCollection(columns = arrayOf(Index(name = "body"), Index(name = "tags"))) class BlogPost { @Id @Column(name = "post_id") var postId: Int? = uninitialized() @Column(name = "body") var body: String? = uninitialized() @ElementCollection @Column(name = "tags") var tags: java.util.HashSet<String> = Sets.newHashSet() // var tags: MutableSet<String> = Sets.newHashSet() fun addTag(tag: String) { tags.add(tag) } }
apache-2.0
e7be0ef5d149d5cc2e8e644b7bc15d3a
22.264706
79
0.706329
3.172691
false
false
false
false
mustafaberkaymutlu/uv-index
autocomplete/src/main/java/net/epictimes/uvindex/autocomplete/AutoCompleteActivity.kt
1
5890
package net.epictimes.uvindex.autocomplete import android.app.Activity import android.content.Intent import android.location.Address import android.os.Bundle import android.os.Handler import android.os.ResultReceiver import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.view.Menu import android.widget.EditText import android.widget.Toast import kotlinx.android.synthetic.main.activity_auto_complete.* import net.epictimes.uvindex.Constants import net.epictimes.uvindex.ui.BaseViewStateActivity import timber.log.Timber import javax.inject.Inject class AutoCompleteActivity : BaseViewStateActivity<AutoCompleteView, AutoCompletePresenter, AutoCompleteViewState>(), AutoCompleteView { @Inject lateinit var autoCompletePresenter: AutoCompletePresenter @Inject lateinit var autoCompleteViewState: AutoCompleteViewState private val placesAdapter: PlacesRecyclerViewAdapter by lazy { PlacesRecyclerViewAdapter() } private val addressResultReceiver: AutoCompleteActivity.AddressResultReceiver by lazy { AddressResultReceiver() } override fun createPresenter(): AutoCompletePresenter = autoCompletePresenter override fun createViewState(): AutoCompleteViewState = autoCompleteViewState override fun onNewViewStateInstance() { // no-op } override fun onCreate(savedInstanceState: Bundle?) { DaggerAutoCompleteComponent.builder() .singletonComponent(singletonComponent) .build() .inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.activity_auto_complete) setSupportActionBar(toolbar) supportActionBar?.let { it.setDisplayHomeAsUpEnabled(true) it.setDisplayShowTitleEnabled(false) } with(recyclerViewPlaces) { layoutManager = LinearLayoutManager(this@AutoCompleteActivity) adapter = placesAdapter } toolbar.setNavigationOnClickListener { presenter.userClickedUp() } placesAdapter.rowClickListener = { address -> presenter.userSelectedAddress(address) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.autocomplete, menu) val searchView = menu.findItem(R.id.action_search).actionView as SearchView searchView.setQuery(viewState.searchQuery, false) makeSearchEditTextColorWhite(searchView) val handler = Handler() with(searchView) { setIconifiedByDefault(false) isFocusable = true maxWidth = Integer.MAX_VALUE requestFocusFromTouch() setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean = false override fun onQueryTextChange(s: String): Boolean { viewState.searchQuery = s handler.removeCallbacksAndMessages(null) handler.postDelayed({ presenter.userEnteredPlace(s) }, 500) return true } }) } return true } override fun displayAddresses(addresses: List<Address>) { Timber.d("received addresses: %s", addresses) placesAdapter.setAddresses(addresses) } override fun clearAddresses() { placesAdapter.clearAddresses() } override fun startFetchingAddress(place: String, maxResults: Int) { FetchAddressIntentService.startIntentService(context = this, resultReceiver = addressResultReceiver, locationName = place, maxResults = maxResults) } override fun goToQueryScreen() { finish() } override fun setSelectedAddress(address: Address?) { val intent = Intent() address?.let { intent.putExtra(Constants.BundleKeys.ADDRESS, address) setResult(RESULT_OK, intent) } ?: run { setResult(Activity.RESULT_CANCELED, intent) } } override fun displayPlaceFetchError(errorMessage: String) { Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show() } override fun onBackPressed() { presenter.userClickedBack() super.onBackPressed() } private fun makeSearchEditTextColorWhite(searchView: SearchView) { val searchEditText = searchView.findViewById<EditText>(android.support.v7.appcompat.R.id.search_src_text) val colorWhite = ContextCompat.getColor(this, android.R.color.white) with(searchEditText) { setTextColor(colorWhite) setHintTextColor(colorWhite) } } inner class AddressResultReceiver : ResultReceiver(Handler()) { override fun onReceiveResult(resultCode: Int, resultData: Bundle) { super.onReceiveResult(resultCode, resultData) val fetchResult = AddressFetchResult.values()[resultCode] val receivedErrorMessage: String? = resultData.getString(FetchAddressIntentService.KEY_ERROR_MESSAGE) val receivedAddresses = resultData.getParcelableArrayList<Address>(FetchAddressIntentService.KEY_RESULT) with(viewState) { addresses.addAll(receivedAddresses) addressState = fetchResult errorMessage = receivedErrorMessage } when (fetchResult) { AddressFetchResult.SUCCESS -> { presenter.userAddressReceived(receivedAddresses) } AddressFetchResult.FAIL -> { presenter.userAddressFetchFailed(receivedErrorMessage!!) } } } } }
apache-2.0
8b4116e3dd1a7f56bc5ab30f795eee6d
32.089888
117
0.667402
5.463822
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/views/viewer/video/InputStreamCacheDataSource.kt
1
3297
package com.pr0gramm.app.ui.views.viewer.video import android.net.Uri import com.google.android.exoplayer2.C import com.google.android.exoplayer2.upstream.BaseDataSource import com.google.android.exoplayer2.upstream.DataSpec import com.pr0gramm.app.io.Cache import com.pr0gramm.app.util.BoundedInputStream import com.pr0gramm.app.util.closeQuietly import java.io.BufferedInputStream import java.io.EOFException import java.io.InputStream /** * A data source that uses a Cache as a data source. */ internal class InputStreamCacheDataSource(private val cache: Cache) : BaseDataSource(true) { private var opened: Boolean = false private var _uri: Uri? = null private var inputStream: InputStream? = null private var bytesRemaining: Long = C.LENGTH_UNSET.toLong() override fun open(dataSpec: DataSpec): Long { _uri = dataSpec.uri transferInitializing(dataSpec) cache.get(dataSpec.uri).use { entry -> // get the input stream from the entry. val inputStream = entry.inputStreamAt(dataSpec.position.toInt()) this.inputStream = inputStream // gets the size of the file. This also initializes the cache entry. val totalSize = entry.totalSize.toLong() if (dataSpec.length == C.LENGTH_UNSET.toLong()) { this.bytesRemaining = totalSize - dataSpec.position } else { // limit amount to the requested length. this.inputStream = BoundedInputStream(inputStream, dataSpec.length) this.bytesRemaining = dataSpec.length } // reduce read calls to file this.inputStream = BufferedInputStream(this.inputStream, 1024 * 64) opened = true // everything looks fine, inform listeners about data transfer transferStarted(dataSpec) return bytesRemaining } } override fun close() { _uri = null if (inputStream != null) { inputStream.closeQuietly() inputStream = null } if (opened) { opened = false transferEnded() } } override fun read(buffer: ByteArray, offset: Int, readLength: Int): Int { if (readLength == 0) { return 0 } if (bytesRemaining == 0L) { return C.RESULT_END_OF_INPUT } val bytesToRead = if (bytesRemaining == C.LENGTH_UNSET.toLong()) readLength else Math.min(bytesRemaining, readLength.toLong()).toInt() // read from input stream val stream = inputStream ?: throw IllegalStateException("DataSource is not open.") val bytesTransferred = stream.read(buffer, offset, bytesToRead) if (bytesTransferred == -1) { if (bytesRemaining != C.LENGTH_UNSET.toLong()) { // End of stream reached having not read sufficient data. throw EOFException() } return C.RESULT_END_OF_INPUT } if (bytesRemaining != C.LENGTH_UNSET.toLong()) { bytesRemaining -= bytesTransferred.toLong() } bytesTransferred(bytesTransferred) return bytesTransferred } override fun getUri(): Uri? = _uri }
mit
fc068dce2c4b9a1333f904726d2a93ea
30.103774
92
0.621777
4.663366
false
true
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/darkroom/DarkRoomWrapper.kt
1
891
package me.ykrank.s1next.data.api.model.darkroom import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.JsonNode import me.ykrank.s1next.App import me.ykrank.s1next.util.JsonUtil class DarkRoomWrapper { @JsonIgnore var darkRooms: List<DarkRoom> = listOf() @JsonProperty("message") var message: DarkRoomMessage? = null @JsonIgnore var last: Boolean = false constructor() @JsonCreator constructor(@JsonProperty("data") d: JsonNode?) { if (d != null) { val rooms = mutableListOf<DarkRoom>() d.elements().forEach { rooms.add(JsonUtil.readJsonNode(App.preAppComponent.jsonMapper, it, DarkRoom::class.java)) } darkRooms = rooms } } }
apache-2.0
78afba2a1f36813e0cda6689b2edfbe3
27.774194
106
0.685746
4.105991
false
false
false
false
xamoom/xamoom-android-sdk
xamoomsdk/src/main/java/com/xamoom/android/xamoomsdk/PushDevice/PushDeviceUtil.kt
1
1703
package com.xamoom.android.xamoomsdk.PushDevice import android.content.SharedPreferences import android.location.Location class PushDeviceUtil(val preferences: SharedPreferences) { fun storeLocation(location: Location) { preferences.edit().putFloat("xamoom_push_device_lat", location.latitude.toFloat()).apply() preferences.edit().putFloat("xamoom_push_device_lon", location.longitude.toFloat()).apply() } fun storeToken(token: String) { preferences.edit().putString("xamoom_push_device_token", token).apply() } fun getSavedLocation(): Map<String, Float>? { val lat = preferences.getFloat("xamoom_push_device_lat", 0.0f) val lon = preferences.getFloat("xamoom_push_device_lon", 0.0f) if (lat == 0.0f || lon == 0.0f) { return null } return mapOf("lat" to lat, "lon" to lon) } fun getSavedToken(): String? { val token = preferences.getString("xamoom_push_device_token", "") if (token!!.isEmpty()) { return null } return token } fun setSound(sound: Boolean) { preferences.edit().putBoolean("xamoom_push_device_sound", sound).apply() } fun getSound(): Boolean { return preferences.getBoolean("xamoom_push_device_sound", true) } fun setNoNotification(noNotification: Boolean) { preferences.edit().putBoolean("xamoom_push_device_no_notification", noNotification).apply() } fun getNoNotification(): Boolean { return preferences.getBoolean("xamoom_push_device_no_notification", false) } companion object { const val PREFES_NAME = "push_device_util_preferences" } }
mit
15effc993818018b3dde9bfc10384b46
28.894737
99
0.648855
3.94213
false
false
false
false
FHannes/intellij-community
uast/uast-common/src/org/jetbrains/uast/evaluation/MapBasedEvaluationContext.kt
2
3061
/* * Copyright 2000-2017 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. */ package org.jetbrains.uast.evaluation import org.jetbrains.uast.* import org.jetbrains.uast.values.UUndeterminedValue import org.jetbrains.uast.visitor.UastVisitor import java.lang.ref.SoftReference import java.util.* class MapBasedEvaluationContext( override val uastContext: UastContext, override val extensions: List<UEvaluatorExtension> ) : UEvaluationContext { private val evaluators = WeakHashMap<UDeclaration, SoftReference<UEvaluator>>() override fun analyzeAll(file: UFile, state: UEvaluationState): UEvaluationContext { file.accept(object: UastVisitor { override fun visitElement(node: UElement) = false override fun visitMethod(node: UMethod): Boolean { analyze(node, state) return true } override fun visitVariable(node: UVariable): Boolean { if (node is UField) { analyze(node, state) return true } else return false } }) return this } private fun getOrCreateEvaluator(declaration: UDeclaration, state: UEvaluationState? = null) = evaluators[declaration]?.get() ?: createEvaluator(uastContext, extensions).apply { when (declaration) { is UMethod -> this.analyze(declaration, state ?: declaration.createEmptyState()) is UField -> this.analyze(declaration, state ?: declaration.createEmptyState()) } evaluators[declaration] = SoftReference(this) } override fun analyze(declaration: UDeclaration, state: UEvaluationState) = getOrCreateEvaluator(declaration, state) override fun getEvaluator(declaration: UDeclaration) = getOrCreateEvaluator(declaration) private fun getEvaluator(expression: UExpression): UEvaluator? { var containingElement = expression.uastParent while (containingElement != null) { if (containingElement is UDeclaration) { val evaluator = evaluators[containingElement]?.get() if (evaluator != null) { return evaluator } } containingElement = containingElement.uastParent } return null } override fun valueOf(expression: UExpression) = getEvaluator(expression)?.evaluate(expression) ?: UUndeterminedValue }
apache-2.0
1ca5e8e7450f26fdd5c6d322ec055f36
37.759494
119
0.654361
5.286701
false
false
false
false
B515/Schedule
app/src/main/kotlin/xyz/b515/schedule/ui/view/SettingsActivity.kt
1
3093
package xyz.b515.schedule.ui.view import android.os.Bundle import android.preference.* import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_pref.* import org.jetbrains.anko.browse import org.jetbrains.anko.startActivity import xyz.b515.schedule.BuildConfig import xyz.b515.schedule.R import xyz.b515.schedule.util.PackageHelper class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pref) fragmentManager.beginTransaction().replace(R.id.content, SettingsFragment()).commit() setSupportActionBar(settings_toolbar) settings_toolbar.setNavigationOnClickListener { onBackPressed() } } class SettingsFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_settings) val userNamePreference = findPreference("user") as EditTextPreference val psdNamePreference = findPreference("password") as EditTextPreference val versionPreference = findPreference("version") val splashScreenPreference = findPreference("splash_screen") as SwitchPreference val themePreference = findPreference("theme") val sourcePreference = findPreference("source") versionPreference.summary = BuildConfig.VERSION_NAME bindPreferenceSummaryToValue(userNamePreference) bindPreferenceSummaryToValue(psdNamePreference) splashScreenPreference.setOnPreferenceChangeListener { _, boo -> PackageHelper.changeMain(context, boo as Boolean) true } themePreference.setOnPreferenceClickListener { startActivity<ThemeActivity>() true } sourcePreference.setOnPreferenceClickListener { browse(getString(R.string.source_code_url)) true } } companion object { private val onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, newValue -> val value = newValue.toString() when { value.isEmpty() -> preference.setSummary(R.string.settings_empty) preference.key == "password" -> preference.setSummary(R.string.settings_password_mask) else -> preference.summary = value } true } private fun bindPreferenceSummaryToValue(preference: Preference) { preference.onPreferenceChangeListener = onPreferenceChangeListener onPreferenceChangeListener.onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")) } } } }
apache-2.0
a7e3d3b602b05d4c73a045fa6ebb78be
41.383562
116
0.651148
6.22334
false
false
false
false
NextFaze/dev-fun
devfun-annotations/src/main/java/com/nextfaze/devfun/inject/InstanceProvider.kt
1
7302
package com.nextfaze.devfun.inject import com.nextfaze.devfun.function.FunctionTransformer import kotlin.reflect.KClass /** * Provides object instances for one or more types. * * A rudimentary form of dependency injection is used throughout all of DevFun (not just for user-code function * invocation, but also between modules, definition and item processing, and anywhere else an object of some type is * desired - in general nothing in DevFun is static (except for the occasional `object`, but even then that is usually * an implementation and uses DI). * * This process is facilitated by various instance providers - most of which is described at the wiki entry on * [Dependency Injection](https://nextfaze.github.io/dev-fun/wiki/-dependency%20-injection.html). * * To quickly and simply provide a single object type, use [captureInstance] or [singletonInstance], which creates a * [CapturingInstanceProvider] that can be added to the root (composite) instance provider at `DevFun.instanceProviders`. * e.g. * ```kotlin * class SomeType : BaseType * * val provider = captureInstance { someObject.someType } // triggers for SomeType or BaseType * val singleInstance = singletonInstance { SomeType() } // triggers for SomeType or BaseType (result of invocation is saved) * ``` * * If you want to reduce the type range then specify its base type manually: * ```kotlin * val provider = captureInstance<BaseType> { someObject.someType } // triggers only for BaseType * ``` * * _Be aware of leaks! The lambda could implicitly hold a local `this` reference._ * * @see ThrowingInstanceProvider */ interface InstanceProvider { /** * Try to get an instance of some [clazz]. * * @return An instance of [clazz], or `null` if this provider can not handle the type * * @see ThrowingInstanceProvider.get */ operator fun <T : Any> get(clazz: KClass<out T>): T? } /** Same as [InstanceProvider], but throws [ClassInstanceNotFoundException] instead of returning `null`. */ interface ThrowingInstanceProvider : InstanceProvider { /** * Get an instance of some [clazz]. * * @return An instance of [clazz] * * @throws ClassInstanceNotFoundException When [clazz] could not be found/instantiated */ override operator fun <T : Any> get(clazz: KClass<out T>): T } /** Exception thrown when attempting to provide a type that was not found from any [InstanceProvider]. */ @Suppress("unused") class ClassInstanceNotFoundException : Exception { constructor(clazz: KClass<*>) : super( """ Failed to get instance of $clazz Are you using proguard? Add @Keep or adjust rules. Is it injected? Might need a custom instance provider. Or add @Constructable to the class to allow DevFun to attempt instantiation and injection of it.""".trimIndent() ) constructor(msg: String) : super(msg) constructor(cause: Exception) : super(cause) } /** * An instance provider that requests an instance of a class from a captured lambda. * * Be aware of leaks! The lambda could implicitly hold a local `this` reference. * * Be wary of using a `typealias` as a type - the resultant function "type" itself is used at compile time. * e.g. * ```kotlin * typealias MyStringAlias = () -> String? * val provider1 = captureInstance<MyStringAlias> { ... } * * typealias MyOtherAlias = () -> Type? * // will be triggered for MyStringAlias and MyOtherAlias since behind the scenes they are both kotlin.Function0<T> * val provider2 = captureInstance<MyOtherAlias> { ... } * ``` * * @see captureInstance */ class CapturingInstanceProvider<out T : Any>(private val instanceClass: KClass<T>, private val instance: () -> T?) : InstanceProvider { @Suppress("UNCHECKED_CAST") override fun <T : Any> get(clazz: KClass<out T>) = when { clazz.isSuperclassOf(instanceClass) -> instance() as T? else -> null } } /** * Utility function to capture an instance of an object. * * e.g. * ```kotlin * class SomeType : BaseType * * val provider = captureInstance { someObject.someType } // triggers for SomeType or BaseType * ``` * * If you want to reduce the type range then specify its base type manually: * ```kotlin * val provider = captureInstance<BaseType> { someObject.someType } // triggers only for BaseType * ``` * * Be wary of using a `typealias` as a type - the resultant function "type" itself is used at compile time. * e.g. * ```kotlin * typealias MyStringAlias = () -> String? * val provider1 = captureInstance<MyStringAlias> { ... } * * typealias MyOtherAlias = () -> Type? * // will be triggered for MyStringAlias and MyOtherAlias since behind the scenes they are both kotlin.Function0<T> * val provider2 = captureInstance<MyOtherAlias> { ... } * ``` * * @see singletonInstance * @see CapturingInstanceProvider */ inline fun <reified T : Any> captureInstance(noinline instance: () -> T?): InstanceProvider = CapturingInstanceProvider(T::class, instance) /** * Utility function to provide a single instance of some type. * * e.g. * ```kotlin * class SomeType : BaseType * * val provider = singletonInstance { SomeType() } // triggers for SomeType or BaseType (result of invocation is saved) * ``` * * If you want to reduce the type range then specify its base type manually: * ```kotlin * val provider = singletonInstance<BaseType> { SomeType() } // triggers only for BaseType (result of invocation is saved) * ``` * * Be wary of using a `typealias` as a type - the resultant function "type" itself is used at compile time. * e.g. * ```kotlin * typealias MyStringAlias = () -> String? * val provider1 = singletonInstance<MyStringAlias> { ... } * * typealias MyOtherAlias = () -> Type? * // will be triggered for MyStringAlias and MyOtherAlias since behind the scenes they are both kotlin.Function0<T> * val provider2 = singletonInstance<MyOtherAlias> { ... } * ``` * * @see captureInstance * @see CapturingInstanceProvider */ inline fun <reified T : Any> singletonInstance(noinline instance: () -> T?): InstanceProvider { val singleton: T? by lazy { instance() } return CapturingInstanceProvider(T::class) { singleton } } /** * Tag to allow classes to be instantiated when no other [InstanceProvider] was able to provide the class. * * The class must have only one constructor. Any arguments to the constructor will be injected as normal. * * In general this should not be used (you should be using your own dependency injection framework). * However for quick-n-dirty uses this can make life a bit easier (e.g. function transformers which are debug only anyway). * * Note: `inner` classes will work as long as the outer class can be resolved/injected.. * * Types annotated with `@javax.inject.Singleton` will only be created once. * * @param singleton If `true` then a single shared instance will be constructed. * Be careful when using this on inner classes as it will hold a reference to its outer class. * i.e. Only use this if the outer class is an object/singleton. * * @see FunctionTransformer */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Constructable(val singleton: Boolean = false)
apache-2.0
908fd03a1c7d3295e3c9d60af53c7bb1
38.258065
139
0.706656
4.043189
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/data/dao/SiteDao.kt
1
1524
package cc.aoeiuv020.panovel.data.dao import androidx.room.* import cc.aoeiuv020.panovel.data.entity.Site import java.util.* /** * Created by AoEiuV020 on 2018.05.24-14:20:59. */ @Dao abstract class SiteDao { @Query("select * from Site where hide = 0 order by pinnedTime desc, createTime desc, name asc") abstract fun list(): List<Site> @Query("select * from Site") abstract fun listAllSite(): List<Site> /** * 同步网站列表时删除已经不再支持的网站, */ @Delete abstract fun removeSite(site: Site) /** * 插入前都有查询,所以不用在插入失败时尝试更新, */ @Insert abstract fun insert(site: Site) @Query("update Site set enabled = :enabled where name = :name") abstract fun updateEnabled(name: String, enabled: Boolean) @Query("select * from Site where name = :name") abstract fun query(name: String): Site? @Query("select count(*) from Site where name = :name") abstract fun checkSiteSupport(name: String): Boolean @Query("update Site set baseUrl = :baseUrl, logo = :logo where name = :name") abstract fun updateSiteInfo(name: String, baseUrl: String, logo: String) @Query("update Site set pinnedTime = :pinnedTime where name = :name") abstract fun updatePinnedTime(name: String, pinnedTime: Date) @Query("update Site set hide = :hide where name = :name") abstract fun updateHide(name: String, hide: Boolean) @Update abstract fun updateSite(site: Site) }
gpl-3.0
78c240e91b9d28e8951fc494bf6e4d0a
27.254902
99
0.675
3.654822
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLRootQueryInfo.kt
1
2236
package net.nemerosa.ontrack.graphql.schema import graphql.schema.GraphQLFieldDefinition import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.graphql.support.GQLScalarLocalDateTime import net.nemerosa.ontrack.graphql.support.stringField import net.nemerosa.ontrack.model.structure.Info import net.nemerosa.ontrack.model.structure.InfoService import net.nemerosa.ontrack.model.structure.VersionInfo import org.springframework.stereotype.Component /** * Root `info` query to get information about the application. */ @Component class GQLRootQueryInfo( private val infoService: InfoService, private val gqlTypeInfo: GQLTypeInfo ) : GQLRootQuery { override fun getFieldDefinition(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("info") .description("Gets information about the application") .type(gqlTypeInfo.typeRef) .dataFetcher { infoService.info } .build() } @Component class GQLTypeInfo( private val gqlTypeVersionInfo: GQLTypeVersionInfo ) : GQLType { override fun getTypeName(): String = Info::class.java.simpleName override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Application information") .field { it.name(Info::version.name) .description("Version information") .type(gqlTypeVersionInfo.typeRef) } .build() } @Component class GQLTypeVersionInfo : GQLType { override fun getTypeName(): String = VersionInfo::class.java.simpleName override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Version information") .field { it.name(VersionInfo::date.name) .description("Creation date") .type(GQLScalarLocalDateTime.INSTANCE) } .stringField(VersionInfo::display, "Display version") .stringField(VersionInfo::full, "Full version") .stringField(VersionInfo::branch, "Git branch") .stringField(VersionInfo::commit, "Git commit") .build() }
mit
fecb2acfef98e53aa801628d1d293a1d
32.38806
99
0.700805
4.968889
false
false
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/pagination/PaginatedListExtensions.kt
1
1283
package net.nemerosa.ontrack.model.pagination typealias Seed<T> = (offset: Int, size: Int) -> Pair<Int, List<T>> /** * Computes a paginated list over several collections in turn. * * @param T Type of item in the lists * @param offset Overall offset * @param size Size for a page */ fun <T> spanningPaginatedList( offset: Int, size: Int, seeds: Collection<Seed<T>>, ): PaginatedList<T> { // Total count collected so far var total = 0 // Sliding offset var slidingOffset = offset // Total list val result = mutableListOf<T>() // For each seed seeds.forEach { seed -> // While the list size does not exceed the page size if (slidingOffset >= 0 && result.size < size) { // How much do we need to collect still? val leftOver = size - result.size // Sliding the offset slidingOffset = maxOf(0, slidingOffset - total) // Total count and items for THIS seed val (count, items) = seed(slidingOffset, leftOver) // Completing the total total += count // Completing the collection result += items } } // Getting the final page return PaginatedList.create(result, offset, size, total) }
mit
6e9f4b0e0c6433845198d7f6b4d35eda
28.860465
66
0.604832
4.234323
false
false
false
false
goodwinnk/intellij-community
platform/lang-impl/src/com/intellij/execution/compound/CompoundRunConfiguration.kt
1
7812
// 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.execution.compound import com.intellij.execution.* import com.intellij.execution.configurations.* import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.impl.RunManagerImpl import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl import com.intellij.execution.impl.compareTypesForUi import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.icons.AllIcons import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import gnu.trove.THashSet import org.jdom.Element import java.util.* import javax.swing.Icon internal data class TypeNameTarget(val type: String, val name: String, val targetId: String?) data class SettingsAndEffectiveTarget(val settings: RunnerAndConfigurationSettings, val target: ExecutionTarget) class CompoundRunConfiguration @JvmOverloads constructor(project: Project, name: String, factory: ConfigurationFactory = runConfigurationType<CompoundRunConfigurationType>()) : RunConfigurationBase(project, factory, name), RunnerIconProvider, WithoutOwnBeforeRunSteps, Cloneable { companion object { @JvmField internal val COMPARATOR: Comparator<RunConfiguration> = Comparator { o1, o2 -> val compareTypeResult = compareTypesForUi(o1.type, o2.type) if (compareTypeResult == 0) o1.name.compareTo(o2.name) else compareTypeResult } } // we cannot compute setToRun on read because we need type.displayName to sort, but to get type we need runManager - it is prohibited to get runManager in the readExternal private var unsortedConfigurations: List<TypeNameTarget> = emptyList() // have to use RunConfiguration instead of RunnerAndConfigurationSettings because setConfigurations (called from CompoundRunConfigurationSettingsEditor.applyEditorTo) cannot use RunnerAndConfigurationSettings private var sortedConfigurationsWithTargets = TreeMap<RunConfiguration, ExecutionTarget?>(COMPARATOR) private var isInitialized = false fun getConfigurationsWithTargets(runManager: RunManagerImpl): Map<RunConfiguration, ExecutionTarget?> { initIfNeed(runManager) return sortedConfigurationsWithTargets } fun setConfigurationsWithTargets(value: Map<RunConfiguration, ExecutionTarget?>) { markInitialized() sortedConfigurationsWithTargets.clear() sortedConfigurationsWithTargets.putAll(value) } fun setConfigurationsWithoutTargets(value: Collection<RunConfiguration>) { setConfigurationsWithTargets(value.associate { it to null }) } private fun initIfNeed(runManager: RunManagerImpl) { if (isInitialized) { return } sortedConfigurationsWithTargets.clear() val targetManager = ExecutionTargetManager.getInstance(project) as ExecutionTargetManagerImpl for ((type, name, targetId) in unsortedConfigurations) { val settings = runManager.findConfigurationByTypeAndName(type, name) if (settings != null && settings.configuration !== this) { val target = targetId?.let { targetManager.findTargetByIdFor(settings, it) } sortedConfigurationsWithTargets.put(settings.configuration, target) } } markInitialized() } private fun markInitialized() { unsortedConfigurations = emptyList() isInitialized = true } override fun getConfigurationEditor() = CompoundRunConfigurationSettingsEditor(project) override fun checkConfiguration() { if (sortedConfigurationsWithTargets.isEmpty()) { throw RuntimeConfigurationException("There is nothing to run") } val temp = RunnerAndConfigurationSettingsImpl(RunManagerImpl.getInstanceImpl(project), this) if (ExecutionTargetManager.getInstance(project).getTargetsFor(temp).isEmpty()) { throw RuntimeConfigurationException("No suitable targets to run on; please choose a target for each configuration") } } override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? { try { checkConfiguration() } catch (e: RuntimeConfigurationException) { throw ExecutionException(e.message) } promptUserToUseRunDashboard( project, getConfigurationsWithEffectiveRunTargets().map { it.settings.configuration.type } ) return RunProfileState { _, _ -> ApplicationManager.getApplication().invokeLater { val groupId = ExecutionEnvironment.getNextUnusedExecutionId() for ((settings, target) in getConfigurationsWithEffectiveRunTargets()) { ExecutionUtil.runConfiguration(settings, executor, target, groupId) } } null } } fun getConfigurationsWithEffectiveRunTargets(): List<SettingsAndEffectiveTarget> { val runManager = RunManagerImpl.getInstanceImpl(project) val activeTarget = ExecutionTargetManager.getActiveTarget(project) val defaultTarget = DefaultExecutionTarget.INSTANCE return sortedConfigurationsWithTargets.mapNotNull { (configuration, specifiedTarget) -> runManager.getSettings(configuration)?.let { val effectiveTarget = specifiedTarget ?: if (ExecutionTargetManager.canRun(it, activeTarget)) activeTarget else defaultTarget SettingsAndEffectiveTarget(it, effectiveTarget) } } } override fun readExternal(element: Element) { super.readExternal(element) val children = element.getChildren("toRun") if (children.isEmpty()) { unsortedConfigurations = emptyList() return } val list = THashSet<TypeNameTarget>() for (child in children) { val type = child.getAttributeValue("type") ?: continue val name = child.getAttributeValue("name") ?: continue list.add(TypeNameTarget(type, name, child.getAttributeValue("targetId"))) } unsortedConfigurations = list.toList() } override fun writeExternal(element: Element) { super.writeExternal(element) for ((configuration, target) in sortedConfigurationsWithTargets) { val child = Element("toRun") child.setAttribute("type", configuration.type.id) child.setAttribute("name", configuration.name) target?.let { child.setAttribute("targetId", it.id) } element.addContent(child) } } override fun clone(): RunConfiguration { val clone = super<RunConfigurationBase>.clone() as CompoundRunConfiguration clone.unsortedConfigurations = unsortedConfigurations clone.sortedConfigurationsWithTargets = TreeMap(COMPARATOR) clone.sortedConfigurationsWithTargets.putAll(sortedConfigurationsWithTargets) return clone } override fun getExecutorIcon(configuration: RunConfiguration, executor: Executor): Icon? { return if (DefaultRunExecutor.EXECUTOR_ID == executor.id && hasRunningSingletons()) { AllIcons.Actions.Restart } else executor.icon } private fun hasRunningSingletons(): Boolean { val project = project if (project.isDisposed) { return false } return ExecutionManagerImpl.getInstance(project).getRunningDescriptors { s -> val manager = RunManagerImpl.getInstanceImpl(project) for ((configuration, _) in sortedConfigurationsWithTargets) { if (configuration is CompoundRunConfiguration && configuration.hasRunningSingletons()) { return@getRunningDescriptors true } val settings = manager.findSettings(configuration) if (settings != null && !settings.configuration.isAllowRunningInParallel && configuration == s.configuration) { return@getRunningDescriptors true } } false }.isNotEmpty() } }
apache-2.0
8c3cb10e58a8afad01d6c15b83c807a9
38.06
210
0.756016
5.176938
false
true
false
false
CherepanovAleksei/BinarySearchTree
src/app.kt
1
1309
import RBTree.RedBlackTree import RBTree.logic import RBTree.RBNode /** * Created by [email protected] */ fun main(array: Array<String>) { //var bst=BinarySearchTree() val bst = RedBlackTree<Int, String>() var flagKV: Boolean = false var key: Int? = 0 var value: String? = null while (true) { val input = readLine() when (input) { "-f" -> { print("Key to found: ") if (bst.search(readLine()!!.toInt()) != null) println("Key found") else println("Key not found") } "-p" -> { for (i in bst) { logic<Int, String>().display(i) } } "-d" -> { println("Key to delete: ") bst.delete(readLine()!!.toInt()) } "-q" -> return else -> { if (flagKV) { if (input != null) value = input.toString() //val newNode = RBNode(key!!, value!!) bst.insert(key!!, value!!) flagKV = false } else { key = input?.toIntOrNull() if (key != null) flagKV = true } } } } }
mit
3e2bb2a68887523c1713f53d81c6e0ac
26.87234
82
0.411765
4.452381
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityDialog.kt
1
4451
package com.tamsiree.rxdemo.activity import android.os.Bundle import android.view.LayoutInflater import android.widget.ImageView import com.tamsiree.rxdemo.R import com.tamsiree.rxkit.RxBarTool.noTitle import com.tamsiree.rxkit.RxBarTool.setTransparentStatusBar import com.tamsiree.rxkit.RxDeviceTool.setPortrait import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.dialog.* import kotlinx.android.synthetic.main.activity_dialog.* /** * @author tamsiree */ class ActivityDialog : ActivityBase() { private var mRxDialogDate: RxDialogDate? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) noTitle(this) setContentView(R.layout.activity_dialog) setTransparentStatusBar(this) setPortrait(this) } override fun initView() { rx_title.setLeftFinish(mContext) button_tran.setOnClickListener { val rxDialog = RxDialog(mContext, R.style.tran_dialog) val view1 = LayoutInflater.from(mContext).inflate(R.layout.image, null) val pageItem = view1.findViewById<ImageView>(R.id.page_item) pageItem.setImageResource(R.drawable.coin) rxDialog.setContentView(view1) rxDialog.show() } button_DialogSure.setOnClickListener { //提示弹窗 val rxDialogSure = RxDialogSure(mContext) rxDialogSure.logoView.setImageResource(R.drawable.logo) rxDialogSure.sureView.setOnClickListener { rxDialogSure.cancel() } rxDialogSure.show() } button_DialogSureCancle.setOnClickListener { //提示弹窗 val rxDialogSureCancel = RxDialogSureCancel(mContext) rxDialogSureCancel.titleView.setBackgroundResource(R.drawable.logo) rxDialogSureCancel.sureView.setOnClickListener { rxDialogSureCancel.cancel() } rxDialogSureCancel.cancelView.setOnClickListener { rxDialogSureCancel.cancel() } rxDialogSureCancel.show() } button_DialogEditTextSureCancle.setOnClickListener { //提示弹窗 val rxDialogEditSureCancel = RxDialogEditSureCancel(mContext) rxDialogEditSureCancel.titleView.setBackgroundResource(R.drawable.logo) rxDialogEditSureCancel.sureView.setOnClickListener { rxDialogEditSureCancel.cancel() } rxDialogEditSureCancel.cancelView.setOnClickListener { rxDialogEditSureCancel.cancel() } rxDialogEditSureCancel.show() } button_DialogWheelYearMonthDay.setOnClickListener { if (mRxDialogDate == null) { initWheelYearMonthDayDialog() } mRxDialogDate!!.show() } button_DialogShapeLoading.setOnClickListener { val rxDialogShapeLoading = RxDialogShapeLoading(this) rxDialogShapeLoading.show() } button_DialogLoadingProgressAcfunVideo.setOnClickListener { RxDialogAcfunVideoLoading(this).show() } button_DialogLoadingspinkit.setOnClickListener { val rxDialogLoading = RxDialogLoading(mContext) rxDialogLoading.show() } button_DialogScaleView.setOnClickListener { val rxDialogScaleView = RxDialogScaleView(mContext) rxDialogScaleView.setImage("squirrel.jpg", true) rxDialogScaleView.show() } } override fun initData() { } private fun initWheelYearMonthDayDialog() { // ------------------------------------------------------------------选择日期开始 mRxDialogDate = RxDialogDate(this, 1994) mRxDialogDate?.sureView?.setOnClickListener { if (mRxDialogDate?.checkBoxDay?.isChecked!!) { button_DialogWheelYearMonthDay.text = (mRxDialogDate?.selectorYear.toString() + "年" + mRxDialogDate?.selectorMonth + "月" + mRxDialogDate?.selectorDay + "日") } else { button_DialogWheelYearMonthDay.text = (mRxDialogDate?.selectorYear.toString() + "年" + mRxDialogDate?.selectorMonth + "月") } mRxDialogDate!!.cancel() } mRxDialogDate?.cancleView?.setOnClickListener { mRxDialogDate?.cancel() } // ------------------------------------------------------------------选择日期结束 } }
apache-2.0
52bcf530b2eedf53d0a6096951fa29f8
40.065421
108
0.643296
4.633966
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/colorpicker/ColorPickerPreference.kt
1
5633
package com.tamsiree.rxui.view.colorpicker import android.content.Context import android.content.DialogInterface import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.preference.Preference import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.widget.ImageView import com.tamsiree.rxui.R import com.tamsiree.rxui.view.colorpicker.ColorPickerView.WHEEL_TYPE import com.tamsiree.rxui.view.colorpicker.ColorPickerView.WHEEL_TYPE.Companion.indexOf import com.tamsiree.rxui.view.colorpicker.builder.ColorPickerClickListener import com.tamsiree.rxui.view.colorpicker.builder.ColorPickerDialogBuilder /** * @author tamsiree * @date 2018/6/11 11:36:40 整合修改 */ class ColorPickerPreference : Preference { protected var alphaSlider = false protected var lightSlider = false protected var selectedColor = 0 protected var wheelType: WHEEL_TYPE? = null protected var density = 0 protected var colorIndicator: ImageView? = null private var pickerTitle: String? = null private var pickerButtonCancel: String? = null private var pickerButtonOk: String? = null constructor(context: Context?) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initWith(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initWith(context, attrs) } private fun initWith(context: Context, attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorPickerPreference) try { alphaSlider = typedArray.getBoolean(R.styleable.ColorPickerPreference_alphaSlider, false) lightSlider = typedArray.getBoolean(R.styleable.ColorPickerPreference_lightnessSlider, false) density = typedArray.getInt(R.styleable.ColorPickerPreference_density, 10) wheelType = indexOf(typedArray.getInt(R.styleable.ColorPickerPreference_wheelType, 0)) selectedColor = typedArray.getInt(R.styleable.ColorPickerPreference_initialColor, -0x1) pickerTitle = typedArray.getString(R.styleable.ColorPickerPreference_pickerTitle) if (pickerTitle == null) { pickerTitle = "Choose color" } pickerButtonCancel = typedArray.getString(R.styleable.ColorPickerPreference_pickerButtonCancel) if (pickerButtonCancel == null) { pickerButtonCancel = "cancel" } pickerButtonOk = typedArray.getString(R.styleable.ColorPickerPreference_pickerButtonOk) if (pickerButtonOk == null) { pickerButtonOk = "ok" } } finally { typedArray.recycle() } widgetLayoutResource = R.layout.color_widget } override fun onBindView(view: View) { super.onBindView(view) val res = view.context.resources var colorChoiceDrawable: GradientDrawable? = null colorIndicator = view.findViewById<View>(R.id.color_indicator) as ImageView val currentDrawable = colorIndicator!!.drawable if (currentDrawable != null && currentDrawable is GradientDrawable) { colorChoiceDrawable = currentDrawable } if (colorChoiceDrawable == null) { colorChoiceDrawable = GradientDrawable() colorChoiceDrawable.shape = GradientDrawable.OVAL } val tmpColor = if (isEnabled) selectedColor else darken(selectedColor, .5f) colorChoiceDrawable.setColor(tmpColor) colorChoiceDrawable.setStroke(TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 1f, res.displayMetrics ).toInt(), darken(tmpColor, .8f)) colorIndicator!!.setImageDrawable(colorChoiceDrawable) } fun setValue(value: Int) { if (callChangeListener(value)) { selectedColor = value persistInt(value) notifyChanged() } } override fun onSetInitialValue(restoreValue: Boolean, defaultValue: Any) { setValue((if (restoreValue) getPersistedInt(0) else defaultValue as Int)) } override fun onClick() { val builder = ColorPickerDialogBuilder .with(context) .setTitle(pickerTitle) .initialColor(selectedColor) .wheelType(wheelType) .density(density) .setPositiveButton(pickerButtonOk, object : ColorPickerClickListener { override fun onClick(d: DialogInterface?, lastSelectedColor: Int, allColors: Array<Int?>?) { setValue(lastSelectedColor) } }) .setNegativeButton(pickerButtonCancel, null) if (!alphaSlider && !lightSlider) { builder.noSliders() } else if (!alphaSlider) { builder.lightnessSliderOnly() } else if (!lightSlider) { builder.alphaSliderOnly() } builder .build() .show() } companion object { fun darken(color: Int, factor: Float): Int { val a = Color.alpha(color) val r = Color.red(color) val g = Color.green(color) val b = Color.blue(color) return Color.argb(a, Math.max((r * factor).toInt(), 0), Math.max((g * factor).toInt(), 0), Math.max((b * factor).toInt(), 0)) } } }
apache-2.0
9e8dedf2bbc67f3611b92a57c831f13d
39.47482
113
0.647467
4.742833
false
false
false
false
uchuhimo/kotlin-playground
konf/src/test/kotlin/com/uchuhimo/konf/ConfigGenerateDocSpec.kt
1
6458
package com.uchuhimo.konf import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.dsl.xgiven import org.jetbrains.spek.subject.SubjectSpek object ConfigGenerateDocSpec : SubjectSpek<Config>({ val spec = NetworkBuffer subject { Config { addSpec(spec) } } xgiven("a config") { group("generate doc") { val complexConfig by memoized { subject.apply { addSpec(object : ConfigSpec("disk.file") { val size = optional("size", 1024, description = "size of disk file") }) } } on("generate Java properties doc") { it("generate doc in correct format") { println(complexConfig.generatePropertiesDoc()) } } on("generate HOCON doc") { it("generate doc in correct format") { println(complexConfig.generateHoconDoc()) } } on("generate YAML doc") { it("generate doc in correct format") { println(complexConfig.generateYamlDoc()) } } on("generate TOML doc") { it("generate doc in correct format") { println(complexConfig.generateTomlDoc()) } } on("generate XML doc") { it("generate doc in correct format") { println(complexConfig.generateXmlDoc()) } } } } }) private fun generateItemDoc( item: Item<*>, key: String = item.name, separator: String = " = ", encode: (Any) -> String ): String = StringBuilder().apply { item.description.lines().forEach { line -> appendln("# $line") } if (item is LazyItem) { appendln("# default: ${item.placeholder}") } append(key) append(separator) if (item is OptionalItem) { append(encode(item.default)) } appendln() }.toString() fun Config.generatePropertiesDoc(): String = StringBuilder().apply { for (item in this@generatePropertiesDoc) { append(generateItemDoc(item, encode = Any::toString)) appendln() } }.toString() private fun encodeAsHocon(value: Any): String = when (value) { is Int -> value.toString() is String -> "\"$value\"" is Enum<*> -> "\"${value.name}\"" else -> value.toString() } fun Config.generateHoconDoc(): String = StringBuilder().apply { toTree.visit( onEnterPath = { node -> val path = node.path if (path.isNotEmpty()) { append(" ".repeat(4 * (path.size - 1))) appendln("${path.last()} {") } }, onLeavePath = { node -> val path = node.path if (path.isNotEmpty()) { append(" ".repeat(4 * (path.size - 1))) appendln("}") } }, onEnterItem = { node -> val path = node.path val item = node.item generateItemDoc( item, key = item.path.last(), encode = ::encodeAsHocon ).lines().forEach { line -> append(" ".repeat(4 * (path.size - 1))) append(line) appendln() } } ) }.toString() fun Config.generateYamlDoc(): String = StringBuilder().apply { toTree.visit( onEnterPath = { node -> val path = node.path if (path.size >= 1) { append(" ".repeat(4 * (path.size - 1))) appendln("${path.last()}:") } }, onEnterItem = { node -> val item = node.item val path = node.path generateItemDoc( item, key = item.path.last(), separator = ": ", encode = ::encodeAsHocon ).lines().forEach { line -> append(" ".repeat(4 * (path.size - 1))) append(line) appendln("") } } ) }.toString() fun Config.generateTomlDoc(): String = StringBuilder().apply { specs.forEach { spec -> appendln("[${spec.prefix}]") spec.items.forEach { item -> append(generateItemDoc(item, key = item.path.last(), encode = ::encodeAsHocon)) appendln() } } }.toString() fun Config.generateXmlDoc(): String = StringBuilder().apply { appendln("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") appendln("<configuration>") for (item in this@generateXmlDoc) { appendln(" <property>") appendln(" <name>${item.name}</name>") append(" <value>") if (item is OptionalItem) { append(item.default.toString()) } else if (item is LazyItem) { append("<!-- ${item.placeholder} -->") } appendln("</value>") appendln(" <description>") item.description.lines().forEach { line -> appendln(" $line") } appendln(" </description>") appendln(" </property>") } appendln("</configuration>") }.toString()
apache-2.0
9040412c391c7212e9bb1b7d77b7b813
34.483516
99
0.40384
5.543348
false
true
false
false
marcelgross90/Cineaste
app/src/main/kotlin/de/cineaste/android/database/dao/EpisodeDao.kt
1
4806
package de.cineaste.android.database.dao import android.content.ContentValues import android.content.Context import de.cineaste.android.entity.series.Episode class EpisodeDao private constructor(context: Context) : BaseDao(context) { fun executeCustomSql(sql: String) { writeDb.execSQL(sql) } fun create(episode: Episode) { val values = ContentValues() values.put(EpisodeEntry.ID, episode.id) values.put(EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER, episode.episodeNumber) values.put(EpisodeEntry.COLUMN_EPISODE_NAME, episode.name) values.put(EpisodeEntry.COLUMN_EPISODE_DESCRIPTION, episode.description) values.put(EpisodeEntry.COLUMN_EPISODE_SEASON_ID, episode.seasonId) values.put(EpisodeEntry.COLUMN_EPISODE_WATCHED, if (episode.isWatched) 1 else 0) writeDb.insert( EpisodeEntry.TABLE_NAME, null, values ) } fun create(episode: Episode, seriesId: Long, seasonId: Long) { val values = ContentValues() values.put(EpisodeEntry.ID, episode.id) values.put(EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER, episode.episodeNumber) values.put(EpisodeEntry.COLUMN_EPISODE_NAME, episode.name) values.put(EpisodeEntry.COLUMN_EPISODE_DESCRIPTION, episode.description) values.put(EpisodeEntry.COLUMN_EPISODE_SERIES_ID, seriesId) values.put(EpisodeEntry.COLUMN_EPISODE_SEASON_ID, seasonId) values.put(EpisodeEntry.COLUMN_EPISODE_WATCHED, if (episode.isWatched) 1 else 0) writeDb.insert(EpisodeEntry.TABLE_NAME, null, values) } fun read(selection: String, selectionArgs: Array<String>): List<Episode> { val episodes = ArrayList<Episode>() val projection = arrayOf( EpisodeEntry.ID, EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER, EpisodeEntry.COLUMN_EPISODE_NAME, EpisodeEntry.COLUMN_EPISODE_DESCRIPTION, EpisodeEntry.COLUMN_EPISODE_SERIES_ID, EpisodeEntry.COLUMN_EPISODE_SEASON_ID, EpisodeEntry.COLUMN_EPISODE_WATCHED ) val c = readDb.query( EpisodeEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER + " ASC", null ) if (c.moveToFirst()) { do { val currentEpisode = Episode() currentEpisode.id = c.getLong(c.getColumnIndexOrThrow(EpisodeEntry.ID)) currentEpisode.episodeNumber = c.getInt(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER)) currentEpisode.name = c.getString(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_NAME)) currentEpisode.description = c.getString(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_DESCRIPTION)) currentEpisode.seriesId = c.getLong(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_SERIES_ID)) currentEpisode.seasonId = c.getLong(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_SEASON_ID)) currentEpisode.isWatched = c.getInt(c.getColumnIndexOrThrow(EpisodeEntry.COLUMN_EPISODE_WATCHED)) > 0 episodes.add(currentEpisode) } while (c.moveToNext()) } c.close() return episodes } fun update(episode: Episode) { val values = ContentValues() values.put(EpisodeEntry.ID, episode.id) values.put(EpisodeEntry.COLUMN_EPISODE_EPISODE_NUMBER, episode.episodeNumber) values.put(EpisodeEntry.COLUMN_EPISODE_NAME, episode.name) values.put(EpisodeEntry.COLUMN_EPISODE_DESCRIPTION, episode.description) values.put(EpisodeEntry.COLUMN_EPISODE_SERIES_ID, episode.seriesId) values.put(EpisodeEntry.COLUMN_EPISODE_SEASON_ID, episode.seasonId) values.put(EpisodeEntry.COLUMN_EPISODE_WATCHED, if (episode.isWatched) 1 else 0) val selection = EpisodeEntry.ID + " LIKE ?" val selectionArgs = arrayOf(episode.id.toString()) writeDb.update(EpisodeEntry.TABLE_NAME, values, selection, selectionArgs) } fun deleteBySeriesId(seriesId: Long) { writeDb.delete( EpisodeEntry.TABLE_NAME, EpisodeEntry.COLUMN_EPISODE_SERIES_ID + " = ?", arrayOf(seriesId.toString() + "") ) } companion object { private var instance: EpisodeDao? = null fun getInstance(context: Context): EpisodeDao { if (instance == null) { instance = EpisodeDao(context) } return instance!! } } }
gpl-3.0
03c15a59ce9aed5dcd2d29dd45c9366c
38.393443
97
0.645443
4.458256
false
false
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/fetch/internal/DownloadUtils.kt
1
3313
/* * Copyright (C) 2022 panpf <[email protected]> * * 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.github.panpf.sketch.fetch.internal import com.github.panpf.sketch.fetch.HttpUriFetcher import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.internal.ProgressListenerDelegate import com.github.panpf.sketch.util.getMimeTypeFromUrl import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.isActive import java.io.IOException import java.io.InputStream import java.io.OutputStream @Throws(IOException::class, CancellationException::class) internal fun copyToWithActive( request: ImageRequest, inputStream: InputStream, outputStream: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE, coroutineScope: CoroutineScope, contentLength: Long, ): Long { var bytesCopied = 0L val buffer = ByteArray(bufferSize) var bytes = inputStream.read(buffer) var lastNotifyTime = 0L val progressListenerDelegate = request.progressListener?.let { ProgressListenerDelegate(coroutineScope, it) } var lastUpdateProgressBytesCopied = 0L while (bytes >= 0 && coroutineScope.isActive) { outputStream.write(buffer, 0, bytes) bytesCopied += bytes if (progressListenerDelegate != null && contentLength > 0) { val currentTime = System.currentTimeMillis() if ((currentTime - lastNotifyTime) > 300) { lastNotifyTime = currentTime val currentBytesCopied = bytesCopied lastUpdateProgressBytesCopied = currentBytesCopied progressListenerDelegate.onUpdateProgress( request, contentLength, currentBytesCopied ) } } bytes = inputStream.read(buffer) } if (coroutineScope.isActive) { if (progressListenerDelegate != null && contentLength > 0 && lastUpdateProgressBytesCopied != bytesCopied ) { progressListenerDelegate.onUpdateProgress(request, contentLength, bytesCopied) } } else { throw CancellationException() } return bytesCopied } /** * Parse the response's `content-type` header. * * "text/plain" is often used as a default/fallback MIME type. * Attempt to guess a better MIME type from the file extension. */ internal fun getMimeType(url: String, contentType: String?): String? { if (contentType == null || contentType.isEmpty() || contentType.isBlank()) { return getMimeTypeFromUrl(url) } return if (contentType.startsWith(HttpUriFetcher.MIME_TYPE_TEXT_PLAIN)) { getMimeTypeFromUrl(url) } else { null } ?: contentType.substringBefore(';') }
apache-2.0
97763c4ad115409cb27d117e34b6e354
35.406593
90
0.69997
4.773775
false
false
false
false
zathras/misc
playground/stream_server/src/main/kotlin/ReversingServerStatePattern.kt
1
6653
import java.net.InetSocketAddress import java.nio.ByteBuffer import java.nio.channels.SelectionKey import java.nio.channels.Selector import java.nio.channels.ServerSocketChannel import java.nio.channels.SocketChannel /** * Implements a server on port 7777 that reverses each line it gets. * The server uses one thread, but can service multiple clients * simultaneously. It uses the "raw" nio classes and the state pattern. * This is intended to illustrate what coroutines (and futures) * conceptually do "under the hood." */ object ReversingServerStatePattern { class Reverser : () -> Unit { private var state : State private val readBuffer: ByteBuffer private val writeBuffer: ByteBuffer private val line = StringBuffer() private val selector : Selector private val socket : SocketChannel constructor(selector: Selector, socket: SocketChannel) { this.selector = selector socket.configureBlocking(false) readBuffer = ByteBuffer.allocate(4) writeBuffer = ByteBuffer.allocate(5) this.socket = socket this.state = READING } fun start() = state.register(this) interface State : (Reverser) -> Unit { fun running() : Boolean fun register(reverser: Reverser) } companion object { val READING : State = object : State { override fun running() = false override fun register(reverser: Reverser) { reverser.socket.register(reverser.selector, SelectionKey.OP_READ, reverser) } override fun invoke(reverser: Reverser) { with(reverser) { assert(readBuffer.hasRemaining()) val result = socket.read(readBuffer) if (result == -1) { // Discard any pending buffered output socket.close() state = CLOSED return } readBuffer.flip() state = PROCESSING_READ } } } val PROCESSING_READ : State = object : State { override fun running() = true override fun register(reverser: Reverser) { } override fun invoke(reverser: Reverser) { with(reverser) { while (readBuffer.hasRemaining()) { val ch = readBuffer.get().toChar() line.append(ch) println("Received $ch") if (ch == '\r' || ch == '\n') { state = PROCESSING_WRITE return } } readBuffer.clear() state = READING } } } val PROCESSING_WRITE : State = object : State { override fun running() = true override fun register(reverser: Reverser) { } override fun invoke(reverser: Reverser) { with (reverser) { if (line.isEmpty()) { state = PROCESSING_READ // In case read buffer has more return } while (!line.isEmpty() && writeBuffer.hasRemaining()) { val i = if (line.length == 1) 0 else line.lastIndex - 1 val ch = line.get(i) // avoid EOLN until end line.deleteCharAt(i) println("writing $ch") writeBuffer.put(ch.toByte()) } writeBuffer.flip() state = WRITING return } } } val WRITING : State = object : State { override fun running() = false override fun register(reverser: Reverser) { reverser.socket.register(reverser.selector, SelectionKey.OP_WRITE, reverser) } override fun invoke(reverser: Reverser) { with (reverser) { val result = socket.write(writeBuffer) if (result == -1) { socket.close() state = CLOSED return } if (!writeBuffer.hasRemaining()) { writeBuffer.clear() state = PROCESSING_WRITE } } } } val CLOSED : State = object : State { override fun running() = false override fun register(reverser: Reverser) = Unit override fun invoke(reverser: Reverser) = Unit } } override fun invoke() { try { do { state(this) } while (state.running()) state.register(this) } catch (ex : Exception) { ex.printStackTrace() socket.close() } } } val selector = Selector.open() private fun acceptConnection(ssChannel: ServerSocketChannel) { val socket: SocketChannel = ssChannel.accept() println("Accepted $socket") val r = Reverser(selector, socket) r.start() } fun run() { val ssChannel = ServerSocketChannel.open() ssChannel.configureBlocking(false) ssChannel.bind(InetSocketAddress(7777)) val ssKey = ssChannel.register(selector, SelectionKey.OP_ACCEPT, { acceptConnection(ssChannel) }) while (true) { println("Selecting from ${selector.keys()}...") selector.select() println("Selected.") val selected = selector.selectedKeys() for (key in selector.selectedKeys()) { println(key == ssKey) @Suppress("UNCHECKED_CAST") val task = key.attachment() as () -> Unit task() } selected.clear() } } }
mit
d20632942634cefeb2af63c687b0a25b
34.015789
96
0.460093
5.581376
false
false
false
false
doerfli/hacked
app/src/main/kotlin/li/doerf/hacked/ui/adapters/BreachedSitesAdapter.kt
1
6372
package li.doerf.hacked.ui.adapters import android.content.Context import android.text.Html import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Picasso import io.reactivex.processors.PublishProcessor import li.doerf.hacked.HackedApplication import li.doerf.hacked.R import li.doerf.hacked.db.entities.BreachedSite import li.doerf.hacked.util.NavEvent import org.joda.time.format.DateTimeFormat class BreachedSitesAdapter( val context: Context, private var myBreachedSites: List<BreachedSite>, private val compactView: Boolean) : RecyclerView.Adapter<RecyclerViewHolder>() { private lateinit var navEvents: PublishProcessor<NavEvent> override fun onViewAttachedToWindow(holder: RecyclerViewHolder) { super.onViewAttachedToWindow(holder) navEvents = (context as HackedApplication).navEvents } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder { if (compactView) { val itemLayout = LayoutInflater.from(parent.context) .inflate(R.layout.card_breached_site_compact, parent, false) return RecyclerViewHolder(itemLayout) } val itemLayout = LayoutInflater.from(parent.context) .inflate(R.layout.card_breached_site, parent, false) return RecyclerViewHolder(itemLayout) } override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) { val site = myBreachedSites[position] val view = holder.view if (compactView) { bindCompactView(view, site) } else { bindFullView(view, site) } } private fun bindFullView(siteCard: View, site: BreachedSite) { val nameView = siteCard.findViewById<TextView>(R.id.site_name) nameView.text = site.title val pwnCountView = siteCard.findViewById<TextView>(R.id.pwn_count) pwnCountView.text = String.format(context.resources.configuration.locale, "(%,d)", site.pwnCount) val details = siteCard.findViewById<RelativeLayout>(R.id.breach_details) val arrowDown = siteCard.findViewById<ImageView>(R.id.arrow_down) val arrowUp = siteCard.findViewById<ImageView>(R.id.arrow_up) if (! site.detailsVisible) { siteCard.setBackgroundColor(context.resources.getColor(android.R.color.white)) details.visibility = View.GONE arrowDown.visibility = View.VISIBLE arrowUp.visibility = View.GONE } else { siteCard.setBackgroundColor(context.resources.getColor(R.color.selectedCard)) details.visibility = View.VISIBLE arrowDown.visibility = View.GONE arrowUp.visibility = View.VISIBLE val domain = siteCard.findViewById<TextView>(R.id.domain) domain.text = site.domain val dtfOut = DateTimeFormat.forPattern("yyyy/MM/dd") val breachDate = siteCard.findViewById<TextView>(R.id.breach_date) breachDate.text = dtfOut.print(site.breachDate) val compromisedData = siteCard.findViewById<TextView>(R.id.compromised_data) compromisedData.text = site.dataClasses val description = siteCard.findViewById<TextView>(R.id.description) description.text = Html.fromHtml(site.description).toString() val logoView = siteCard.findViewById<ImageView>(R.id.logo) if (site.logoPath != null && site.logoPath.isNotEmpty()) { logoView.visibility = View.VISIBLE Picasso.get().load(site.logoPath).into(logoView) } else { logoView.visibility = View.GONE } } val additionalFlagsLabel: View = siteCard.findViewById<View>(R.id.label_additional_flags) val additionalFlags: TextView = siteCard.findViewById<TextView>(R.id.additional_flags) if (site.hasAdditionalFlags()) { additionalFlagsLabel.visibility = View.VISIBLE additionalFlags.visibility = View.VISIBLE additionalFlags.setText(getFlags(site)) } else { additionalFlagsLabel.visibility = View.GONE additionalFlags.visibility = View.GONE } siteCard.setOnClickListener { site.detailsVisible = ! site.detailsVisible notifyDataSetChanged() } } private fun bindCompactView(card: View, site: BreachedSite) { val nameView = card.findViewById<TextView>(R.id.site_name) nameView.text = site.title getFlags(site) val pwnCountView = card.findViewById<TextView>(R.id.pwn_count) pwnCountView.text = String.format(context.resources.configuration.locale, "(%,d)", site.pwnCount) card.setOnClickListener { _ -> navEvents.onNext(NavEvent(NavEvent.Destination.ALL_BREACHES, site.id, null)) } } private fun getFlags(site: BreachedSite): String? { val flags = StringBuilder() if (!site.verified) { Log.d("BreachedSitesAdapter", "unverified: " + site.name) flags.append(context.getString(R.string.unverified)).append(" ") } if (site.fabricated) { Log.d("BreachedSitesAdapter", "fabricated: " + site.name) flags.append(context.getString(R.string.fabricated)).append(" ") } if (site.retired) { Log.d("BreachedSitesAdapter", "retired: " + site.name) flags.append(context.getString(R.string.retired)).append(" ") } if (site.sensitive) { Log.d("BreachedSitesAdapter", "sensitive: " + site.name) flags.append(context.getString(R.string.sensitive)).append(" ") } if (site.spamList) { Log.d("BreachedSitesAdapter", "spam_list: " + site.name) flags.append(context.getString(R.string.spam_list)).append(" ") } return flags.toString() } override fun getItemCount(): Int { return myBreachedSites.size } fun addItems(list: List<BreachedSite>) { myBreachedSites = list notifyDataSetChanged() } }
apache-2.0
9571a7aaf3286536798e49d37feb6359
38.339506
159
0.659448
4.328804
false
false
false
false
stripe/stripe-android
paymentsheet-example/src/main/java/com/stripe/android/paymentsheet/example/playground/activity/AppearanceBottomSheetDialogFragment.kt
1
24385
package com.stripe.android.paymentsheet.example.playground.activity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.Divider import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Remove import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.rememberNestedScrollInteropConnection import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.godaddy.android.colorpicker.ClassicColorPicker import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.example.R private val BASE_FONT_SIZE = 20.sp private val BASE_PADDING = 8.dp private val SECTION_LABEL_COLOR = Color(159, 159, 169) internal class AppearanceBottomSheetDialogFragment : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setContent { AppearancePicker( currentAppearance = AppearanceStore.state, updateAppearance = { AppearanceStore.state = it }, ) } } } companion object { fun newInstance(): AppearanceBottomSheetDialogFragment { return AppearanceBottomSheetDialogFragment() } } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun AppearancePicker( currentAppearance: PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { val scrollState = rememberScrollState() val nestedScrollConnection = rememberNestedScrollInteropConnection() Scaffold( topBar = { TopAppBar( title = { Text("Appearance") }, actions = { TextButton(onClick = AppearanceStore::reset) { Text(text = stringResource(R.string.reset)) } }, backgroundColor = MaterialTheme.colors.surface, contentColor = MaterialTheme.colors.onSurface, ) }, modifier = Modifier .systemBarsPadding() .nestedScroll(nestedScrollConnection), ) { padding -> Column( modifier = Modifier .padding(padding) .verticalScroll(scrollState) ) { Spacer(modifier = Modifier.height(16.dp)) CustomizationCard("Colors") { Colors( currentAppearance = currentAppearance, updateAppearance = updateAppearance, ) } CustomizationCard("Shapes") { Shapes( currentAppearance = currentAppearance, updateAppearance = updateAppearance, ) } CustomizationCard("Typography") { Typography( currentAppearance = currentAppearance, updateAppearance = updateAppearance, ) } CustomizationCard("PrimaryButton") { PrimaryButton( currentAppearance = currentAppearance, updateAppearance = updateAppearance, ) } Spacer(modifier = Modifier.height(16.dp)) } } } @Composable private fun CustomizationCard( label: String, content: @Composable () -> Unit ) { Column( modifier = Modifier.padding(horizontal = 16.dp), ) { Text( text = label, fontSize = 24.sp, color = SECTION_LABEL_COLOR, modifier = Modifier.padding(vertical = BASE_PADDING) ) Card( backgroundColor = Color.White, elevation = 2.dp, ) { Column { content() } } } } @Composable private fun Colors( currentAppearance: PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { ColorItem( label = "primary", currentColor = Color(currentAppearance.colorsLight.primary), onColorPicked = { color -> currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( primary = color.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( primary = color.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "surface", currentColor = Color(currentAppearance.colorsLight.surface), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( surface = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( surface = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "component", currentColor = Color(currentAppearance.colorsLight.component), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( component = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( component = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "componentBorder", currentColor = Color(currentAppearance.colorsLight.componentBorder), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( componentBorder = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( componentBorder = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "componentDivider", currentColor = Color(currentAppearance.colorsLight.componentDivider), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( componentDivider = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( componentDivider = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "onComponent", currentColor = Color(currentAppearance.colorsLight.onComponent), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( onComponent = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( onComponent = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "onSurface", currentColor = Color(currentAppearance.colorsLight.onSurface), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( onSurface = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( onSurface = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "subtitle", currentColor = Color(currentAppearance.colorsLight.subtitle), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( subtitle = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( subtitle = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "placeholderText", currentColor = Color(currentAppearance.colorsLight.placeholderText), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( placeholderText = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( placeholderText = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "appBarIcon", currentColor = Color(currentAppearance.colorsLight.appBarIcon), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( appBarIcon = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( appBarIcon = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "error", currentColor = Color(currentAppearance.colorsLight.error), onColorPicked = { currentAppearance.copy( colorsLight = currentAppearance.colorsLight.copy( error = it.toArgb() ), colorsDark = currentAppearance.colorsDark.copy( error = it.toArgb() ) ) }, updateAppearance = updateAppearance, ) } @Composable private fun Shapes( currentAppearance: PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { IncrementDecrementItem("cornerRadiusDp", currentAppearance.shapes.cornerRadiusDp) { updateAppearance( currentAppearance.copy( shapes = currentAppearance.shapes.copy( cornerRadiusDp = it ) ) ) } Divider() IncrementDecrementItem("borderStrokeWidthDp", currentAppearance.shapes.borderStrokeWidthDp) { updateAppearance( currentAppearance.copy( shapes = currentAppearance.shapes.copy( borderStrokeWidthDp = it ) ) ) } } @Composable private fun Typography( currentAppearance: PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { FontScaleSlider(currentAppearance.typography.sizeScaleFactor) { updateAppearance( currentAppearance.copy( typography = currentAppearance.typography.copy( sizeScaleFactor = it ) ) ) } Divider() FontDropDown(currentAppearance.typography.fontResId) { updateAppearance( currentAppearance.copy( typography = currentAppearance.typography.copy( fontResId = it ) ) ) } } @Composable private fun PrimaryButton( currentAppearance: PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { val currentButton = currentAppearance.primaryButton val currentBackground = currentButton.colorsLight.background?.let { Color(it) } ?: run { Color(currentAppearance.colorsLight.primary) } ColorItem( label = "background", currentColor = currentBackground, onColorPicked = { currentAppearance.copy( primaryButton = currentButton.copy( colorsLight = currentButton.colorsLight.copy( background = it.toArgb() ), colorsDark = currentButton.colorsDark.copy( background = it.toArgb() ) ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "onBackground", currentColor = Color(currentButton.colorsLight.onBackground), onColorPicked = { currentAppearance.copy( primaryButton = currentButton.copy( colorsLight = currentButton.colorsLight.copy( onBackground = it.toArgb() ), colorsDark = currentButton.colorsDark.copy( onBackground = it.toArgb() ) ) ) }, updateAppearance = updateAppearance, ) Divider() ColorItem( label = "border", currentColor = Color(currentButton.colorsLight.border), onColorPicked = { currentAppearance.copy( primaryButton = currentButton.copy( colorsLight = currentButton.colorsLight.copy( border = it.toArgb() ), colorsDark = currentButton.colorsDark.copy( border = it.toArgb() ) ) ) }, updateAppearance = updateAppearance, ) val currentCornerRadius = currentButton.shape.cornerRadiusDp ?: currentAppearance.shapes.cornerRadiusDp Divider() IncrementDecrementItem("cornerRadiusDp", currentCornerRadius) { updateAppearance( currentAppearance.copy( primaryButton = currentButton.copy( shape = currentButton.shape.copy( cornerRadiusDp = it ) ) ) ) } val currentBorderStrokeWidth = currentButton.shape.borderStrokeWidthDp ?: currentAppearance.shapes.borderStrokeWidthDp Divider() IncrementDecrementItem("borderStrokeWidthDp", currentBorderStrokeWidth) { updateAppearance( currentAppearance.copy( primaryButton = currentButton.copy( shape = currentButton.shape.copy( borderStrokeWidthDp = it ) ) ) ) } val currentFontSize = currentButton.typography.fontSizeSp ?: (currentAppearance.typography.sizeScaleFactor * 16) Divider() IncrementDecrementItem("fontSizeSp", currentFontSize) { updateAppearance( currentAppearance.copy( primaryButton = currentButton.copy( typography = currentButton.typography.copy( fontSizeSp = it ) ) ) ) } val currentFontFamily = currentButton.typography.fontResId ?: currentAppearance.typography.fontResId Divider() FontDropDown(currentFontFamily) { updateAppearance( currentAppearance.copy( primaryButton = currentButton.copy( typography = currentButton.typography.copy( fontResId = it ) ) ) ) } } @Composable private fun ColorItem( label: String, currentColor: Color, onColorPicked: (Color) -> PaymentSheet.Appearance, updateAppearance: (PaymentSheet.Appearance) -> Unit, ) { val openDialog = remember { mutableStateOf(false) } ColorPicker(openDialog, currentColor) { updateAppearance(onColorPicked(it)) } Row( modifier = Modifier .fillMaxWidth() .padding(all = BASE_PADDING) .clickable { openDialog.value = true }, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text(text = label, fontSize = BASE_FONT_SIZE) ColorIcon(innerColor = currentColor) } } @Composable private fun ColorPicker( openDialog: MutableState<Boolean>, defaultColor: Color, onClose: (Color) -> Unit, ) { val currentColor = remember { mutableStateOf(defaultColor) } if (openDialog.value) { AlertDialog( onDismissRequest = { openDialog.value = false onClose(currentColor.value) }, text = { ClassicColorPicker( modifier = Modifier.fillMaxSize(), onColorChanged = { currentColor.value = it.toColor() } ) }, buttons = { Button( modifier = Modifier .fillMaxWidth() .padding(all = BASE_PADDING), colors = ButtonDefaults.buttonColors(backgroundColor = currentColor.value), onClick = { openDialog.value = false onClose(currentColor.value) } ) { Text(text = "Pick Color") } } ) } } @Composable private fun ColorIcon(innerColor: Color) { val brush = Brush.verticalGradient( listOf( Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Magenta ) ) Box( modifier = Modifier .border(BorderStroke(3.dp, brush), CircleShape) ) { Box( modifier = Modifier .size(32.dp) .clip(CircleShape) .background(Color.Transparent) ) Box( modifier = Modifier .size(20.dp) .clip(CircleShape) .background(innerColor) .align(Alignment.Center) ) } } @Composable private fun IncrementDecrementItem(label: String, value: Float, onValueChange: (Float) -> Unit) { Row( modifier = Modifier .fillMaxWidth() .padding(all = BASE_PADDING), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text(text = "$label: $value", fontSize = BASE_FONT_SIZE) Row { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .height(32.dp) .width(50.dp) .clickable { val newValue = value - 1 onValueChange(if (newValue < 0) 0.0f else newValue) } ) { Icon( imageVector = Icons.Rounded.Remove, contentDescription = null, ) } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .height(32.dp) .width(50.dp) .clickable { onValueChange(value + 1) } ) { Icon( imageVector = Icons.Rounded.Add, contentDescription = null, ) } } } } @Composable private fun FontScaleSlider(sliderPosition: Float, onValueChange: (Float) -> Unit) { Text( text = "sizeScaleFactor: $sliderPosition", fontSize = BASE_FONT_SIZE, modifier = Modifier.padding(horizontal = BASE_PADDING) ) Slider( value = sliderPosition, valueRange = 0f..2f, onValueChange = { onValueChange(it) } ) } @Composable private fun FontDropDown(fontResId: Int?, fontSelectedCallback: (Int?) -> Unit) { var expanded by remember { mutableStateOf(false) } val items = mapOf( R.font.cursive to "Cursive", R.font.opensans to "OpenSans", null to "Default" ) items[fontResId]?.let { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxSize() .padding(all = BASE_PADDING) .wrapContentSize(Alignment.TopStart) ) { Text( text = "Font Resource: $it", fontFamily = getFontFromResource(fontResId), fontSize = BASE_FONT_SIZE, modifier = Modifier .fillMaxWidth() .clickable(onClick = { expanded = true }) ) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier.fillMaxWidth() ) { items.forEach { font -> FontDropDownMenuItem(label = font.value, fontResId = font.key) { expanded = false fontSelectedCallback(font.key) } } } } } } @Composable private fun FontDropDownMenuItem(label: String, fontResId: Int?, onClick: () -> Unit) { DropdownMenuItem( onClick = onClick, ) { Text( text = label, fontFamily = getFontFromResource(fontResId) ) } } private fun getFontFromResource(fontResId: Int?): FontFamily { return fontResId?.let { FontFamily(Font(it)) } ?: run { FontFamily.Default } }
mit
0ad56cfef6af0c33a5c219553e589f7d
31.043364
97
0.567603
5.411673
false
false
false
false
congwiny/KotlinBasic
src/main/kotlin/function/varargs.kt
1
1130
package function /** * 可变数量的参数(Varargs) */ fun main(args: Array<String>) { val b = arrayOf("b", "c", "d") hello(*b) val a = arrayOf(1, 2, 3) /** * 当我们调用 vararg-函数时,我们可以一个接一个地传参,例如 asList(1, 2, 3), * 或者,如果我们已经有一个数组并希望将其内容传给该函数, * 我们使用伸展(spread)操作符(在数组前面加 *) */ val list = asList(-1, 0, *a, 4) //允许将可变数量的参数传递给函数 println(list) //[-1, 0, 1, 2, 3, 4] /** * 可以通过使用星号操作符将可变数量参数(vararg) 以命名形式传入: */ val list2 = asList(ts = *a) println(list2) //[1, 2, 3] } /** * 函数的参数(通常是最后一个)可以用 vararg 修饰符标记: */ fun <T> asList(vararg ts: T): List<T> { val result = ArrayList<T>() for (t in ts) // ts is an Array(ts变量具有类型 Array<out T>) result.add(t) return result } fun hello(vararg args: String) { for (obj in args) { println(obj) } }
apache-2.0
9421a02a20e9609dc9c6ff1b55be61e9
19.575
58
0.551095
2.417647
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/ComposeExampleActivity.kt
1
6953
package com.stripe.example.activity import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Divider import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.stripe.android.model.Address import com.stripe.android.model.ConfirmPaymentIntentParams import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.payments.paymentlauncher.PaymentLauncher import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.example.R import com.stripe.example.Settings import com.stripe.example.module.StripeIntentViewModel /** * An Activity to demonstrate [PaymentLauncher] with Jetpack Compose. */ class ComposeExampleActivity : AppCompatActivity() { private val viewModel: StripeIntentViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeScreen() } } @Composable fun ComposeScreen() { val inProgress by viewModel.inProgress.observeAsState(false) val status by viewModel.status.observeAsState("") val paymentLauncher = rememberPaymentLauncher() ComposeScreen( inProgress = inProgress, status = status, onConfirm = { paymentLauncher.confirm(it) } ) } @Composable private fun ComposeScreen( inProgress: Boolean, status: String, onConfirm: (ConfirmPaymentIntentParams) -> Unit ) { Column(modifier = Modifier.padding(horizontal = 10.dp)) { if (inProgress) { LinearProgressIndicator( modifier = Modifier.fillMaxWidth() ) } Text( stringResource(R.string.payment_auth_intro), modifier = Modifier.padding(vertical = 5.dp) ) ConfirmButton( params = confirmParams3ds1, buttonName = R.string.confirm_with_3ds1_button, onConfirm = onConfirm, inProgress = inProgress ) ConfirmButton( params = confirmParams3ds2, buttonName = R.string.confirm_with_3ds2_button, onConfirm = onConfirm, inProgress = inProgress ) Divider(modifier = Modifier.padding(vertical = 5.dp)) Text(text = status) } } /** * Create [PaymentLauncher] in a [Composable] */ @Composable private fun rememberPaymentLauncher(): PaymentLauncher { val context = LocalContext.current val settings = remember { Settings(context) } return PaymentLauncher.rememberLauncher( publishableKey = settings.publishableKey, stripeAccountId = settings.stripeAccountId, callback = ::onPaymentResult ) } private fun onPaymentResult(paymentResult: PaymentResult) { when (paymentResult) { is PaymentResult.Completed -> { viewModel.status.value += "\n\nPaymentIntent confirmation succeeded\n\n" viewModel.inProgress.value = false } is PaymentResult.Canceled -> { viewModel.status.value += "\n\nPaymentIntent confirmation cancelled\n\n" viewModel.inProgress.value = false } is PaymentResult.Failed -> { viewModel.status.value += "\n\nPaymentIntent confirmation failed with " + "throwable ${paymentResult.throwable} \n\n" viewModel.inProgress.value = false } } } @Composable private fun ConfirmButton( params: PaymentMethodCreateParams, @StringRes buttonName: Int, inProgress: Boolean, onConfirm: (ConfirmPaymentIntentParams) -> Unit ) { Button( onClick = { createAndConfirmPaymentIntent(params, onConfirm) }, modifier = Modifier .fillMaxWidth() .padding(vertical = 5.dp), enabled = !inProgress ) { Text(stringResource(buttonName)) } } private fun createAndConfirmPaymentIntent( params: PaymentMethodCreateParams, onConfirm: (ConfirmPaymentIntentParams) -> Unit ) { viewModel.createPaymentIntent("us").observe( this ) { it.onSuccess { responseData -> val confirmPaymentIntentParams = ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams( paymentMethodCreateParams = params, clientSecret = responseData.getString("secret"), shipping = SHIPPING ) onConfirm(confirmPaymentIntentParams) } } } private companion object { /** * See https://stripe.com/docs/payments/3d-secure#three-ds-cards for more options. */ private val confirmParams3ds2 = PaymentMethodCreateParams.create( PaymentMethodCreateParams.Card.Builder() .setNumber("4000000000003238") .setExpiryMonth(1) .setExpiryYear(2025) .setCvc("123") .build() ) private val confirmParams3ds1 = PaymentMethodCreateParams.create( PaymentMethodCreateParams.Card.Builder() .setNumber("4000000000003063") .setExpiryMonth(1) .setExpiryYear(2025) .setCvc("123") .build() ) private val SHIPPING = ConfirmPaymentIntentParams.Shipping( address = Address.Builder() .setCity("San Francisco") .setCountry("US") .setLine1("123 Market St") .setLine2("#345") .setPostalCode("94107") .setState("CA") .build(), name = "Jenny Rosen", carrier = "Fedex", trackingNumber = "12345" ) } }
mit
007a992dcf5ab644bdbc243e91488083
34.116162
90
0.606932
5.41933
false
false
false
false
jitsi/ice4j
src/test/kotlin/org/ice4j/ice/harvest/StaticMappingCandidateHarvesterTest.kt
1
6631
/* * Copyright @ 2020 - present 8x8, 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. */ import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import org.ice4j.Transport import org.ice4j.TransportAddress import org.ice4j.ice.Component import org.ice4j.ice.HostCandidate import org.ice4j.ice.ServerReflexiveCandidate import org.ice4j.ice.harvest.StaticMappingCandidateHarvester import org.jitsi.utils.logging2.createLogger class StaticMappingCandidateHarvesterTest : ShouldSpec() { override fun isolationMode(): IsolationMode = IsolationMode.InstancePerLeaf val component = mockk<Component>() init { val hostCandidate1 = createHostCandidate("10.0.0.1", 10000) val hostCandidate2 = createHostCandidate("10.0.0.111", 10000) val hostCandidate3 = createHostCandidate("10.0.0.1", 11111) val srflxCandidate1 = mockk<ServerReflexiveCandidate>().apply { every { hostAddress } returns ta("10.10.0.1", 22222) } val srflxCandidate2 = mockk<ServerReflexiveCandidate>().apply { every { hostAddress } returns ta("192.168.0.1", 1234) } component.apply { every { logger } returns createLogger() every { componentID } returns Component.RTP every { localCandidates } returns listOf( hostCandidate1, hostCandidate2, hostCandidate3, srflxCandidate1, srflxCandidate2 ) every { addLocalCandidate(any()) } returns true } val publicHostname = "192.168.255.255" context("Harvesting without matching port") { val harvester = StaticMappingCandidateHarvester( face = ta("10.0.0.1", 10000), mask = ta(publicHostname, 20000), matchPort = false ) context("publicAddressMatches") { harvester.publicAddressMatches(ta(publicHostname, 1234)) shouldBe true harvester.publicAddressMatches(ta(publicHostname, 10000)) shouldBe true harvester.publicAddressMatches(ta(publicHostname, 20000)) shouldBe true harvester.publicAddressMatches(ta("192.168.1.1", 20000)) shouldBe false } val candidatesAdded = harvester.harvest(component) should("Add a candidate corresponding to hostCandidate1") { val addedCandidate = candidatesAdded.find { it.base == hostCandidate1 }!! addedCandidate.transportAddress shouldBe ta(publicHostname, hostCandidate1.transportAddress.port) } should("Not add a candidate corresponding to hostCandidate2 (hostname does not match)") { candidatesAdded.find { it.base == hostCandidate2 } shouldBe null } should("Add a candidate corresponding to hostCandidate3") { val addedCandidate = candidatesAdded.find { it.base == hostCandidate3 }!! addedCandidate.transportAddress shouldBe ta(publicHostname, hostCandidate3.transportAddress.port) } should("Not add a candidate corresponding to any of the srflx candidateS (they are not HostCandidate)") { candidatesAdded.find { it.base == srflxCandidate1 } shouldBe null candidatesAdded.find { it.base == srflxCandidate2 } shouldBe null } should("Not add any other candidates") { candidatesAdded.size shouldBe 2 } } context("Harvesting with matching port") { val publicPort = 33333 val harvester = StaticMappingCandidateHarvester( face = ta("10.0.0.1", 10000), mask = ta(publicHostname, publicPort), matchPort = true ) context("publicAddressMatches") { harvester.publicAddressMatches(ta(publicHostname, 1234)) shouldBe false harvester.publicAddressMatches(ta(publicHostname, 10000)) shouldBe false harvester.publicAddressMatches(ta(publicHostname, 20000)) shouldBe false harvester.publicAddressMatches(ta(publicHostname, publicPort)) shouldBe true harvester.publicAddressMatches(ta("192.168.1.1", 20000)) shouldBe false } val candidatesAdded = harvester.harvest(component) should("Add a candidate corresponding to hostCandidate1") { val addedCandidate = candidatesAdded.find { it.base == hostCandidate1 }!! addedCandidate.transportAddress shouldBe ta(publicHostname, publicPort) } should("Not add a candidate corresponding to hostCandidate2 (hostname does not match)") { candidatesAdded.find { it.base == hostCandidate2 } shouldBe null } should("Not add a candidate corresponding to hostCandidate3 (port does not match)") { candidatesAdded.find { it.base == hostCandidate3 } shouldBe null } should("Not add a candidate corresponding to any of the srflx candidateS (they are not HostCandidate)") { candidatesAdded.find { it.base == srflxCandidate1 } shouldBe null candidatesAdded.find { it.base == srflxCandidate2 } shouldBe null } should("Not add any other candidates") { candidatesAdded.size shouldBe 1 } } } private fun createHostCandidate(hostname: String, port: Int) = mockk<HostCandidate>().apply { val localAddress = ta(hostname, port) every { hostAddress } returns localAddress every { transportAddress } returns localAddress every { transport } returns localAddress.transport every { stunServerAddress } returns null every { parentComponent } returns component every { isSSL } returns false } } /** Create a UDP TransportAddress */ private fun ta(hostname: String, port: Int) = TransportAddress(hostname, port, Transport.UDP)
apache-2.0
9806e8a22bab94acebd00304e4e4acf6
46.705036
117
0.652843
4.604861
false
false
false
false
AndroidX/androidx
compose/ui/ui-graphics/src/androidAndroidTest/kotlin/androidx/compose/ui/graphics/AndroidMatrixTest.kt
3
5161
/* * Copyright 2020 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.ui.graphics import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertTrue private const val delta = 0.01f @SmallTest @RunWith(AndroidJUnit4::class) class AndroidMatrixTest { @Test fun rotate90() { val point = FloatArray(2) val m = Matrix() m.rotateZ(90f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(0f) p.mapPoints(point, floatArrayOf(100f, 100f)) assertThat(point[0]).isWithin(delta).of(-100f) assertThat(point[1]).isWithin(delta).of(100f) val composeMatrix = Matrix().apply { setFrom(p) } assertTrue(composeMatrix.values.contentEquals(m.values)) } @Test fun rotate30() { val point = FloatArray(2) val m = Matrix() m.rotateZ(30f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(0f) p.mapPoints(point, floatArrayOf(100f, 0f)) assertThat(point[0]).isWithin(delta).of(86.602540378f) assertThat(point[1]).isWithin(delta).of(50f) val composeMatrix = Matrix().apply { setFrom(p) } assertTrue(composeMatrix.values.contentEquals(m.values)) } @Test fun translateX() { val point = FloatArray(2) val m = Matrix() m.translate(10f, 0f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(10f) assertThat(point[1]).isWithin(delta).of(0f) p.mapPoints(point, floatArrayOf(100f, 100f)) assertThat(point[0]).isWithin(delta).of(110f) assertThat(point[1]).isWithin(delta).of(100f) val composeMatrix = Matrix().apply { setFrom(p) } assertTrue(composeMatrix.values.contentEquals(m.values)) } @Test fun translateY() { val point = FloatArray(2) val m = Matrix() m.translate(0f, 10f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(10f) p.mapPoints(point, floatArrayOf(100f, 100f)) val message = "Matrix:\n$m\nPlatform:\n$p" assertWithMessage(message).that(point[0]).isWithin(delta).of(100f) assertWithMessage(message).that(point[1]).isWithin(delta).of(110f) m.translate(0f, 10f) val q = android.graphics.Matrix().apply { setFrom(m) } q.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(20f) val composeMatrix = Matrix().apply { setFrom(q) } assertTrue(composeMatrix.values.contentEquals(m.values)) } @Test fun scale() { val point = FloatArray(2) val m = Matrix() m.scale(2f, 3f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(0f) p.mapPoints(point, floatArrayOf(100f, 100f)) assertThat(point[0]).isWithin(delta).of(200f) assertThat(point[1]).isWithin(delta).of(300f) val composeMatrix = Matrix().apply { setFrom(p) } assertTrue(composeMatrix.values.contentEquals(m.values)) } @Test fun rotate90Scale() { val point = FloatArray(2) val m = Matrix() m.rotateZ(90f) m.scale(2f, 3f) val p = android.graphics.Matrix().apply { setFrom(m) } p.mapPoints(point, floatArrayOf(0f, 0f)) assertThat(point[0]).isWithin(delta).of(0f) assertThat(point[1]).isWithin(delta).of(0f) p.mapPoints(point, floatArrayOf(100f, 100f)) assertThat(point[0]).isWithin(delta).of(-300f) assertThat(point[1]).isWithin(delta).of(200f) val composeMatrix = Matrix().apply { setFrom(p) } assertTrue(composeMatrix.values.contentEquals(m.values)) } }
apache-2.0
4b6a89dff15122d7507334002c3df37a
35.602837
75
0.645611
3.614146
false
true
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/NumberToBoolean.kt
1
4045
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.context.MappingContext import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum import java.lang.IllegalArgumentException abstract class NumberToBoolean< GRAPH_DEF: GeneratedMessageV3, OP_DEF_TYPE: GeneratedMessageV3, NODE_TYPE: GeneratedMessageV3, ATTR_DEF : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE: ProtocolMessageEnum>(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>): BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE> (name = "booleantonumber", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) { override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean { return argDescriptorType == AttributeValueType.INT || argDescriptorType == AttributeValueType.FLOAT } override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean { return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.BOOL) } override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> { val ret = ArrayList<OpNamespace.ArgDescriptor>() for ((k, v) in mappingNamesToPerform()) { val descriptorBuilder = OpNamespace.ArgDescriptor.newBuilder() descriptorBuilder.name = k val irAttribute = mappingCtx.irAttributeValueForNode(v) val targetIdx = lookupIndexForArgDescriptor( argDescriptorName = k, opDescriptorName = mappingCtx.nd4jOpName(), argDescriptorType = OpNamespace.ArgDescriptor.ArgType.BOOL ) if(targetIdx < 0) { throw java.lang.IllegalArgumentException("Output attribute $k not found with boolean type for op name ${mappingCtx.nd4jOpName()} and input op name ${mappingCtx.opName()}") } descriptorBuilder.argIndex = targetIdx descriptorBuilder.argType = OpNamespace.ArgDescriptor.ArgType.BOOL when(irAttribute.attributeValueType()) { AttributeValueType.FLOAT -> { descriptorBuilder.boolValue = irAttribute.floatValue() > 0 } AttributeValueType.INT -> { descriptorBuilder.boolValue = irAttribute.intValue() > 0 } else -> { throw IllegalArgumentException("Illegal type ${irAttribute.attributeValueType()}") } } ret.add(descriptorBuilder.build()) } return ret } }
apache-2.0
262ffb25cc35a94206e5e40ed6fc150c
45.505747
187
0.649444
5.100883
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/move/common/RsMoveUtil.kt
2
12646
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.move.common import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.source.DummyHolder import com.intellij.psi.util.PsiTreeUtil import com.intellij.usageView.UsageInfo import org.rust.ide.utils.import.insertUseItem import org.rust.lang.core.macros.setContext import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* sealed class RsMoveUsageInfo(open val element: RsElement) : UsageInfo(element) class RsModDeclUsageInfo(override val element: RsModDeclItem, val file: RsFile) : RsMoveUsageInfo(element) class RsPathUsageInfo( override val element: RsPath, private val rsReference: PsiReference, val target: RsQualifiedNamedElement ) : RsMoveUsageInfo(element) { lateinit var referenceInfo: RsMoveReferenceInfo override fun getReference(): PsiReference = rsReference } class RsMoveReferenceInfo( /** * [pathOldOriginal] is real path (from user files). * [pathOld] is our helper path (created with [RsCodeFragmentFactory]), which is more convenient to work with. * * In most cases [pathOld] equals to [pathOldOriginal], but there are two corner cases: * 1) Paths with type arguments: `mod1::mod2::Struct1::<T, R>` * ^~~~~~~~~~~~~~~~~~~~~~~~~~^ pathOldOriginal * ^~~~~~~~~~~~~~~~~~^ pathOld * We create [pathOld] from [pathOldOriginal] by deleting type arguments * 2) Paths to nullary enum variants in bindings. * Unfortunately they are parsed as [RsPatIdent]: * match none_or_some { * None => ... * ^~~^ pathOldOriginal * This RsPatIdent (pathOldOriginal) is plain identifier, * so we take it text and create new one-segment RsPath (pathOld) * * Mutable because it can be inside moved elements (if reference is outside), so after move we have to change it. */ var pathOld: RsPath, /** [RsPath] or [RsPatIdent] */ var pathOldOriginal: RsElement, /** `null` means no accessible path found */ val pathNewAccessible: RsPath?, /** Fallback path to use when `pathNew == null` (if user choose "Continue" in conflicts view) */ val pathNewFallback: RsPath?, /** * == `pathOld.reference.resolve()` * mutable because it can be inside moved elements, so after move we have to change it */ var target: RsQualifiedNamedElement, val forceReplaceDirectly: Boolean = false, ) { val pathNew: RsPath? get() = pathNewAccessible ?: pathNewFallback val isInsideUseDirective: Boolean get() = pathOldOriginal.ancestorStrict<RsUseItem>() != null override fun toString(): String = "'${pathOld.text}' → '${target.qualifiedName}'" } /** * Ideally all these functions should have package-private visibility and be at top-level. * But unfortunately there is no package-private visibility, * so we put functions inside object to decrease their priority in completion in other files. */ object RsMoveUtil { fun String.toRsPath(psiFactory: RsPsiFactory): RsPath? = psiFactory.tryCreatePath(this) ?: run { LOG.error("Can't create RsPath from '$this'") null } fun String.toRsPath(codeFragmentFactory: RsCodeFragmentFactory, context: RsElement): RsPath? = codeFragmentFactory.createPath(this, context) ?: run { LOG.error("Can't create RsPath from '$this' in context $context") null } fun String.toRsPathInEmptyTmpMod( codeFragmentFactory: RsCodeFragmentFactory, psiFactory: RsPsiFactory, context: RsMod ): RsPath? { val mod = psiFactory.createModItem(TMP_MOD_NAME, "") mod.setContext(context) return toRsPath(codeFragmentFactory, mod) } fun RsPath.isAbsolute(): Boolean { if (basePath().hasColonColon) return true if (startsWithSuper()) return false if (containingFile is DummyHolder) LOG.error("Path '$text' is inside dummy holder") val basePathTarget = basePath().reference?.resolve() as? RsMod ?: return false return basePathTarget.isCrateRoot } fun RsPath.startsWithSuper(): Boolean = basePath().referenceName == "super" fun RsPath.startsWithSelf(): Boolean = basePath().referenceName == "self" private fun RsPath.startsWithCSelf(): Boolean = basePath().referenceName == "Self" /** * Like `text`, but without spaces and comments. * Expected to be used for paths without type qualifiers and type arguments. */ val RsPath.textNormalized: String get() { val parts = listOfNotNull(path?.textNormalized, coloncolon?.text, referenceName) return parts.joinToString("") } /** * Any outermost path has exactly one simple subpath: * `mod1::mod2::Struct1::method1` * ^~~~~~~~~~~~~~~~~~~~~~~~~~~^ not simple * ^~~~~~~~~~~~~~~~~~^ simple * ^~~~~~~~~^ not simple * ^~~^ not simple * * Path is simple if target of all subpaths is [RsMod] * (target of whole path could be [RsMod] or [RsItemElement]). * These paths are simple: * - `mod1::mod2::Struct1` * - `mod1::mod2::func1` * - `mod1::mod2::mod3` (when `parent` is not [RsPath]) * These are not: * - `Struct1::func1` * - `Vec::<i32>::new()` * - `Self::Item1` */ fun isSimplePath(path: RsPath): Boolean { // TODO: don't ignore `self::`, only `Self::` ? if (path.startsWithSelf() || path.startsWithCSelf()) return false val target = path.reference?.resolve() ?: return false if (target is RsMod && path.parent is RsPath) return false val subpaths = generateSequence(path.path) { it.path } return subpaths.all { it.reference?.resolve() is RsMod } } /** * Creates `pathOld` from `pathOldOriginal`. * See comment for [RsMoveReferenceInfo.pathOld] for details. */ fun convertFromPathOriginal(pathOriginal: RsElement, codeFragmentFactory: RsCodeFragmentFactory): RsPath = when (pathOriginal) { is RsPath -> pathOriginal.removeTypeArguments(codeFragmentFactory) is RsPatIdent -> { val context = pathOriginal.context as? RsElement ?: pathOriginal codeFragmentFactory.createPath(pathOriginal.text, context)!! } else -> error("unexpected pathOriginal: $pathOriginal, text=${pathOriginal.text}") } /** * Converts `mod1::mod2::Struct1::<T>` to `mod1::mod2::Struct1`. * Because it is much nicer to work with path when it does not have type arguments. * Original path will be stored as [RsMoveReferenceInfo.pathOldOriginal]. * And we will convert path back to path with type arguments in [RsMoveRetargetReferencesProcessor.replacePathOldWithTypeArguments]. */ private fun RsPath.removeTypeArguments(codeFragmentFactory: RsCodeFragmentFactory): RsPath { if (typeArgumentList == null) return this val pathCopy = copy() as RsPath pathCopy.typeArgumentList?.delete() val context = context as? RsElement ?: this return pathCopy.text.toRsPath(codeFragmentFactory, context) ?: this } fun RsPath.resolvesToAndAccessible(target: RsQualifiedNamedElement): Boolean { if (containingFile is DummyHolder) LOG.error("Path '$text' is inside dummy holder") if (target.containingFile is DummyHolder) LOG.error("Target $target of path '$text' is inside dummy holder") val reference = reference ?: return false if (!reference.isReferenceTo(target)) return false return isTargetOfEachSubpathAccessible() } fun RsPath.isTargetOfEachSubpathAccessible(): Boolean { for (subpath in generateSequence(this) { it.path }) { val subpathTarget = subpath.reference?.resolve() as? RsVisible ?: continue if (!subpathTarget.isVisibleFrom(containingMod)) return false } return true } val RsElement.containingModOrSelf: RsMod get() = (this as? RsMod) ?: containingMod /** * @return `super` instead of `this` for [RsFile] * * ([RsMod.containingMod] returns `super` when mod is [RsModItem] and `this` when mod is [RsFile]) */ val RsElement.containingModStrict: RsMod get() = when (this) { is RsMod -> `super` ?: this else -> containingMod } /** Like [PsiElement.add], but works correctly for [RsModItem] */ fun RsMod.addInner(element: PsiElement): PsiElement = addBefore(element, if (this is RsModItem) rbrace else null) // TODO: possible performance improvement: iterate over RsElement ancestors only once fun RsElement.isInsideMovedElements(elementsToMove: List<ElementToMove>): Boolean { if (containingFile is RsCodeFragment) LOG.error("Unexpected containingFile: $containingFile") return elementsToMove.any { when (it) { is ItemToMove -> PsiTreeUtil.isAncestor(it.item, this, false) is ModToMove -> containingModOrSelf.superMods.contains(it.mod) } } } @JvmField val LOG: Logger = logger<RsMoveUtil>() } inline fun <reified T : RsElement> movedElementsShallowDescendantsOfType( elementsToMove: List<ElementToMove>, processInlineModules: Boolean = true ): List<T> = movedElementsShallowDescendantsOfType(elementsToMove, T::class.java, processInlineModules) fun <T : RsElement> movedElementsShallowDescendantsOfType( elementsToMove: List<ElementToMove>, aClass: Class<T>, processInlineModules: Boolean = true, ): List<T> { return elementsToMove.flatMap { val element = it.element if (element is RsFile || !processInlineModules && element is RsMod) { return@flatMap emptyList<T>() } PsiTreeUtil.findChildrenOfAnyType(element, false, aClass) } } inline fun <reified T : RsElement> movedElementsDeepDescendantsOfType(elementsToMove: List<ElementToMove>): Sequence<T> = movedElementsDeepDescendantsOfType(elementsToMove, T::class.java) fun <T : RsElement> movedElementsDeepDescendantsOfType( elementsToMove: List<ElementToMove>, aClass: Class<T> ): Sequence<T> { return elementsToMove.asSequence() .flatMap { elementToMove -> when (elementToMove) { is ItemToMove -> PsiTreeUtil.findChildrenOfAnyType(elementToMove.item, false, aClass).asSequence() is ModToMove -> { val mod = elementToMove.mod val childModules = mod.childModules .filter { it.containingFile != mod.containingFile } .map { ModToMove(it) } val childModulesDescendants = movedElementsDeepDescendantsOfType(childModules, aClass) val selfDescendants = PsiTreeUtil.findChildrenOfAnyType(mod, false, aClass).asSequence() selfDescendants + childModulesDescendants } } } } /** * Updates `pub(in path)` visibility modifier. * We replace `path` with common parent module of `newParent` and target of old `path`. */ fun RsVisRestriction.updateScopeIfNecessary(psiFactory: RsPsiFactory, newParent: RsMod) { if (crateRoot == newParent.crateRoot) { if (path.kind == PathKind.SELF) return // `pub(self)` // TODO: pass `oldScope` as parameter? val oldScope = path.reference?.resolve() as? RsMod ?: return val newScope = commonParentMod(oldScope, newParent) ?: return val newScopePath = newScope.crateRelativePath ?: return val newVisRestriction = psiFactory.createVisRestriction("crate$newScopePath") replace(newVisRestriction) } else { // RsVisibility has text `pub(in path)` // after removing RsVisRestriction it will be changed to `pub` delete() } } fun addImport(psiFactory: RsPsiFactory, context: RsElement, usePath: String, alias: String? = null) { if (!usePath.contains("::")) return val blockScope = context.ancestors.find { it is RsBlock && it.childOfType<RsUseItem>() != null } as RsBlock? check(context !is RsMod) val scope = blockScope ?: context.containingMod val useItem = psiFactory.createUseItem(usePath, alias = alias) scope.insertUseItem(psiFactory, useItem) }
mit
bab81e7c1abd8f38f33e555df1141c11
40.455738
136
0.659127
4.456821
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/tools/behavior/KitSimpleActivityBehavior.kt
1
1020
package com.mcgars.basekitk.tools.behavior import android.content.Context import com.google.android.material.appbar.AppBarLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import android.util.AttributeSet import android.view.View /** * Created by Altarix on 01.04.2016. */ class KitSimpleActivityBehavior : AppBarLayout.ScrollingViewBehavior { constructor() {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean { val bool = super.onDependentViewChanged(parent, child, dependency) // child?.let { // if (child.id == R.id.contentFrame && child.paddingTop >= 0) { // if (Build.VERSION.SDK_INT > 10) // child.translationY = (-child.paddingTop).toFloat() // child.setPadding(0, 0, 0, 0) // parent?.requestLayout() // } // } return bool } }
apache-2.0
4650cb415e54616c86f4bd47d2eb0e9e
34.172414
108
0.659804
4.285714
false
false
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/account/DiskUsageDrawable.kt
1
935
package com.stevenschoen.putionew.account import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.GradientDrawable import androidx.core.content.ContextCompat import com.stevenschoen.putionew.R class DiskUsageDrawable(context: Context) : GradientDrawable() { private val usedPaint = Paint().apply { color = ContextCompat.getColor(context, R.color.putio_accent_dark) } private val usedRect = Rect() var usedFraction = 0f set(value) { field = value invalidateSelf() } init { shape = GradientDrawable.RECTANGLE color = ContextCompat.getColorStateList(context, R.color.putio_accent) } override fun draw(canvas: Canvas) { super.draw(canvas) canvas.drawRect( 0f, 0f, usedFraction * bounds.right, bounds.bottom.toFloat(), usedPaint ) } }
mit
4e7971c834fe91ce5b28b40b1dd608da
22.375
74
0.71123
4.137168
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/Util.kt
1
5492
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft import java.text.DecimalFormat import java.util.ArrayList /** * Returns the damage value to be placed in the database for a specific id. This returns the given damage * value for any id where the damage value represents a different distinct block or item. In all other cases, * 0 is returned. Blocks or items whose damage value represents orientation, or lava/water level return 0. For * blocks whose damage value determines both the block type <i>and</i> orientation are normalized to a standard * value for representing that block type in the database. So far only the block type <i>log</i> and <i>log2</i> * fall under this category (id's 17 and 162 respectively). * * @param id The id of the block or item to be normalized * @param damage The given damage value for this block or item * @return The normalized value to be placed into the database */ fun damageValue(id: Short, damage: Short): Short { when (id.toInt()) { 1, // Stone 3, // Dirt 5, // Wooden Planks 6, // Saplings 12, // Sand 18, // Leaves 19, // Sponges 24, // Sandstone 31, // Tall Grass 35, // Wool 38, // Flowers 43, // Double Slabs 44, // Slabs 95, // Stained Glass 97, // Monster Egg Blocks 98, // Stone Bricks 125, // Double New Wooden Slabs 126, // New Wooden Slabs 139, // Cobblestone Walls 144, // Various Head Blocks 155, // Quartz Blocks 159, // Stained Clay 160, // Stained Glass Panes 161, // New Leaves 168, // Prismarine Blocks 171, // Carpet 175, // Various Plants 179, // Red Sandstone 263, // Coal and Charcoal 349, // Various Raw Fish 350, // Various Cooked Fish 351, // Dyes 373, // All Potions 383, // Mob Spawn Eggs 397, // Various Heads 425 // Colored Banners -> return damage 17, // Wood 162 // New Wood -> return if (damage >= 8) { (damage - 8).toShort() } else if (damage >= 4) { (damage - 4).toShort() } else { damage } else -> return 0 } } private val df = DecimalFormat("#,##0.00") fun distanceUnits(distance: Int): String { var distanceM = distance / 100.0 if (distanceM > 1000) { distanceM /= 1000.0 return df.format(distanceM) + " km" } else { return df.format(distanceM) + " m" } } /** * Transform time held in seconds to human readable time * * @param seconds Length of time interval in seconds * @return String of time in a more human readable format, for example 219 seconds would read as "3 minutes, 39 seconds" */ fun transformTime(seconds: Int): String { if (seconds < 0) { throw IllegalArgumentException("Time must not be negative") } // Figure out the playtime in a human readable format val secondsInMinute = 60 val secondsInHour = 60 * secondsInMinute val secondsInDay = 24 * secondsInHour val secondsInWeek = 7 * secondsInDay val weeks = seconds / secondsInWeek val daySeconds = seconds % secondsInWeek val days = daySeconds / secondsInDay val hourSeconds = daySeconds % secondsInDay val hours = hourSeconds / secondsInHour val minuteSeconds = hourSeconds % secondsInHour val minutes = minuteSeconds / secondsInMinute val remainingSeconds = minuteSeconds % secondsInMinute // Make some strings val weekString: String val dayString: String val hourString: String val minuteString: String val secondString: String // Use correct grammar, and don't use it if it's zero if (weeks == 1) { weekString = "$weeks week" } else if (weeks == 0) { weekString = "" } else { weekString = "$weeks weeks" } if (days == 1) { dayString = "$days day" } else if (days == 0) { dayString = "" } else { dayString = "$days days" } if (hours == 1) { hourString = "$hours hour" } else if (hours == 0) { hourString = "" } else { hourString = "$hours hours" } if (minutes == 1) { minuteString = "$minutes minute" } else if (minutes == 0) { minuteString = "" } else { minuteString = "$minutes minutes" } if (remainingSeconds == 1) { secondString = "$remainingSeconds second" } else if (remainingSeconds == 0) { secondString = "" } else { secondString = "$remainingSeconds seconds" } val results = ArrayList<String>() if (!weekString.isEmpty()) { results.add(weekString) } if (!dayString.isEmpty()) { results.add(dayString) } if (!hourString.isEmpty()) { results.add(hourString) } if (!minuteString.isEmpty()) { results.add(minuteString) } if (!secondString.isEmpty()) { results.add(secondString) } if (results.size == 0) { return "0 seconds" } val sb = StringBuilder() results.forEachIndexed { i, s -> if (i == 0) { sb.append(s) } else { sb.append(", ").append(s) } } return sb.toString() }
mit
3561f88eb4ebba4d244825beeefe7f92
26.46
120
0.581391
3.991279
false
false
false
false
MaTriXy/KAndroid
kandroid/src/main/kotlin/com/pawegio/kandroid/KDisplayMetrics.kt
1
1374
/* * Copyright 2015-2016 Paweł Gajda * * 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("NOTHING_TO_INLINE") package com.pawegio.kandroid import android.app.Fragment import android.support.v4.app.Fragment as SupportFragment import android.content.Context import android.view.View inline fun Context.dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() inline fun Context.sp(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt() inline fun Fragment.dp(value: Int): Int = activity.dp(value) inline fun Fragment.sp(value: Int): Int = activity.sp(value) inline fun SupportFragment.dp(value: Int): Int = activity.dp(value) inline fun SupportFragment.sp(value: Int): Int = activity.sp(value) inline fun View.dp(value: Int): Int = context.dp(value) inline fun View.sp(value: Int): Int = context.sp(value)
apache-2.0
550b0bea8391d56caf65bc4c416ebe76
33.35
97
0.753824
3.680965
false
false
false
false
esofthead/mycollab
mycollab-dao/src/main/java/org/mybatis/scripting/velocity/Ifnull.kt
3
1551
package org.mybatis.scripting.velocity import java.io.IOException import java.io.Writer import org.apache.velocity.context.InternalContextAdapter import org.apache.velocity.exception.MethodInvocationException import org.apache.velocity.exception.ParseErrorException import org.apache.velocity.exception.ResourceNotFoundException import org.apache.velocity.runtime.directive.Directive import org.apache.velocity.runtime.directive.DirectiveConstants import org.apache.velocity.runtime.parser.node.Node /** * @author MyCollab Ltd. * @since 4.0 */ class Ifnull : Directive() { /* * (non-Javadoc) * * @see org.apache.velocity.runtime.directive.Directive#getName() */ override fun getName(): String = "ifnull" /* * (non-Javadoc) * * @see org.apache.velocity.runtime.directive.Directive#getType() */ override fun getType(): Int = DirectiveConstants.BLOCK /* * (non-Javadoc) * * @see * org.apache.velocity.runtime.directive.Directive#render(org.apache.velocity * .context.InternalContextAdapter, java.io.Writer, * org.apache.velocity.runtime.parser.node.Node) */ @Throws(IOException::class, ResourceNotFoundException::class, ParseErrorException::class, MethodInvocationException::class) override fun render(context: InternalContextAdapter, writer: Writer, node: Node): Boolean { val value = node.jjtGetChild(0).value(context) if (value == null) { val content = node.jjtGetChild(1) content.render(context, writer) } return true } }
agpl-3.0
62fc1a45080124afa52a9b05b9247043
28.826923
127
0.727273
3.926582
false
false
false
false
xdtianyu/CallerInfo
app/src/main/java/org/xdty/callerinfo/presenter/MainPresenter.kt
1
5037
package org.xdty.callerinfo.presenter import android.annotation.SuppressLint import org.xdty.callerinfo.application.Application import org.xdty.callerinfo.contract.MainContract.Presenter import org.xdty.callerinfo.contract.MainContract.View import org.xdty.callerinfo.data.CallerDataSource import org.xdty.callerinfo.data.CallerDataSource.OnDataUpdateListener import org.xdty.callerinfo.model.database.Database import org.xdty.callerinfo.model.db.Caller import org.xdty.callerinfo.model.db.InCall import org.xdty.callerinfo.model.permission.Permission import org.xdty.callerinfo.model.setting.Setting import org.xdty.callerinfo.utils.Alarm import org.xdty.callerinfo.utils.Contact import org.xdty.phone.number.RxPhoneNumber import org.xdty.phone.number.model.caller.Status import javax.inject.Inject @SuppressLint("CheckResult") class MainPresenter(private val mView: View) : Presenter, OnDataUpdateListener { private val mInCallList: MutableList<InCall> = ArrayList() @Inject internal lateinit var mSetting: Setting @Inject internal lateinit var mPermission: Permission @Inject internal lateinit var mPhoneNumber: RxPhoneNumber @Inject internal lateinit var mDatabase: Database @Inject internal lateinit var mAlarm: Alarm @Inject internal lateinit var mContact: Contact @Inject internal lateinit var mCallerDataSource: CallerDataSource private var isInvalidateDataUpdate = false private var isWaitDataUpdate = false init { Application.appComponent.inject(this) } override fun result(requestCode: Int, resultCode: Int) {} override fun loadInCallList() { mDatabase.fetchInCalls().subscribe { inCalls -> mInCallList.clear() mInCallList.addAll(inCalls) mView.showCallLogs(mInCallList) if (mInCallList.size == 0) { mView.showNoCallLog(true) } else { mView.showNoCallLog(false) } mView.showLoading(false) } } override fun loadCallerMap() { mCallerDataSource.loadCallerMap().subscribe { callerMap -> mView.attachCallerMap(callerMap) } } override fun removeInCallFromList(inCall: InCall) { mInCallList.remove(inCall) } override fun removeInCall(inCall: InCall) { mDatabase.removeInCall(inCall) } override fun clearAll() { mDatabase.clearAllInCalls().subscribe { loadInCallList() } } override fun search(number: String) { if (number.isEmpty()) { return } mView.showSearching() mCallerDataSource.getCaller(number).subscribe { caller -> if (caller.number != null) { mView.showSearchResult(caller) } else { mView.showSearchFailed(!caller.isOffline) } } } override fun checkEula() { if (!mSetting.isEulaSet) { mView.showEula() } } override fun setEula() { mSetting.setEula() } override fun canDrawOverlays(): Boolean { return mPermission.canDrawOverlays() } override fun checkPermission(permission: String): Int { return mPermission.checkPermission(permission) } override fun start() { mCallerDataSource.setOnDataUpdateListener(this) loadCallerMap() // if (System.currentTimeMillis() - mSetting.lastCheckDataUpdateTime() > 6 * 3600 * 1000) { // mPhoneNumber.checkUpdate().subscribe(new Consumer<Status>() { // @Override // public void accept(Status status) throws Exception { // if (status != null && status.count > 0) { // mView.notifyUpdateData(status); // mSetting.setStatus(status); // } // } // }); // } } override fun clearSearch() {} override fun dispatchUpdate(status: Status) { mView.showUpdateData(status) mPhoneNumber.upgradeData().subscribe { result -> mView.updateDataFinished(result) if (result) { mSetting.updateLastCheckDataUpdateTime(System.currentTimeMillis()) } } } override fun getCaller(number: String): Caller { return mCallerDataSource.getCallerFromCache(number) } override fun clearCache() { mCallerDataSource.clearCache().subscribe { loadInCallList() } } override fun itemOnLongClicked(inCall: InCall) { mView.showBottomSheet(inCall) } override fun invalidateDataUpdate(isInvalidate: Boolean) { isInvalidateDataUpdate = isInvalidate if (isWaitDataUpdate) { mView.showCallLogs(mInCallList) isWaitDataUpdate = false } } override fun onDataUpdate(caller: Caller) { isWaitDataUpdate = isInvalidateDataUpdate if (!isWaitDataUpdate) { mView.showCallLogs(mInCallList) } } }
gpl-3.0
380c21d62c113e1e718e9bd5d7d88de4
30.291925
106
0.647806
4.533753
false
false
false
false
czyzby/ktx
graphics/src/main/kotlin/ktx/graphics/graphics.kt
2
3618
package ktx.graphics import com.badlogic.gdx.Gdx import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Camera import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.PixmapIO import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.glutils.GLFrameBuffer import com.badlogic.gdx.graphics.glutils.ShaderProgram import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.utils.BufferUtils import com.badlogic.gdx.utils.ScreenUtils import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Automatically calls [Batch.begin] and [Batch.end]. * @param projectionMatrix A projection matrix to set on the batch before [Batch.begin]. If null, the batch's matrix * remains unchanged. * @param action inlined. Executed after [Batch.begin] and before [Batch.end]. */ @OptIn(ExperimentalContracts::class) inline fun <B : Batch> B.use(projectionMatrix: Matrix4? = null, action: (B) -> Unit) { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } if (projectionMatrix != null) { this.projectionMatrix = projectionMatrix } begin() action(this) end() } /** * Automatically calls [Batch.begin] and [Batch.end]. * @param camera The camera's [Camera.combined] matrix will be set to the batch's projection matrix before [Batch.begin] * @param action inlined. Executed after [Batch.begin] and before [Batch.end]. */ @OptIn(ExperimentalContracts::class) inline fun <B : Batch> B.use(camera: Camera, action: (B) -> Unit) { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } use(camera.combined, action) } /** * Automatically calls [Batch.begin] with the provided matrix * @param projectionMatrix A projection matrix to set on the batch before [Batch.begin]. */ fun <B : Batch> B.begin(projectionMatrix: Matrix4) { this.projectionMatrix = projectionMatrix begin() } /** * Sets the batch's projection matrix to the camera's [Camera.combined] matrix and calls [Batch.begin]. * @param camera The camera's [Camera.combined] matrix will be set to the batch's projection matrix before [Batch.begin]. */ fun <B : Batch> B.begin(camera: Camera) = begin(camera.combined) /** * Automatically calls [ShaderProgram.bind]. * @param action inlined. Executed after [ShaderProgram.bind]. */ @OptIn(ExperimentalContracts::class) inline fun <S : ShaderProgram> S.use(action: (S) -> Unit) { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } bind() action(this) } /** * Automatically calls [GLFrameBuffer.begin] and [GLFrameBuffer.end]. * @param action inlined. Executed after [GLFrameBuffer.begin] and before [GLFrameBuffer.end]. */ @OptIn(ExperimentalContracts::class) inline fun <B : GLFrameBuffer<*>> B.use(action: (B) -> Unit) { contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) } begin() action(this) end() } /** * Takes a screenshot of the entire screen and saves the image using the given [fileHandle]. */ fun takeScreenshot(fileHandle: FileHandle) { val bufferWidth = Gdx.graphics.backBufferWidth val bufferHeight = Gdx.graphics.backBufferHeight val pixels = ScreenUtils.getFrameBufferPixels(0, 0, bufferWidth, bufferHeight, true) // Ensuring the screenshot is opaque: var i = 4 val alpha = 255.toByte() while (i < pixels.size) { pixels[i - 1] = alpha i += 4 } val screenshotImage = Pixmap(bufferWidth, bufferHeight, Pixmap.Format.RGBA8888) BufferUtils.copy(pixels, 0, screenshotImage.pixels, pixels.size) PixmapIO.writePNG(fileHandle, screenshotImage) screenshotImage.dispose() }
cc0-1.0
9421f4618637d8a3fcc2ead781e8ff63
33.788462
121
0.746269
3.788482
false
false
false
false
BloodWorkXGaming/ExNihiloCreatio
src/main/java/exnihilocreatio/compatibility/crafttweaker/Sieve.kt
1
2423
package exnihilocreatio.compatibility.crafttweaker import crafttweaker.IAction import crafttweaker.annotations.ZenRegister import crafttweaker.api.item.IIngredient import crafttweaker.api.item.IItemStack import crafttweaker.api.minecraft.CraftTweakerMC import exnihilocreatio.blocks.BlockSieve import exnihilocreatio.compatibility.crafttweaker.prefab.ENCRemoveAll import exnihilocreatio.registries.manager.ExNihiloRegistryManager import exnihilocreatio.registries.types.Siftable import exnihilocreatio.util.ItemInfo import net.minecraft.item.ItemStack import net.minecraft.item.crafting.Ingredient import stanhebben.zenscript.annotations.ZenClass import stanhebben.zenscript.annotations.ZenMethod @ZenClass("mods.exnihilocreatio.Sieve") @ZenRegister object Sieve { @ZenMethod @JvmStatic fun removeAll() { CrTIntegration.removeActions += ENCRemoveAll(ExNihiloRegistryManager.SIEVE_REGISTRY, "Sieve") } @ZenMethod @JvmStatic fun addStringMeshRecipe(block: IIngredient, drop: IItemStack, chance: Float) { CrTIntegration.addActions += AddRecipe(block, drop, chance, BlockSieve.MeshType.STRING) } @ZenMethod @JvmStatic fun addFlintMeshRecipe(block: IIngredient, drop: IItemStack, chance: Float) { CrTIntegration.addActions += AddRecipe(block, drop, chance, BlockSieve.MeshType.FLINT) } @ZenMethod @JvmStatic fun addIronMeshRecipe(block: IIngredient, drop: IItemStack, chance: Float) { CrTIntegration.addActions += AddRecipe(block, drop, chance, BlockSieve.MeshType.IRON) } @ZenMethod @JvmStatic fun addDiamondMeshRecipe(block: IIngredient, drop: IItemStack, chance: Float) { CrTIntegration.addActions += AddRecipe(block, drop, chance, BlockSieve.MeshType.DIAMOND) } private class AddRecipe( block: IIngredient, private val drop: IItemStack, private val chance: Float, private val meshType: BlockSieve.MeshType ) : IAction { private val input: Ingredient = CraftTweakerMC.getIngredient(block) override fun apply() { ExNihiloRegistryManager.SIEVE_REGISTRY.register(input, Siftable(ItemInfo(drop.internal as ItemStack), chance, meshType.id)) } override fun describe() = "Adding Sieve recipe for ${input.matchingStacks.joinToString(prefix = "[", postfix = "]")} for Mesh ${meshType.getName()}" } }
mit
ba2cbbd4770741db87b8b5bfa398398b
35.712121
156
0.744944
4.206597
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/auth/ui/activity/CredentialAuthActivity.kt
2
9588
package org.stepik.android.view.auth.ui.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.Spannable import android.text.SpannableString import android.text.TextWatcher import android.view.View import android.view.inputmethod.EditorInfo import androidx.activity.viewModels import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.res.ResourcesCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import kotlinx.android.synthetic.main.activity_auth_credential.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.analytic.LoginInteractionType import org.stepic.droid.base.App import org.stepic.droid.model.Credentials import org.stepic.droid.ui.activities.SmartLockActivityBase import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.util.setOnKeyboardOpenListener import org.stepic.droid.util.ProgressHelper import org.stepic.droid.util.toBundle import org.stepik.android.domain.auth.model.LoginFailType import org.stepik.android.model.Course import org.stepik.android.presentation.auth.CredentialAuthPresenter import org.stepik.android.presentation.auth.CredentialAuthView import org.stepik.android.view.auth.extension.getMessageFor import org.stepik.android.view.auth.model.AutoAuth import org.stepik.android.view.base.ui.span.TypefaceSpanCompat import ru.nobird.android.view.base.ui.extension.hideKeyboard import javax.inject.Inject class CredentialAuthActivity : SmartLockActivityBase(), CredentialAuthView { companion object { private const val EXTRA_EMAIL = "extra_email" private const val EXTRA_PASSWORD = "extra_password" private const val EXTRA_AUTO_AUTH = "extra_auto_auth" private const val EXTRA_COURSE = "extra_course" init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } fun createIntent( context: Context, email: String? = null, password: String? = null, autoAuth: AutoAuth = AutoAuth.NONE, course: Course? = null ): Intent = Intent(context, CredentialAuthActivity::class.java) .putExtra(EXTRA_EMAIL, email) .putExtra(EXTRA_PASSWORD, password) .putExtra(EXTRA_AUTO_AUTH, autoAuth) .putExtra(EXTRA_COURSE, course) } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val credentialAuthPresenter: CredentialAuthPresenter by viewModels { viewModelFactory } private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth_credential) injectComponent() initTitle() forgotPasswordView.setOnClickListener { screenManager.openRemindPassword(this@CredentialAuthActivity) } loginField.setOnEditorActionListener { _, actionId, _ -> var handled = false if (actionId == EditorInfo.IME_ACTION_NEXT) { passwordField.requestFocus() handled = true } handled } passwordField.setOnEditorActionListener { _, actionId, _ -> var handled = false if (actionId == EditorInfo.IME_ACTION_SEND) { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN_NEXT_ON_SIGN_IN_SCREEN) analytic.reportEvent(Analytic.Login.REQUEST_LOGIN_WITH_INTERACTION_TYPE, LoginInteractionType.ime.toBundle()) submit() handled = true } handled } val onFocusField = { _: View, hasFocus: Boolean -> if (hasFocus) { analytic.reportEvent(Analytic.Login.TAP_ON_FIELDS) } } loginField.setOnFocusChangeListener(onFocusField) passwordField.setOnFocusChangeListener(onFocusField) val reportAnalyticWhenTextBecomeNotBlank = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { if (s.isNullOrBlank()) { analytic.reportEvent(Analytic.Login.TYPING_TEXT_FIELDS) } } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { credentialAuthPresenter.onFormChanged() } override fun afterTextChanged(s: Editable?) {} } loginField.addTextChangedListener(reportAnalyticWhenTextBecomeNotBlank) passwordField.addTextChangedListener(reportAnalyticWhenTextBecomeNotBlank) launchSignUpButton.setOnClickListener { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_UP) screenManager .showRegistration( this@CredentialAuthActivity, intent.getParcelableExtra(EXTRA_COURSE) ) } signInWithSocial.setOnClickListener { finish() } loginButton.setOnClickListener { analytic.reportEvent(Analytic.Interaction.CLICK_SIGN_IN_ON_SIGN_IN_SCREEN) analytic.reportEvent(Analytic.Login.REQUEST_LOGIN_WITH_INTERACTION_TYPE, LoginInteractionType.button.toBundle()) submit() } loginRootView.requestFocus() initGoogleApiClient() setOnKeyboardOpenListener(root_view, { stepikLogo.isVisible = false signInText.isVisible = false }, { stepikLogo.isVisible = true signInText.isVisible = true }) if (savedInstanceState == null) { setData(intent) } } private fun injectComponent() { App.component() .authComponentBuilder() .build() .inject(this) } override fun onStart() { super.onStart() credentialAuthPresenter.attachView(this) } override fun onStop() { credentialAuthPresenter.detachView(this) super.onStop() } private fun initTitle() { val signInString = getString(R.string.sign_in) val signInWithPasswordSuffix = getString(R.string.sign_in_with_password_suffix) val spannableSignIn = SpannableString(signInString + signInWithPasswordSuffix) val typeface = ResourcesCompat.getFont(this, R.font.roboto_medium) spannableSignIn.setSpan(TypefaceSpanCompat(typeface), 0, signInString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) signInText.text = spannableSignIn } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setData(intent) } private fun setData(intent: Intent) { val autoAuth = intent .getSerializableExtra(EXTRA_AUTO_AUTH) as? AutoAuth ?: AutoAuth.NONE val email = intent.getStringExtra(EXTRA_EMAIL) val password = intent.getStringExtra(EXTRA_PASSWORD) loginField.setText(email) passwordField.setText(password) when { email == null -> loginField.requestFocus() passwordField == null -> passwordField.requestFocus() } if (autoAuth != AutoAuth.NONE) { submit(autoAuth) } } private fun submit(autoAuth: AutoAuth = AutoAuth.NONE) { currentFocus?.hideKeyboard() val login = loginField.text.toString() val password = passwordField.text.toString() credentialAuthPresenter.submit(Credentials(login, password), isRegistration = autoAuth == AutoAuth.REGISTRATION) } override fun applyTransitionPrev() {} // we need default system animation override fun setState(state: CredentialAuthView.State) { if (state is CredentialAuthView.State.Loading) { ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG) } else { ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG) } when (state) { is CredentialAuthView.State.Idle -> { loginButton.isEnabled = true loginForm.isEnabled = true loginErrorMessage.isVisible = false } is CredentialAuthView.State.Error -> { loginErrorMessage.text = getMessageFor(state.failType) loginErrorMessage.isVisible = true if (state.failType == LoginFailType.EMAIL_ALREADY_USED || state.failType == LoginFailType.EMAIL_PASSWORD_INVALID) { loginForm.isEnabled = false loginButton.isEnabled = false } } is CredentialAuthView.State.Success -> if (state.credentials != null && checkPlayServices() && googleApiClient?.isConnected == true) { requestToSaveCredentials(state.credentials) } else { openMainFeed() } } } override fun onCredentialsSaved() { openMainFeed() } private fun openMainFeed() { screenManager.showMainFeedAfterLogin(this, intent.getParcelableExtra(EXTRA_COURSE)) } }
apache-2.0
f17eeef8f5ae04df610c23cca8438053
34.25
125
0.655507
5.051633
false
false
false
false
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/ui/cart/CartViewModel.kt
1
2121
package com.marknkamau.justjava.ui.cart import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.marknjunge.core.data.local.PreferencesRepository import com.marknjunge.core.data.model.* import com.marknjunge.core.data.repository.CartRepository import com.marknkamau.justjava.data.db.DbRepository import com.marknkamau.justjava.data.models.CartItem import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CartViewModel @Inject constructor( private val preferencesRepository: PreferencesRepository, private val dbRepository: DbRepository, private val cartRepository: CartRepository ) : ViewModel() { private val _items = MutableLiveData<List<CartItem>>() val items: LiveData<List<CartItem>> = _items private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = _loading fun isSignedIn() = preferencesRepository.isSignedIn fun getCartItems() { viewModelScope.launch { _items.value = dbRepository.getCartItems() } } fun deleteItem(item: CartItem) { viewModelScope.launch { dbRepository.deleteItemFromCart(item) _items.value = dbRepository.getCartItems() } } fun verifyOrder(items: List<CartItem>): LiveData<Resource<List<VerifyOrderResponse>>> { val livedata = MutableLiveData<Resource<List<VerifyOrderResponse>>>() viewModelScope.launch { _loading.value = true val verificationDto = items.mapIndexed { index, item -> val options = item.options.map { VerifyOrderItemOptionDto(it.choiceId, it.optionId, it.optionPrice) } VerifyOrderItemDto(index, item.cartItem.productId, item.cartItem.productBasePrice, options) } livedata.value = cartRepository.verifyOrder(VerifyOrderDto(verificationDto)) _loading.value = false } return livedata } }
apache-2.0
866ebcd885d80e0a38326852a8441a4d
33.209677
107
0.7124
4.641138
false
false
false
false
square/wire
wire-library/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt
1
7249
/* * Copyright 2019 Square 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.squareup.wire.internal import com.squareup.wire.GrpcException import com.squareup.wire.GrpcResponse import com.squareup.wire.GrpcStatus import com.squareup.wire.ProtoAdapter import com.squareup.wire.use import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.runBlocking import okhttp3.Call import okhttp3.Callback import okhttp3.Headers.Companion.headersOf import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody import okio.BufferedSink import okio.IOException import java.io.Closeable internal val APPLICATION_GRPC_MEDIA_TYPE: MediaType = "application/grpc".toMediaType() /** Returns a new request body that writes [onlyMessage]. */ internal fun <S : Any> newRequestBody( minMessageToCompress: Long, requestAdapter: ProtoAdapter<S>, onlyMessage: S ): RequestBody { return object : RequestBody() { override fun contentType() = APPLICATION_GRPC_MEDIA_TYPE override fun writeTo(sink: BufferedSink) { val grpcMessageSink = GrpcMessageSink( sink = sink, minMessageToCompress = minMessageToCompress, messageAdapter = requestAdapter, callForCancel = null, grpcEncoding = "gzip", ) grpcMessageSink.use { it.write(onlyMessage) } } } } /** * Returns a new duplex request body that allows us to write request messages even after the * response status, headers, and body have been received. */ internal fun newDuplexRequestBody(): PipeDuplexRequestBody { return PipeDuplexRequestBody(APPLICATION_GRPC_MEDIA_TYPE, pipeMaxBufferSize = 1024 * 1024) } /** Writes messages to the request body. */ internal fun <S : Any> PipeDuplexRequestBody.messageSink( minMessageToCompress: Long, requestAdapter: ProtoAdapter<S>, callForCancel: Call ) = GrpcMessageSink( sink = createSink(), minMessageToCompress = minMessageToCompress, messageAdapter = requestAdapter, callForCancel = callForCancel, grpcEncoding = "gzip", ) /** Sends the response messages to the channel. */ internal fun <R : Any> SendChannel<R>.readFromResponseBodyCallback( grpcCall: RealGrpcStreamingCall<*, R>, responseAdapter: ProtoAdapter<R> ): Callback { return object : Callback { override fun onFailure(call: Call, e: IOException) { // Something broke. Kill the response channel. close(e) } override fun onResponse(call: Call, response: GrpcResponse) { grpcCall.responseMetadata = response.headers.toMap() runBlocking { response.use { response.messageSource(responseAdapter).use { reader -> var exception: Exception? = null try { while (true) { val message = reader.read() ?: break send(message) } exception = response.grpcResponseToException() } catch (e: IOException) { exception = response.grpcResponseToException(e) } catch (e: Exception) { exception = e } finally { try { close(exception) } catch (_: CancellationException) { // If it's already canceled, there's nothing more to do. } } } } } } } } /** * Stream messages from the request channel to the request body stream. This means: * * 1. read a message (non blocking, suspending code) * 2. write it to the stream (blocking) * 3. repeat. We also have to wait for all 2s to end before closing the writer * * If this fails reading a message from the channel, we need to call [MessageSink.cancel]. If it * fails writing a message to the network, we shouldn't call that method. * * If it fails either reading or writing we need to call [MessageSink.close] (via [Closeable.use]) * and [ReceiveChannel.cancel]. */ internal suspend fun <S : Any> ReceiveChannel<S>.writeToRequestBody( requestBody: PipeDuplexRequestBody, minMessageToCompress: Long, requestAdapter: ProtoAdapter<S>, callForCancel: Call ) { val requestWriter = requestBody.messageSink(minMessageToCompress, requestAdapter, callForCancel) try { requestWriter.use { var channelReadFailed = true try { consumeEach { message -> channelReadFailed = false requestWriter.write(message) channelReadFailed = true } channelReadFailed = false } finally { if (channelReadFailed) requestWriter.cancel() } } } catch (e: Throwable) { cancel(CancellationException("Could not write message", e)) if (e !is IOException && e !is CancellationException) { throw e } } } /** Reads messages from the response body. */ internal fun <R : Any> GrpcResponse.messageSource( protoAdapter: ProtoAdapter<R> ): GrpcMessageSource<R> { checkGrpcResponse() val grpcEncoding = header("grpc-encoding") val responseSource = body!!.source() return GrpcMessageSource(responseSource, protoAdapter, grpcEncoding) } /** Returns an exception if the response does not follow the protocol. */ private fun GrpcResponse.checkGrpcResponse() { val contentType = body!!.contentType() if (code != 200 || contentType == null || contentType.type != "application" || contentType.subtype != "grpc" && contentType.subtype != "grpc+proto" ) { throw IOException("expected gRPC but was HTTP status=$code, content-type=$contentType") } } /** Returns an exception if the gRPC call didn't have a grpc-status of 0. */ internal fun GrpcResponse.grpcResponseToException(suppressed: IOException? = null): IOException? { var trailers = headersOf() var transportException = suppressed try { trailers = trailers() } catch (e: IOException) { if (transportException == null) transportException = e } val grpcStatus = trailers["grpc-status"] ?: header("grpc-status") val grpcMessage = trailers["grpc-message"] ?: header("grpc-message") if (transportException != null) { return IOException( "gRPC transport failure" + " (HTTP status=$code, grpc-status=$grpcStatus, grpc-message=$grpcMessage)", transportException ) } if (grpcStatus != "0") { val grpcStatusInt = grpcStatus?.toIntOrNull() ?: throw IOException( "gRPC transport failure" + " (HTTP status=$code, grpc-status=$grpcStatus, grpc-message=$grpcMessage)" ) return GrpcException(GrpcStatus.get(grpcStatusInt), grpcMessage) } return null // Success. }
apache-2.0
5f0e5ee410c97f8bd2dafa8731a181db
31.653153
98
0.691406
4.361613
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageSnapshotImpl.kt
3
27675
// 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.intellij.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.util.ExceptionUtil import com.intellij.util.ObjectUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.getDiff import com.intellij.workspaceModel.storage.impl.exceptions.AddDiffException import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException import com.intellij.workspaceModel.storage.impl.external.EmptyExternalEntityMapping import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY import com.intellij.workspaceModel.storage.url.MutableVirtualFileUrlIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrlIndex import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import kotlin.reflect.KClass import kotlin.reflect.KProperty1 internal data class EntityReferenceImpl<E : WorkspaceEntity>(private val id: EntityId) : EntityReference<E>() { override fun resolve(storage: EntityStorage): E? { @Suppress("UNCHECKED_CAST") return (storage as AbstractEntityStorage).entityDataById(id)?.createEntity(storage) as? E } } internal class EntityStorageSnapshotImpl constructor( override val entitiesByType: ImmutableEntitiesBarrel, override val refs: RefsTable, override val indexes: StorageIndexes ) : EntityStorageSnapshot, AbstractEntityStorage() { // This cache should not be transferred to other versions of storage private val persistentIdCache = ConcurrentHashMap<PersistentEntityId<*>, WorkspaceEntity>() @Suppress("UNCHECKED_CAST") override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entity = persistentIdCache.getOrPut(id) { super.resolve(id) ?: NULL_ENTITY } return if (entity !== NULL_ENTITY) entity as E else null } override fun toSnapshot(): EntityStorageSnapshot = this companion object { private val NULL_ENTITY = ObjectUtils.sentinel("null entity", WorkspaceEntity::class.java) val EMPTY = EntityStorageSnapshotImpl(ImmutableEntitiesBarrel.EMPTY, RefsTable(), StorageIndexes.EMPTY) } } internal class MutableEntityStorageImpl( override val entitiesByType: MutableEntitiesBarrel, override val refs: MutableRefsTable, override val indexes: MutableStorageIndexes, @Volatile private var trackStackTrace: Boolean = false ) : MutableEntityStorage, AbstractEntityStorage() { internal val changeLog = WorkspaceBuilderChangeLog() // Temporal solution for accessing error in deft project. internal var throwExceptionOnError = false internal fun incModificationCount() { this.changeLog.modificationCount++ } override val modificationCount: Long get() = this.changeLog.modificationCount private val writingFlag = AtomicBoolean() @Volatile private var stackTrace: String? = null @Volatile private var threadId: Long? = null @Volatile private var threadName: String? = null override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> { @Suppress("UNCHECKED_CAST") return entitiesByType[entityClass.toClassId()]?.all()?.map { it.wrapAsModifiable(this) } as? Sequence<E> ?: emptySequence() } override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> { val classId = entityClass.toClassId() @Suppress("UNCHECKED_CAST") return indexes.softLinks.getIdsByEntry(id).asSequence() .filter { it.clazz == classId } .map { entityDataByIdOrDie(it).wrapAsModifiable(this) as R } } override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null val entityData: WorkspaceEntityData<WorkspaceEntity> = entityDataById(entityIds) as? WorkspaceEntityData<WorkspaceEntity> ?: return null @Suppress("UNCHECKED_CAST") return entityData.wrapAsModifiable(this) as E? } // Do not remove cast to Class<out TypedEntity>. kotlin fails without it @Suppress("USELESS_CAST") override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source -> indexes.entitySourceIndex .getIdsByEntry(source)!!.map { val entityDataById: WorkspaceEntityData<WorkspaceEntity> = this.entityDataById(it) as? WorkspaceEntityData<WorkspaceEntity> ?: run { reportErrorAndAttachStorage("Cannot find an entity by id $it", this@MutableEntityStorageImpl) error("Cannot find an entity by id $it") } entityDataById.wrapAsModifiable(this) } .groupBy { (it as WorkspaceEntityBase).getEntityInterface() } } } override fun <T : WorkspaceEntity> addEntity(entity: T) { try { lockWrite() entity as ModifiableWorkspaceEntityBase<T> entity.applyToBuilder(this) } finally { unlockWrite() } } // This should be removed or not extracted into the interface fun <T : WorkspaceEntity, D: ModifiableWorkspaceEntityBase<T>> putEntity(entity: D) { try { lockWrite() val newEntityData = entity.getEntityData() // Check for persistent id uniqueness assertUniquePersistentId(newEntityData) entitiesByType.add(newEntityData, entity.getEntityClass().toClassId()) // Add the change to changelog createAddEvent(newEntityData) // Update indexes indexes.entityAdded(newEntityData) } finally { unlockWrite() } } private fun <T : WorkspaceEntity> assertUniquePersistentId(pEntityData: WorkspaceEntityData<T>) { pEntityData.persistentId()?.let { persistentId -> val ids = indexes.persistentIdIndex.getIdsByEntry(persistentId) if (ids != null) { // Oh, oh. This persistent id exists already // Fallback strategy: remove existing entity with all it's references val existingEntityData = entityDataByIdOrDie(ids) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error( """ addEntity: persistent id already exists. Replacing entity with the new one. Persistent id: $persistentId Existing entity data: $existingEntityData New entity data: $pEntityData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(persistentId) ) if (throwExceptionOnError) { throw PersistentIdAlreadyExistsException(persistentId) } } } } @Suppress("UNCHECKED_CAST") override fun <M : ModifiableWorkspaceEntity<out T>, T : WorkspaceEntity> modifyEntity(clazz: Class<M>, e: T, change: M.() -> Unit): T { try { lockWrite() val entityId = (e as WorkspaceEntityBase).id val originalEntityData = this.getOriginalEntityData(entityId) as WorkspaceEntityData<T> // Get entity data that will be modified val copiedData = entitiesByType.getEntityDataForModification(entityId) as WorkspaceEntityData<T> val modifiableEntity = copiedData.wrapAsModifiable(this) as M val beforePersistentId = if (e is WorkspaceEntityWithPersistentId) e.persistentId else null val originalParents = this.getOriginalParents(entityId.asChild()) val beforeParents = this.refs.getParentRefsOfChild(entityId.asChild()) val beforeChildren = this.refs.getChildrenRefsOfParentBy(entityId.asParent()).flatMap { (key, value) -> value.map { key to it } } // Execute modification code (modifiableEntity as ModifiableWorkspaceEntityBase<*>).allowModifications { modifiableEntity.change() } // Check for persistent id uniqueness if (beforePersistentId != null) { val newPersistentId = copiedData.persistentId() if (newPersistentId != null) { val ids = indexes.persistentIdIndex.getIdsByEntry(newPersistentId) if (beforePersistentId != newPersistentId && ids != null) { // Oh, oh. This persistent id exists already. // Remove an existing entity and replace it with the new one. val existingEntityData = entityDataByIdOrDie(ids) val existingEntity = existingEntityData.createEntity(this) removeEntity(existingEntity) LOG.error(""" modifyEntity: persistent id already exists. Replacing entity with the new one. Old entity: $existingEntityData Persistent id: $copiedData Broken consistency: $brokenConsistency """.trimIndent(), PersistentIdAlreadyExistsException(newPersistentId)) if (throwExceptionOnError) { throw PersistentIdAlreadyExistsException(newPersistentId) } } } else { LOG.error("Persistent id expected for entity: $copiedData") } } if (!modifiableEntity.changedProperty.contains("entitySource") || modifiableEntity.changedProperty.size > 1) { // Add an entry to changelog addReplaceEvent(this, entityId, beforeChildren, beforeParents, copiedData, originalEntityData, originalParents) } if (modifiableEntity.changedProperty.contains("entitySource")) { updateEntitySource(entityId, originalEntityData, copiedData) } val updatedEntity = copiedData.createEntity(this) this.indexes.updatePersistentIdIndexes(this, updatedEntity, beforePersistentId, copiedData, modifiableEntity) return updatedEntity } finally { unlockWrite() } } private fun <T : WorkspaceEntity> updateEntitySource(entityId: EntityId, originalEntityData: WorkspaceEntityData<T>, copiedEntityData: WorkspaceEntityData<T>) { val newSource = copiedEntityData.entitySource val originalSource = this.getOriginalSourceFromChangelog(entityId) ?: originalEntityData.entitySource this.changeLog.addChangeSourceEvent(entityId, copiedEntityData, originalSource) indexes.entitySourceIndex.index(entityId, newSource) newSource.virtualFileUrl?.let { indexes.virtualFileIndex.index(entityId, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) } } override fun removeEntity(e: WorkspaceEntity) { try { lockWrite() LOG.debug { "Removing ${e.javaClass}..." } e as WorkspaceEntityBase removeEntity(e.id) // NB: This method is called from `createEntity` inside persistent id checking. It's possible that after the method execution // the store is in inconsistent state, so we can't call assertConsistency here. } finally { unlockWrite() } } /** * TODO Spacial cases: when source filter returns true for all entity sources. */ override fun replaceBySource(sourceFilter: (EntitySource) -> Boolean, replaceWith: EntityStorage) { try { lockWrite() replaceWith as AbstractEntityStorage ReplaceBySourceAsGraph.replaceBySourceAsGraph(this, replaceWith, sourceFilter) } finally { unlockWrite() } } override fun collectChanges(original: EntityStorage): Map<Class<*>, List<EntityChange<*>>> { try { lockWrite() val originalImpl = original as AbstractEntityStorage val res = HashMap<Class<*>, MutableList<EntityChange<*>>>() for ((entityId, change) in this.changeLog.changeLog) { when (change) { is ChangeEntry.AddEntity -> { val addedEntity = change.entityData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Added(addedEntity)) } is ChangeEntry.RemoveEntity -> { val removedData = originalImpl.entityDataById(change.id) ?: continue val removedEntity = removedData.createEntity(originalImpl) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() }.add(EntityChange.Removed(removedEntity)) } is ChangeEntry.ReplaceEntity -> { @Suppress("DuplicatedCode") val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ChangeEntitySource -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } is ChangeEntry.ReplaceAndChangeSource -> { val oldData = originalImpl.entityDataById(entityId) ?: continue val replacedData = oldData.createEntity(originalImpl) as WorkspaceEntityBase val replaceToData = change.dataChange.newData.createEntity(this) as WorkspaceEntityBase res.getOrPut(entityId.clazz.findEntityClass<WorkspaceEntity>()) { ArrayList() } .add(EntityChange.Replaced(replacedData, replaceToData)) } } } return res } finally { unlockWrite() } } override fun toSnapshot(): EntityStorageSnapshot { val newEntities = entitiesByType.toImmutable() val newRefs = refs.toImmutable() val newIndexes = indexes.toImmutable() return EntityStorageSnapshotImpl(newEntities, newRefs, newIndexes) } override fun isEmpty(): Boolean = this.changeLog.changeLog.isEmpty() override fun addDiff(diff: MutableEntityStorage) { try { lockWrite() diff as MutableEntityStorageImpl applyDiffProtection(diff, "addDiff") AddDiffOperation(this, diff).addDiff() } finally { unlockWrite() } } @Suppress("UNCHECKED_CAST") override fun <T> getMutableExternalMapping(identifier: String): MutableExternalEntityMapping<T> { try { lockWrite() val mapping = indexes.externalMappings.computeIfAbsent( identifier) { MutableExternalEntityMappingImpl<T>() } as MutableExternalEntityMappingImpl<T> mapping.setTypedEntityStorage(this) return mapping } finally { unlockWrite() } } override fun getMutableVirtualFileUrlIndex(): MutableVirtualFileUrlIndex { try { lockWrite() val virtualFileIndex = indexes.virtualFileIndex virtualFileIndex.setTypedEntityStorage(this) return virtualFileIndex } finally { unlockWrite() } } internal fun addDiffAndReport(message: String, left: EntityStorage?, right: EntityStorage) { reportConsistencyIssue(message, AddDiffException(message), null, left, right, this) } private fun applyDiffProtection(diff: AbstractEntityStorage, method: String) { LOG.trace { "Applying $method. Builder: $diff" } if (diff.storageIsAlreadyApplied) { LOG.error("Builder is already applied.\n Info: \n${diff.applyInfo}") } else { diff.storageIsAlreadyApplied = true var info = "Applying builder using $method. Previous stack trace >>>>\n" if (LOG.isTraceEnabled) { val currentStackTrace = ExceptionUtil.currentStackTrace() info += "\n$currentStackTrace" } info += "<<<<" diff.applyInfo = info } } // modificationCount is not incremented internal fun removeEntity(idx: EntityId, entityFilter: (EntityId) -> Boolean = { true }) { val accumulator: MutableSet<EntityId> = mutableSetOf(idx) accumulateEntitiesToRemove(idx, accumulator, entityFilter) val originals = accumulator.associateWith { this.getOriginalEntityData(it) as WorkspaceEntityData<WorkspaceEntity> to this.getOriginalParents(it.asChild()) } for (id in accumulator) { val entityData = entityDataById(id) if (entityData is SoftLinkable) indexes.removeFromSoftLinksIndex(entityData) entitiesByType.remove(id.arrayId, id.clazz) } // Update index // Please don't join it with the previous loop for (id in accumulator) indexes.entityRemoved(id) accumulator.forEach { LOG.debug { "Cascade removing: ${ClassToIntConverter.INSTANCE.getClassOrDie(it.clazz)}-${it.arrayId}" } this.changeLog.addRemoveEvent(it, originals[it]!!.first, originals[it]!!.second) } } private fun lockWrite() { val currentThread = Thread.currentThread() if (writingFlag.getAndSet(true)) { if (threadId != null && threadId != currentThread.id) { LOG.error(""" Concurrent write to builder from the following threads First Thread: $threadName Second Thread: ${currentThread.name} Previous stack trace: $stackTrace """.trimIndent()) trackStackTrace = true } } if (trackStackTrace || LOG.isTraceEnabled) { stackTrace = ExceptionUtil.currentStackTrace() } threadId = currentThread.id threadName = currentThread.name } private fun unlockWrite() { writingFlag.set(false) stackTrace = null threadId = null threadName = null } internal fun <T : WorkspaceEntity> createAddEvent(pEntityData: WorkspaceEntityData<T>) { val entityId = pEntityData.createEntityId() this.changeLog.addAddEvent(entityId, pEntityData) } /** * Cleanup references and accumulate hard linked entities in [accumulator] */ private fun accumulateEntitiesToRemove(id: EntityId, accumulator: MutableSet<EntityId>, entityFilter: (EntityId) -> Boolean) { val children = refs.getChildrenRefsOfParentBy(id.asParent()) for ((connectionId, childrenIds) in children) { for (childId in childrenIds) { if (childId.id in accumulator) continue if (!entityFilter(childId.id)) continue accumulator.add(childId.id) accumulateEntitiesToRemove(childId.id, accumulator, entityFilter) refs.removeRefsByParent(connectionId, id.asParent()) } } val parents = refs.getParentRefsOfChild(id.asChild()) for ((connectionId, parent) in parents) { refs.removeParentToChildRef(connectionId, parent, id.asChild()) } } companion object { private val LOG = logger<MutableEntityStorageImpl>() fun create(): MutableEntityStorageImpl { return from(EntityStorageSnapshotImpl.EMPTY) } fun from(storage: EntityStorage): MutableEntityStorageImpl { storage as AbstractEntityStorage val newBuilder = when (storage) { is EntityStorageSnapshotImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType) val copiedRefs = MutableRefsTable.from(storage.refs) val copiedIndex = storage.indexes.toMutable() MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndex) } is MutableEntityStorageImpl -> { val copiedBarrel = MutableEntitiesBarrel.from(storage.entitiesByType.toImmutable()) val copiedRefs = MutableRefsTable.from(storage.refs.toImmutable()) val copiedIndexes = storage.indexes.toMutable() MutableEntityStorageImpl(copiedBarrel, copiedRefs, copiedIndexes, storage.trackStackTrace) } } LOG.trace { "Create new builder $newBuilder from $storage.\n${currentStackTrace(10)}" } return newBuilder } internal fun addReplaceEvent( builder: MutableEntityStorageImpl, entityId: EntityId, beforeChildren: List<Pair<ConnectionId, ChildEntityId>>, beforeParents: Map<ConnectionId, ParentEntityId>, copiedData: WorkspaceEntityData<out WorkspaceEntity>, originalEntity: WorkspaceEntityData<out WorkspaceEntity>, originalParents: Map<ConnectionId, ParentEntityId>, ) { val parents = builder.refs.getParentRefsOfChild(entityId.asChild()) val unmappedChildren = builder.refs.getChildrenRefsOfParentBy(entityId.asParent()) val children = unmappedChildren.flatMap { (key, value) -> value.map { key to it } } // Collect children changes val beforeChildrenSet = beforeChildren.toMutableSet() val (removedChildren, addedChildren) = getDiff(beforeChildrenSet, children) // Collect parent changes val parentsMapRes: MutableMap<ConnectionId, ParentEntityId?> = beforeParents.toMutableMap() for ((connectionId, parentId) in parents) { val existingParent = parentsMapRes[connectionId] if (existingParent != null) { if (existingParent == parentId) { parentsMapRes.remove(connectionId, parentId) } else { parentsMapRes[connectionId] = parentId } } else { parentsMapRes[connectionId] = parentId } } val removedKeys = beforeParents.keys - parents.keys removedKeys.forEach { parentsMapRes[it] = null } builder.changeLog.addReplaceEvent(entityId, copiedData, originalEntity, originalParents, addedChildren, removedChildren, parentsMapRes) } } } internal sealed class AbstractEntityStorage : EntityStorage { internal abstract val entitiesByType: EntitiesBarrel internal abstract val refs: AbstractRefsTable internal abstract val indexes: StorageIndexes internal var brokenConsistency: Boolean = false internal var storageIsAlreadyApplied = false internal var applyInfo: String? = null override fun <E : WorkspaceEntity> entities(entityClass: Class<E>): Sequence<E> { @Suppress("UNCHECKED_CAST") return entitiesByType[entityClass.toClassId()]?.all()?.map { it.createEntity(this) } as? Sequence<E> ?: emptySequence() } override fun <E : WorkspaceEntity> entitiesAmount(entityClass: Class<E>): Int { return entitiesByType[entityClass.toClassId()]?.size() ?: 0 } internal fun entityDataById(id: EntityId): WorkspaceEntityData<out WorkspaceEntity>? = entitiesByType[id.clazz]?.get(id.arrayId) internal fun entityDataByIdOrDie(id: EntityId): WorkspaceEntityData<out WorkspaceEntity> { val entityFamily = entitiesByType[id.clazz] ?: error( "Entity family doesn't exist or has no entities: ${id.clazz.findWorkspaceEntity()}") return entityFamily.get(id.arrayId) ?: error("Cannot find an entity by id $id") } override fun <E : WorkspaceEntity, R : WorkspaceEntity> referrers(e: E, entityClass: KClass<R>, property: KProperty1<R, EntityReference<E>>): Sequence<R> { TODO() //return entities(entityClass.java).filter { property.get(it).resolve(this) == e } } override fun <E : WorkspaceEntityWithPersistentId, R : WorkspaceEntity> referrers(id: PersistentEntityId<E>, entityClass: Class<R>): Sequence<R> { val classId = entityClass.toClassId() @Suppress("UNCHECKED_CAST") return indexes.softLinks.getIdsByEntry(id).asSequence() .filter { it.clazz == classId } .map { entityDataByIdOrDie(it).createEntity(this) as R } } override fun <E : WorkspaceEntityWithPersistentId> resolve(id: PersistentEntityId<E>): E? { val entityIds = indexes.persistentIdIndex.getIdsByEntry(id) ?: return null @Suppress("UNCHECKED_CAST") return entityDataById(entityIds)?.createEntity(this) as E? } // Do not remove cast to Class<out TypedEntity>. kotlin fails without it @Suppress("USELESS_CAST") override fun entitiesBySource(sourceFilter: (EntitySource) -> Boolean): Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { return indexes.entitySourceIndex.entries().asSequence().filter { sourceFilter(it) }.associateWith { source -> indexes.entitySourceIndex .getIdsByEntry(source)!!.map { this.entityDataById(it)?.createEntity(this) ?: run { reportErrorAndAttachStorage("Cannot find an entity by id $it", this@AbstractEntityStorage) error("Cannot find an entity by id $it") } } .groupBy { (it as WorkspaceEntityBase).getEntityInterface() } } } @Suppress("UNCHECKED_CAST") override fun <T> getExternalMapping(identifier: String): ExternalEntityMapping<T> { val index = indexes.externalMappings[identifier] as? ExternalEntityMappingImpl<T> if (index == null) return EmptyExternalEntityMapping as ExternalEntityMapping<T> index.setTypedEntityStorage(this) return index } override fun getVirtualFileUrlIndex(): VirtualFileUrlIndex { indexes.virtualFileIndex.setTypedEntityStorage(this) return indexes.virtualFileIndex } override fun <E : WorkspaceEntity> createReference(e: E): EntityReference<E> = EntityReferenceImpl((e as WorkspaceEntityBase).id) internal fun assertConsistencyInStrictMode(message: String, sourceFilter: ((EntitySource) -> Boolean)?, left: EntityStorage?, right: EntityStorage?) { if (ConsistencyCheckingMode.current != ConsistencyCheckingMode.DISABLED) { try { this.assertConsistency() } catch (e: Throwable) { brokenConsistency = true val storage = if (this is MutableEntityStorage) this.toSnapshot() as AbstractEntityStorage else this val report = { reportConsistencyIssue(message, e, sourceFilter, left, right, storage) } if (ConsistencyCheckingMode.current == ConsistencyCheckingMode.ASYNCHRONOUS) { consistencyChecker.execute(report) } else { report() } } } } companion object { val LOG = logger<AbstractEntityStorage>() private val consistencyChecker = AppExecutorUtil.createBoundedApplicationPoolExecutor("Check workspace model consistency", 1) } } /** This function exposes `brokenConsistency` property to the outside and should be removed along with the property itself */ val EntityStorage.isConsistent: Boolean get() = !(this as AbstractEntityStorage).brokenConsistency
apache-2.0
9a58d1b58c3384a328d6f7dbb20d09ef
39.878877
149
0.688889
5.095747
false
false
false
false
Maccimo/intellij-community
platform/execution/src/com/intellij/execution/target/value/TargetEnvironmentFunctions.kt
3
10542
// Copyright 2000-2021 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. @file:JvmName("TargetEnvironmentFunctions") package com.intellij.execution.target.value import com.intellij.execution.target.* import com.intellij.execution.target.local.LocalTargetEnvironment import com.intellij.execution.target.local.LocalTargetEnvironmentRequest import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.FileUtil import org.jetbrains.annotations.ApiStatus import java.io.File import java.io.IOException import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.Paths import java.util.function.Function import kotlin.io.path.name /** * The function that is expected to be resolved with provided * [TargetEnvironment]. * * Such functions could be used during the construction of a command line and * play the role of deferred values of, for example: * - the path to an executable; * - the working directory; * - the command-line parameters; * - the values of environment variables. * * It is recommended to subclass the default implementation [TraceableTargetEnvironmentFunction], see its documentation for rationale. */ typealias TargetEnvironmentFunction<R> = Function<TargetEnvironment, R> /** * Implementation of TraceableTargetEnvironmentFunction that holds the stack trace of its creation. * * Unless it's intended to create hundreds of such objects a second, prefer using this class as a base for [TargetEnvironmentFunction] * to ease debugging in case of raised exceptions. */ @ApiStatus.Experimental abstract class TraceableTargetEnvironmentFunction<R> : TargetEnvironmentFunction<R> { private val creationStack: Throwable = Throwable("Creation stack") final override fun apply(t: TargetEnvironment): R = try { applyInner(t) } catch (err: Throwable) { err.addSuppressed(creationStack) throw err } abstract fun applyInner(t: TargetEnvironment): R override fun <V> andThen(after: Function<in R, out V>): TraceableTargetEnvironmentFunction<V> = TraceableTargetEnvironmentFunction { targetEnvironment -> after.apply(apply(targetEnvironment)) } companion object { @JvmStatic inline operator fun <R> invoke( crossinline delegate: (targetEnvironment: TargetEnvironment) -> R, ): TraceableTargetEnvironmentFunction<R> = object : TraceableTargetEnvironmentFunction<R>() { override fun applyInner(t: TargetEnvironment): R = delegate(t) } } } /** * This function is preferable to use over function literals in Kotlin * (i.e. `TargetEnvironmentFunction { value }`) and lambdas in Java * (i.e. `ignored -> value`) because it is has more explicit [toString] which * results in clear variable descriptions during debugging and better logging * abilities. */ fun <T> constant(value: T): TargetEnvironmentFunction<T> = Constant(value) private class Constant<T>(private val value: T) : TraceableTargetEnvironmentFunction<T>() { override fun toString(): String = "${javaClass.simpleName}($value)" override fun applyInner(t: TargetEnvironment): T = value } @JvmOverloads fun <T> Iterable<TargetEnvironmentFunction<T>>.joinToStringFunction(separator: CharSequence, transform: ((T) -> CharSequence)? = null): TargetEnvironmentFunction<String> = JoinedStringTargetEnvironmentFunction(iterable = this, separator = separator, transform = transform) fun TargetEnvironmentRequest.getTargetEnvironmentValueForLocalPath(localPath: String): TargetEnvironmentFunction<String> { if (this is LocalTargetEnvironmentRequest) return constant(localPath) return TraceableTargetEnvironmentFunction { targetEnvironment -> targetEnvironment.resolveLocalPath(localPath) } } fun getTargetEnvironmentValueForLocalPath(localPath: String): TargetEnvironmentFunction<String> { return TraceableTargetEnvironmentFunction { targetEnvironment -> when (targetEnvironment) { is LocalTargetEnvironment -> localPath else -> targetEnvironment.resolveLocalPath(localPath) } } } private fun TargetEnvironment.resolveLocalPath(localPath: String): String { if (this is ExternallySynchronized) { val pathForSynchronizedVolume = tryMapToSynchronizedVolume(localPath) if (pathForSynchronizedVolume != null) return pathForSynchronizedVolume } val (uploadRoot, relativePath) = request.getUploadRootForLocalPath(localPath) ?: throw IllegalArgumentException( "Local path \"$localPath\" is not registered within uploads in the request") val volume = uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" is expected to be created in the target environment") return joinPaths(volume.targetRoot, relativePath, targetPlatform) } private fun ExternallySynchronized.tryMapToSynchronizedVolume(localPath: String): String? { // TODO [targets] Does not look nice this as TargetEnvironment val targetFileSeparator = targetPlatform.platform.fileSeparator val (volume, relativePath) = synchronizedVolumes.firstNotNullOfOrNull { volume -> getRelativePathIfAncestor(ancestor = volume.localPath, file = localPath)?.let { relativePath -> volume to if (File.separatorChar != targetFileSeparator) { relativePath.replace(File.separatorChar, targetFileSeparator) } else { relativePath } } } ?: return null return joinPaths(volume.targetPath, relativePath, targetPlatform) } fun TargetEnvironmentRequest.getUploadRootForLocalPath(localPath: String): Pair<TargetEnvironment.UploadRoot, String>? { val targetFileSeparator = targetPlatform.platform.fileSeparator return uploadVolumes.mapNotNull { uploadRoot -> getRelativePathIfAncestor(ancestor = uploadRoot.localRootPath, file = localPath)?.let { relativePath -> uploadRoot to if (File.separatorChar != targetFileSeparator) { relativePath.replace(File.separatorChar, targetFileSeparator) } else { relativePath } } }.firstOrNull() } private fun getRelativePathIfAncestor(ancestor: Path, file: String): String? = try { ancestor.relativize(Paths.get(file)).takeIf { !it.startsWith("..") }?.toString() } catch (ignored: InvalidPathException) { null } catch (ignored: IllegalArgumentException) { // It should not happen, but some tests use relative paths, and they fail trying to call `Paths.get("\\").relativize(Paths.get("."))` null } private fun joinPaths(basePath: String, relativePath: String, targetPlatform: TargetPlatform): String { if (relativePath == ".") { return basePath } val fileSeparator = targetPlatform.platform.fileSeparator.toString() return FileUtil.toSystemIndependentName("${basePath.removeSuffix(fileSeparator)}$fileSeparator$relativePath") } fun TargetEnvironment.UploadRoot.getTargetUploadPath(): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val uploadRoot = this@getTargetUploadPath val uploadableVolume = targetEnvironment.uploadVolumes[uploadRoot] ?: throw IllegalStateException("Upload root \"$uploadRoot\" cannot be found") uploadableVolume.targetRoot } fun TargetEnvironmentFunction<String>.getRelativeTargetPath(targetRelativePath: String): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val targetBasePath = [email protected](targetEnvironment) joinPaths(targetBasePath, targetRelativePath, targetEnvironment.targetPlatform) } fun TargetEnvironment.DownloadRoot.getTargetDownloadPath(): TargetEnvironmentFunction<String> = TraceableTargetEnvironmentFunction { targetEnvironment -> val downloadRoot = this@getTargetDownloadPath val downloadableVolume = targetEnvironment.downloadVolumes[downloadRoot] ?: throw IllegalStateException("Download root \"$downloadRoot\" cannot be found") downloadableVolume.targetRoot } fun TargetEnvironment.LocalPortBinding.getTargetEnvironmentValue(): TargetEnvironmentFunction<HostPort> = TraceableTargetEnvironmentFunction { targetEnvironment -> val localPortBinding = this@getTargetEnvironmentValue val resolvedPortBinding = (targetEnvironment.localPortBindings[localPortBinding] ?: throw IllegalStateException("Local port binding \"$localPortBinding\" cannot be found")) resolvedPortBinding.targetEndpoint } @Throws(IOException::class) fun TargetEnvironment.downloadFromTarget(localPath: Path, progressIndicator: ProgressIndicator) { val localFileDir = localPath.parent val downloadVolumes = downloadVolumes.values val downloadVolume = downloadVolumes.find { it.localRoot == localFileDir } ?: error("Volume with local root $localFileDir not found") downloadVolume.download(localPath.name, progressIndicator) } private class JoinedStringTargetEnvironmentFunction<T>(private val iterable: Iterable<TargetEnvironmentFunction<T>>, private val separator: CharSequence, private val transform: ((T) -> CharSequence)?) : TraceableTargetEnvironmentFunction<String>() { override fun applyInner(t: TargetEnvironment): String = iterable.map { it.apply(t) }.joinToString(separator = separator, transform = transform) override fun toString(): String { return "JoinedStringTargetEnvironmentValue(iterable=$iterable, separator=$separator, transform=$transform)" } } private class ConcatTargetEnvironmentFunction(private val left: TargetEnvironmentFunction<String>, private val right: TargetEnvironmentFunction<String>) : TraceableTargetEnvironmentFunction<String>() { override fun applyInner(t: TargetEnvironment): String = left.apply(t) + right.apply(t) override fun toString(): String { return "ConcatTargetEnvironmentFunction(left=$left, right=$right)" } } operator fun TargetEnvironmentFunction<String>.plus(f: TargetEnvironmentFunction<String>): TargetEnvironmentFunction<String> = ConcatTargetEnvironmentFunction(this, f) operator fun TargetEnvironmentFunction<String>.plus(str: String): TargetEnvironmentFunction<String> = this + constant(str)
apache-2.0
4183fa95a238dbafe2922865d1327a15
44.248927
146
0.745684
5.484912
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/action/VimPluginToggleAction.kt
1
1402
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareToggleAction import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.helper.MessageHelper /** * This class is used to handle the Vim Plugin enabled/disabled toggle. This is most likely used as a menu option * but could also be used as a toolbar item. */ class VimPluginToggleAction : DumbAwareToggleAction()/*, LightEditCompatible*/ { override fun isSelected(event: AnActionEvent): Boolean = VimPlugin.isEnabled() override fun setSelected(event: AnActionEvent, b: Boolean) { VimPlugin.setEnabled(b) } override fun update(e: AnActionEvent) { super.update(e) e.presentation.text = if (ActionPlaces.POPUP == e.place) { if (VimPlugin.isEnabled()) MessageHelper.message("action.VimPluginToggle.enabled") else MessageHelper.message("action.VimPluginToggle.enable") } else MessageHelper.message("action.VimPluginToggle.text") } override fun getActionUpdateThread() = ActionUpdateThread.BGT }
mit
f6516f14c82adf9519c8c2636afce97f
35.894737
148
0.774608
4.354037
false
false
false
false
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/action/motion/select/SelectKeyHandlerTest.kt
1
10876
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.action.motion.select import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.helper.VimBehaviorDiffers import org.jetbrains.plugins.ideavim.SkipNeovimReason import org.jetbrains.plugins.ideavim.TestWithoutNeovim import org.jetbrains.plugins.ideavim.VimTestCase /** * @author Alex Plate */ class SelectKeyHandlerTest : VimTestCase() { @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test type in select mode`() { val typed = "Hello" this.doTest( listOf("gh", "<S-Right>", typed), """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery ${typed}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test char mode on empty line`() { val typed = "Hello" this.doTest( listOf("gh", typed), """ A Discovery $c I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery $typed I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test char mode backspace`() { this.doTest( listOf("gh", "<BS>"), """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I ${c}ound it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test char mode delete`() { this.doTest( listOf("gh", "<DEL>"), """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I ${c}ound it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test char mode multicaret`() { val typed = "Hello" this.doTest( listOf("gh", "<S-Right>", typed), """ A Discovery I ${c}found it in a legendary land all rocks and ${c}lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I ${typed}und it in a legendary land all rocks and ${typed}vender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test line mode`() { val typed = "Hello" this.doTest( listOf("gH", typed), """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery $typed all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test line mode empty line`() { val typed = "Hello" this.doTest( listOf("gH", typed), """ A Discovery $c I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery $typed I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test line mode multicaret`() { val typed = "Hello" this.doTest( listOf("gH", typed), """ A Discovery I ${c}found it in a legendary land all rocks and ${c}lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery Hello Hello where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test type in select block mode`() { val typed = "Hello" this.doTest( listOf("g<C-H>", "<S-Down>", "<S-Right>", typed), """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery ${typed}found it in a legendary land ${typed}l rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @VimBehaviorDiffers( originalVimAfter = """ A Discovery Hello Hellofound it in a legendary land Hellol rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """ ) @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test block mode empty line`() { val typed = "Hello" this.doTest( listOf("g<C-H>", "<S-Down>".repeat(2), "<S-Right>", typed), """ A Discovery $c I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery $typed found it in a legendary land ${typed}ll rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test block mode longer line`() { val typed = "Hello" this.doTest( listOf("g<C-H>", "<S-Down>", "<S-Right>".repeat(2), typed), """ A Discovery I found it in a legendary lan${c}d all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary lan$typed all rocks and lavender and tu${typed}d grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.INSERT, VimStateMachine.SubMode.NONE ) } @TestWithoutNeovim(SkipNeovimReason.SELECT_MODE) fun `test block mode longer line with esc`() { val typed = "Hello" this.doTest( listOf("g<C-H>", "<S-Down>", "<S-Right>".repeat(2), typed, "<esc>"), """ A Discovery I found it in a legendary lan${c}d all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), """ A Discovery I found it in a legendary lanHell${c}o all rocks and lavender and tuHell${c}od grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent(), VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE ) assertCaretsVisualAttributes() assertMode(VimStateMachine.Mode.COMMAND) } }
mit
d900c384968f48b888b32060c92ad89c
30.80117
74
0.553236
5.106103
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/SortCommand.kt
1
4411
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.ex.ranges.LineRange import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.helper.inBlockSubMode import com.maddyhome.idea.vim.vimscript.model.ExecutionResult import java.util.* /** * @author Alex Selesse * see "h :sort" */ data class SortCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) { override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.WRITABLE) @Throws(ExException::class) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { val arg = argument val nonEmptyArg = arg.trim().isNotEmpty() val reverse = nonEmptyArg && "!" in arg val ignoreCase = nonEmptyArg && "i" in arg val number = nonEmptyArg && "n" in arg val lineComparator = LineComparator(ignoreCase, number, reverse) if (editor.inBlockSubMode) { val primaryCaret = editor.primaryCaret() val range = getSortLineRange(editor, primaryCaret) val worked = injector.changeGroup.sortRange(editor, range, lineComparator) primaryCaret.moveToInlayAwareOffset( injector.motion.moveCaretToLineStartSkipLeading(editor, range.startLine) ) return if (worked) ExecutionResult.Success else ExecutionResult.Error } var worked = true for (caret in editor.nativeCarets()) { val range = getSortLineRange(editor, caret) if (!injector.changeGroup.sortRange(editor, range, lineComparator)) { worked = false } caret.moveToInlayAwareOffset(injector.motion.moveCaretToLineStartSkipLeading(editor, range.startLine)) } return if (worked) ExecutionResult.Success else ExecutionResult.Error } private fun getSortLineRange(editor: VimEditor, caret: VimCaret): LineRange { val range = getLineRange(editor, caret) // Something like "30,20sort" gets converted to "20,30sort" val normalizedRange = if (range.endLine < range.startLine) LineRange(range.endLine, range.startLine) else range // If we don't have a range, we either have "sort", a selection, or a block if (normalizedRange.endLine - normalizedRange.startLine == 0) { // If we have a selection. val selectionModel = editor.getSelectionModel() return if (selectionModel.hasSelection()) { val start = selectionModel.selectionStart val end = selectionModel.selectionEnd val startLine = editor.offsetToBufferPosition(start).line val endLine = editor.offsetToBufferPosition(end).line LineRange(startLine, endLine) } else { LineRange(0, editor.lineCount() - 1) } // If we have a generic selection, i.e. "sort" entire document } return normalizedRange } private class LineComparator( private val myIgnoreCase: Boolean, private val myNumber: Boolean, private val myReverse: Boolean, ) : Comparator<String> { override fun compare(o1: String, o2: String): Int { var o1ToCompare = o1 var o2ToCompare = o2 if (myReverse) { val tmp = o2ToCompare o2ToCompare = o1ToCompare o1ToCompare = tmp } if (myIgnoreCase) { o1ToCompare = o1ToCompare.uppercase(Locale.getDefault()) o2ToCompare = o2ToCompare.uppercase(Locale.getDefault()) } return if (myNumber) { // About natural sort order - http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html val n1 = injector.searchGroup.findDecimalNumber(o1ToCompare) val n2 = injector.searchGroup.findDecimalNumber(o2ToCompare) if (n1 == null) { if (n2 == null) 0 else -1 } else { if (n2 == null) 1 else n1.compareTo(n2) } } else o1ToCompare.compareTo(o2ToCompare) } } }
mit
96a997d4b13c725055564048e4c1ae05
36.381356
132
0.707549
4.153484
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/jetpack/common/viewholders/JetpackButtonViewHolder.kt
1
2869
package org.wordpress.android.ui.jetpack.common.viewholders import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import androidx.viewbinding.ViewBinding import com.google.android.material.button.MaterialButton import org.wordpress.android.R import org.wordpress.android.databinding.JetpackListButtonPrimaryItemBinding import org.wordpress.android.databinding.JetpackListButtonSecondaryItemBinding import org.wordpress.android.ui.jetpack.common.JetpackListItemState import org.wordpress.android.ui.jetpack.common.JetpackListItemState.ActionButtonState import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.extensions.setVisible import org.wordpress.android.widgets.FlowLayout.LayoutParams sealed class JetpackButtonViewHolder<T : ViewBinding>( parent: ViewGroup, inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> T ) : JetpackViewHolder<T>(parent, inflateBinding) { class Primary( private val uiHelpers: UiHelpers, parent: ViewGroup ) : JetpackButtonViewHolder<JetpackListButtonPrimaryItemBinding>( parent, JetpackListButtonPrimaryItemBinding::inflate ) { override fun onBind(itemUiState: JetpackListItemState) { binding.button.updateState(binding.root, itemUiState as ActionButtonState, uiHelpers) } } class Secondary( private val uiHelpers: UiHelpers, parent: ViewGroup ) : JetpackButtonViewHolder<JetpackListButtonSecondaryItemBinding>( parent, JetpackListButtonSecondaryItemBinding::inflate ) { override fun onBind(itemUiState: JetpackListItemState) { binding.button.updateState(binding.root, itemUiState as ActionButtonState, uiHelpers) } } internal fun MaterialButton.updateState(root: View, buttonState: ActionButtonState, uiHelpers: UiHelpers) { updateItemViewVisibility(root, buttonState.isVisible) uiHelpers.setTextOrHide(this, buttonState.text) isEnabled = buttonState.isEnabled setOnClickListener { buttonState.onClick.invoke() } buttonState.iconRes?.let { iconGravity = MaterialButton.ICON_GRAVITY_TEXT_START icon = context.getDrawable(it) val resources = itemView.context.resources iconSize = resources.getDimensionPixelSize(R.dimen.jetpack_button_icon_size) } } private fun updateItemViewVisibility(root: View, isVisible: Boolean) { with(root) { setVisible(isVisible) layoutParams = if (isVisible) { ConstraintLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) } else { ConstraintLayout.LayoutParams(0, 0) } } } }
gpl-2.0
58f4db2d9afe714b833d1c9d44fd8ec5
39.985714
111
0.729174
5.077876
false
false
false
false
mikegehard/user-management-evolution-kotlin
applications/billing/src/main/kotlin/com/example/billing/reocurringPayments/Controller.kt
1
1613
package com.example.billing.reocurringPayments import com.example.payments.Gateway import org.springframework.boot.actuate.metrics.CounterService import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController import javax.inject.Inject // Can you use delegation here??? // https://youtu.be/mSg9kSYfeX0?t=22m35s @RestController class Controller @Inject constructor(val paymentGateway: Gateway, val counter: CounterService, val service: Service) { @RequestMapping(value = "/reocurringPayment", method = arrayOf(RequestMethod.POST)) fun createReocurringPayment(@RequestBody data: Map<String, Any>): ResponseEntity<String> { val responseHeaders = HttpHeaders().apply { add("content-type", MediaType.APPLICATION_JSON_VALUE) } service.thisMayFail() val createSuccessful = paymentGateway.createReocurringPayment(data["amount"] as Int) val response = if (createSuccessful) { counter.increment("billing.reocurringPayment.created") ResponseEntity("{\"errors\": []}", responseHeaders, HttpStatus.CREATED) } else { ResponseEntity("{\"errors\": [\"error1\", \"error2\"]}", responseHeaders, HttpStatus.BAD_REQUEST) } return response } }
mit
f54f805c0bdec2576bdd66740b99f993
39.325
118
0.747675
4.407104
false
false
false
false
mvysny/vaadin-on-kotlin
vok-framework/src/main/kotlin/eu/vaadinonkotlin/I18n.kt
1
3273
package eu.vaadinonkotlin import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.ConcurrentHashMap public val emptyResourceBundle: ResourceBundle = object : ListResourceBundle() { override fun getContents(): Array<Array<Any>> = arrayOf() } /** * Localizes VoK messages such as exception messages, texts found in the filter components etc. To obtain instance of * this class, just use the `vt` property * which will lookup proper [locale] from the current UI. See the `vt` property documentation for more details. * * The standard Java [ResourceBundle] mechanism is used. * * The following resource bundles are searched: * * The `VokMessages*.properties` bundle, located in the root package (`src/main/resources/`). Create one if you need to customize the localization * strings in your app. * * If the message is not found, the standard message bundle of `com.github.vok.VokMessages*.properties` is consulted. * * Consult the standard message bundle for the list of messages. * * Currently there is no support for parameters nor expressions in the messages. * @property locale the locale to use, not null. */ public class I18n internal constructor(public val locale: Locale) { private val standardMessages: ResourceBundle = ResourceBundle.getBundle("eu.vaadinonkotlin.VokMessages", locale) private val customMessages: ResourceBundle = try { ResourceBundle.getBundle("VokMessages", locale) } catch (ex: MissingResourceException) { // don't log the exception itself, it will clutter the console with uninformative exceptions. log.debug("Custom message bundle VokMessages for locale $locale is missing, ignoring") emptyResourceBundle } /** * Retrieves the message stored under given [key]. If no such message exists, the function must not fail. * Instead, it should provide a key wrapped with indicators that a message is missing, for example * `!{key}!`. */ public operator fun get(key: String): String { if (customMessages.containsKey(key)) { return customMessages.getString(key) } if (standardMessages.containsKey(key)) { return standardMessages.getString(key) } return "!{$key}!"; } /** * Checks whether there is a message under given [key]. If not, [get] will return `!{key}!`. */ public fun contains(key: String): Boolean = customMessages.containsKey(key) || standardMessages.containsKey(key) public companion object { @JvmStatic private val log = LoggerFactory.getLogger(I18n::class.java) } } /** * Returns a provider which provides instances of [I18n]. On debugging, * the provider will always create new instance which allows for hot-redeployment * of the i18n bundles. For production, the [I18n] instances are cached * so that the key lookup is very quick. */ public fun getI18nProvider(production: Boolean): (Locale)-> I18n = when (production) { true -> productionI18nProvider else -> { locale -> I18n(locale) } } private val productionI18nCache = ConcurrentHashMap<Locale, I18n>() private val productionI18nProvider: (Locale)-> I18n = { locale -> productionI18nCache.computeIfAbsent(locale) { l -> I18n(l) } }
mit
e53ca3cdf0a7d118fdcaaebf3304ad76
40.961538
148
0.713413
4.217784
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/zolotayakorona/ZolotayaKoronaTransitData.kt
1
13025
/* * ZolotayaKoronaTransitData.kt * * Copyright 2018 Google * * 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 au.id.micolous.metrodroid.transit.zolotayakorona import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.card.classic.UnauthorizedClassicSector import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.Epoch import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.NumberUtils @Parcelize data class ZolotayaKoronaTransitData internal constructor( private val mSerial: String, private val mBalance: Int?, private val mCardSerial: String, private val mTrip: ZolotayaKoronaTrip?, private val mRefill: ZolotayaKoronaRefill?, private val mCardType: Int, private val mStatus: Int, private val mDiscountCode: Int, private val mSequenceCtr: Int, private val mTail: ImmutableByteArray) : TransitData() { private val estimatedBalance: Int get() { // a trip followed by refill. Assume only one refill. if (mRefill != null && mTrip != null && mRefill.mTime > mTrip.mTime) return mTrip.estimatedBalance + mRefill.mAmount // Last transaction was a trip if (mTrip != null) return mTrip.estimatedBalance // No trips. Look for refill if (mRefill != null) return mRefill.mAmount // Card was never used or refilled return 0 } override val balance get() = if (mBalance == null) TransitCurrency.RUB(estimatedBalance) else TransitCurrency.RUB(mBalance) override val serialNumber get() = formatSerial(mSerial) override val cardName get() = nameCard(mCardType) override val info get(): List<ListItem>? { val regionNum = mCardType shr 16 val cardInfo = CARDS[mCardType] val regionRsrcIdx = cardInfo?.locationId val regionName = ( if (regionRsrcIdx != null) Localizer.localizeString(regionRsrcIdx) else RussiaTaxCodes.BCDToName(regionNum) ) return listOf( ListItem(R.string.zolotaya_korona_region, regionName), ListItem(R.string.card_type, cardInfo?.name ?: mCardType.toString(16)), ListItem(R.string.zolotaya_korona_discount, discountMap[mDiscountCode]?.let { Localizer.localizeString(it) } ?: Localizer.localizeString(R.string.unknown_format, mDiscountCode.toString(16))), // Printed in hex on the receipt ListItem(R.string.card_serial_number, mCardSerial.toUpperCase()), ListItem(R.string.refill_counter, mRefill?.mCounter?.toString() ?: "0")) } override fun getRawFields(level: RawLevel): List<ListItem>? = listOf( // Unsure about next 2 fields, hence they are hidden in raw fields ListItem("Status", mStatus.toString()), ListItem("Issue seqno", mSequenceCtr.toString()), ListItem(FormattedString("ID-Tail"), mTail.toHexDump()) ) override val trips get() = listOfNotNull(mTrip) + listOfNotNull(mRefill) companion object { private val discountMap = mapOf( 0x46 to R.string.zolotaya_korona_discount_111, 0x47 to R.string.zolotaya_korona_discount_100, 0x48 to R.string.zolotaya_korona_discount_200 ) private val INFO_CARDS = mapOf( 0x230100 to CardInfo( name = R.string.card_name_krasnodar_etk, locationId = R.string.location_krasnodar, imageId = R.drawable.krasnodar_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronakrasnodar", preview = true), 0x560200 to CardInfo( name = R.string.card_name_orenburg_ekg, locationId = R.string.location_orenburg, imageId = R.drawable.orenburg_ekg, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronaorenburg", preview = true), 0x632600 to CardInfo( name = R.string.card_name_samara_etk, locationId = R.string.location_samara, imageId = R.drawable.samara_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronasamara", preview = true), 0x760500 to CardInfo( name = R.string.card_name_yaroslavl_etk, locationId = R.string.location_yaroslavl, imageId = R.drawable.yaroslavl_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronayaroslavl", preview = true) ) private val EXTRA_CARDS = mapOf( 0x562300 to CardInfo( name = R.string.card_name_orenburg_school, locationId = R.string.location_orenburg, imageId = R.drawable.orenburg_ekg, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronaorenburg", preview = true), 0x562400 to CardInfo( name = R.string.card_name_orenburg_student, locationId = R.string.location_orenburg, imageId = R.drawable.orenburg_ekg, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronaorenburg", preview = true), 0x631500 to CardInfo( name = R.string.card_name_samara_school, locationId = R.string.location_samara, imageId = R.drawable.samara_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronasamara", preview = true), 0x632700 to CardInfo( name = R.string.card_name_samara_student, locationId = R.string.location_samara, imageId = R.drawable.samara_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronasamara", preview = true), 0x633500 to CardInfo( name = R.string.card_name_samara_garden_dacha, locationId = R.string.location_samara, imageId = R.drawable.samara_etk, imageAlphaId = R.drawable.iso7810_id1_alpha, cardType = CardType.MifareClassic, region = TransitRegion.RUSSIA, keysRequired = true, keyBundle = "zolotayakoronasamara", preview = true) ) private val CARDS = INFO_CARDS + EXTRA_CARDS private fun nameCard(type: Int) = CARDS[type]?.name ?: (Localizer.localizeString(R.string.card_name_zolotaya_korona) + " " + type.toString(16)) private val FALLBACK_CARD_INFO = CardInfo( name = Localizer.localizeString(R.string.card_name_zolotaya_korona), locationId = R.string.location_russia, imageId = R.drawable.zolotayakorona, cardType = CardType.MifareClassic, keysRequired = true, region = TransitRegion.RUSSIA, preview = true) fun parseTime(time: Int, cardType: Int): Timestamp? { if (time == 0) return null val tz = RussiaTaxCodes.BCDToTimeZone(cardType shr 16) val epoch = Epoch.local(1970, tz) // This is pseudo unix time with local day alwayscoerced to 86400 seconds return epoch.daySecond(time / 86400, time % 86400) } private fun getSerial(card: ClassicCard) = card[15, 2].data.getHexString( 4, 10).substring(0, 19) private fun getCardType(card: ClassicCard) = card[15, 1].data.byteArrayToInt( 10, 3) private fun formatSerial(serial: String) = NumberUtils.groupString(serial, " ", 4, 5, 5) val FACTORY: ClassicCardTransitFactory = object : ClassicCardTransitFactory { override val allCards get() = listOf(FALLBACK_CARD_INFO) + INFO_CARDS.values override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity( nameCard(getCardType(card)), formatSerial(getSerial(card))) override fun parseTransitData(card: ClassicCard): TransitData { val cardType = getCardType(card) val balance = if (card[6] is UnauthorizedClassicSector) null else card[6, 0].data.byteArrayToIntReversed(0, 4) val infoBlock = card[4,0].data val refill = ZolotayaKoronaRefill.parse(card[4, 1].data, cardType) val trip = ZolotayaKoronaTrip.parse(card[4, 2].data, cardType, refill, balance) return ZolotayaKoronaTransitData( mSerial = getSerial(card), mCardSerial = card[0, 0].data.getHexString(0, 4), mCardType = cardType, mBalance = balance, mTrip = trip, mRefill = refill, mStatus = infoBlock.getBitsFromBuffer(60, 4), mSequenceCtr = infoBlock.byteArrayToInt(8, 2), mDiscountCode = infoBlock[10].toInt() and 0xff, mTail = infoBlock.sliceOffLen(11, 5) ) } override fun earlyCheck(sectors: List<ClassicSector>): Boolean { val toc = sectors[0][1].data // Check toc entries for sectors 10,12,13,14 and 15 return toc.byteArrayToInt(8, 2) == 0x18ee && toc.byteArrayToInt(12, 2) == 0x18ee } override val earlySectors get() = 1 } } }
gpl-3.0
c1dc940e8b8d5b2a342179b42a436f8a
47.600746
133
0.57428
4.407783
false
false
false
false
FlexSeries/FlexLib
src/main/kotlin/me/st28/flexseries/flexlib/permission/PermissionHelper.kt
1
5692
/** * Copyright 2016 Stealth2800 <http://stealthyone.com/> * Copyright 2016 Contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexlib.permission import org.bukkit.Bukkit import org.bukkit.configuration.ConfigurationSection import org.bukkit.entity.Player import java.util.* object PermissionHelper { private var vaultPerm: net.milkbowl.vault.permission.Permission? = null private var vaultChat: net.milkbowl.vault.chat.Chat? = null internal val groupEntries: MutableMap<String, GroupEntry> = LinkedHashMap() // Group, groups that inherit from it internal val inheritanceIndex: MutableMap<String, MutableList<String>> = HashMap() internal fun reload(config: ConfigurationSection?) { if (config == null) { return } // Setup vault if (vaultPerm == null) { vaultPerm = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission::class.java)!!.provider } if (vaultChat == null) { vaultChat = Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.chat.Chat::class.java)!!.provider } groupEntries.clear() inheritanceIndex.clear() val rawObj = config.get("inheritance")!! // Inferred permissions if (rawObj is List<*>) { for (group in rawObj as List<String>) { groupEntries.put(group, PermissionGroupEntry("flexlib.group." + group)) } return } if (rawObj !is ConfigurationSection) { throw IllegalArgumentException("Invalid configuration for inheritance") } val sec = rawObj for (group in sec.getKeys(false)) { val permission = sec.getString("$group.permission") if (permission != null) { groupEntries.put(group, PermissionGroupEntry(permission)) continue } if (!sec.isSet("groups")) { continue } val inherit = sec.getStringList("groups") if (inherit != null) { groupEntries.put(group, GroupsGroupEntry(group, inherit)) } } } fun getPlayerGroups(player: Player): List<String> { return vaultPerm!!.getPlayerGroups(null, player).map(String::toLowerCase) } fun isPlayerInGroup(player: Player, group: String, checkInheritance: Boolean): Boolean { val entry = groupEntries[group.toLowerCase()] ?: return getPlayerGroups(player).contains(group.toLowerCase()) return entry.containsPlayer(player) || (checkInheritance && entry.playerInherits(player)) } fun getPrimaryGroup(player: Player): String { return vaultChat!!.getPrimaryGroup(player) } /** * @return A list of registered groups, ordered from least to most important. */ fun getGroupOrder(): List<String> { return ArrayList(groupEntries.keys) } fun getTopGroup(player: Player, groups: Collection<String>, defaultGroup: String? = null): String { val reversed = groupEntries.keys.reversed() for (group in reversed) { val entry = groupEntries[group]!! if (groups.contains(group) && (entry.containsPlayer(player) || entry.playerInherits(player))) { return group } } return defaultGroup ?: getPrimaryGroup(player) } } internal interface GroupEntry { /** * @return True if the player is in this group */ fun containsPlayer(player: Player): Boolean /** * @return True ift he player is in this group via inheritance. */ fun playerInherits(player: Player): Boolean } internal class PermissionGroupEntry : GroupEntry { private val permission: String constructor(permission: String) { this.permission = permission } override fun containsPlayer(player: Player): Boolean { return player.hasPermission(permission) } override fun playerInherits(player: Player): Boolean { return containsPlayer(player) } } internal class GroupsGroupEntry: GroupEntry { private val group: String constructor(group: String, inherits: List<String>) { this.group = group.toLowerCase() for (inherit in inherits) { val key = inherit.toLowerCase() if (!PermissionHelper.inheritanceIndex.containsKey(key)) { PermissionHelper.inheritanceIndex.put(inherit, ArrayList()) } PermissionHelper.inheritanceIndex[inherit]!!.add(group) } } override fun containsPlayer(player: Player): Boolean { return PermissionHelper.getPlayerGroups(player).contains(group) } override fun playerInherits(player: Player): Boolean { val playerGroups = PermissionHelper.getPlayerGroups(player) val inheritance = PermissionHelper.inheritanceIndex[group]!! for (inherit in inheritance) { if (playerGroups.contains(inherit)) { return true } } return false } }
apache-2.0
5d35f22847df02a0fd3ea542e466700f
30.103825
132
0.64371
4.669401
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/classic/ClassicAuthenticator.kt
1
6979
/* * ClassicAuthenticator.kt * * Copyright 2012-2015 Eric Butler <[email protected]> * Copyright 2012 Wilbert Duijvenvoorde <[email protected]> * Copyright 2015-2018 Michael Farrell <[email protected]> * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.card.classic import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface import au.id.micolous.metrodroid.key.CardKeysRetriever import au.id.micolous.metrodroid.key.ClassicKeys import au.id.micolous.metrodroid.key.ClassicSectorKey import au.id.micolous.metrodroid.key.ClassicStaticKeys import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.Preferences class ClassicAuthenticator internal constructor(private val mKeys: ClassicKeys, private val isFallback: Boolean, private val isDynamic: Boolean, private val maxProgress: Int, private val mRetryLimit: Int = Preferences.mfcAuthRetry, private val mPreferredBundles: MutableList<String> = mutableListOf() ) { private suspend fun tryKey(tech: ClassicCardTech, sectorIndex: Int, sectorKey: ClassicSectorKey): Boolean { if (!tech.authenticate(sectorIndex, sectorKey)) return false Log.d(TAG, "Authenticated on sector $sectorIndex, bundle ${sectorKey.bundle}, key ${sectorKey.key.toHexString()}, type ${sectorKey.type}") if (!mPreferredBundles.contains(sectorKey.bundle)) mPreferredBundles.add(sectorKey.bundle) return true } private suspend fun tryCandidatesSub(tech: ClassicCardTech, sectorIndex: Int, candidates: Collection<ClassicSectorKey>): ClassicSectorKey? { candidates.forEach { sectorKey -> if (tryKey(tech, sectorIndex, sectorKey)) return sectorKey } return null } private suspend fun tryCandidates(tech: ClassicCardTech, sectorIndex: Int, candidates: Collection<ClassicSectorKey>, keyType: ClassicSectorKey.KeyType): ClassicSectorKey? { if (keyType == ClassicSectorKey.KeyType.UNKNOWN) { tryCandidatesSub(tech, sectorIndex, candidates.map { it.canonType() })?.let { return it } tryCandidatesSub(tech, sectorIndex, candidates.map { it.invertType() })?.let { return it } } else { tryCandidatesSub(tech, sectorIndex, candidates.map { it.updateType(keyType) })?.let { return it } } return null } suspend fun authenticate(tech: ClassicCardTech, feedbackInterface: TagReaderFeedbackInterface, sectorIndex: Int, expectDynamic: Boolean, keyType: ClassicSectorKey.KeyType): ClassicSectorKey? { val failFast = (!isDynamic && expectDynamic) feedbackInterface.updateProgressBar(sectorIndex * 5, maxProgress) if (!isFallback) { feedbackInterface.updateStatusText(Localizer.localizeString(R.string.mfc_have_key, sectorIndex)) } else { feedbackInterface.updateStatusText(Localizer.localizeString(R.string.mfc_default_key, sectorIndex)) } val tries = if (failFast) 1 else mRetryLimit // Try to authenticate with the sector multiple times, in case we have // impaired communications with the card. repeat(tries) { tryNum -> // If we have a known key for the sector on the card, try this first. Log.d(TAG, "Attempting authentication on sector $sectorIndex, try number $tryNum...") tryCandidates(tech, sectorIndex, mKeys.getCandidates(sectorIndex, tech.tagId, mPreferredBundles), keyType)?.let { return it } } // Try with the other keys, unless we know that keys are likely to be dynamic if (failFast) return null feedbackInterface.updateProgressBar(sectorIndex * 5 + 2, maxProgress) repeat (mRetryLimit) {tryNum -> Log.d(TAG, "Attempting authentication with other keys on sector $sectorIndex, try number $tryNum...") // Attempt authentication with alternate keys feedbackInterface.updateStatusText(Localizer.localizeString(R.string.mfc_other_key, sectorIndex)) // Be a little more forgiving on the key list. Lets try all the keys! // // This takes longer, of course, but means that users aren't scratching // their heads when we don't get the right key straight away. tryCandidates(tech, sectorIndex, mKeys.getAllKeys(tech.tagId), keyType)?.let { Log.d(TAG, "Authenticated successfully to sector $sectorIndex with other key. " + "Fix the key file to speed up authentication") return it } } //noinspection StringConcatenation Log.d(TAG, "Authentication unsuccessful for sector $sectorIndex, giving up") return null } companion object { private const val TAG = "ClassicAuthenticator" fun makeAuthenticator(tagId: ImmutableByteArray, retriever: CardKeysRetriever, maxProgress: Int): ClassicAuthenticator { (retriever.forTagID(tagId) as? ClassicKeys)?.let { return ClassicAuthenticator(it, isFallback = false, isDynamic = true, maxProgress = maxProgress) } retriever.forClassicStatic()?.let { return ClassicAuthenticator(it, isFallback = false, isDynamic = false, maxProgress = maxProgress) } return ClassicAuthenticator(ClassicStaticKeys.fallback(), isFallback = true, isDynamic = false, maxProgress = maxProgress) } } }
gpl-3.0
383ca25ced068d755cb07c1d0d2f890b
45.838926
146
0.631896
4.918252
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/friends/feed/data/Post.kt
1
4009
package io.ipoli.android.friends.feed.data import android.support.annotation.DrawableRes import android.support.annotation.StringRes import io.ipoli.android.R import io.ipoli.android.achievement.Achievement import io.ipoli.android.common.datetime.Day import io.ipoli.android.common.datetime.Duration import io.ipoli.android.common.datetime.Minute import io.ipoli.android.player.data.Avatar import io.ipoli.android.quest.Entity import org.threeten.bp.Instant import org.threeten.bp.LocalDate data class Post( override val id: String = "", val playerId: String = "", val playerAvatar: Avatar, val playerDisplayName: String, val playerUsername: String, val playerLevel: Int, val description: String?, val data: Data, val reactions: List<Reaction>, val comments: List<Comment>, val commentCount: Int = 0, val imageUrl: String? = null, val status: Status, val isFromCurrentPlayer: Boolean, override val createdAt: Instant = Instant.now(), override val updatedAt: Instant = Instant.now() ) : Entity { enum class Status { PENDING, APPROVED, REJECTED } data class Comment( val id: String, val playerId: String, val playerAvatar: Avatar, val playerDisplayName: String, val playerUsername: String, val playerLevel: Int, val text: String, val createdAt: Instant = Instant.now() ) sealed class Data { data class DailyChallengeCompleted(val streak: Int, val bestStreak: Int) : Data() data class LevelUp(val level: Int) : Data() data class AchievementUnlocked(val achievement: Achievement) : Data() data class QuestShared( val questId: String, val questName: String, val durationTracked: Duration<Minute> ) : Data() data class QuestWithPomodoroShared( val questId: String, val questName: String, val pomodoroCount: Int ) : Data() data class ChallengeShared(val challengeId: String, val name: String) : Data() data class ChallengeCompleted( val challengeId: String, val name: String, val duration: Duration<Day> ) : Data() data class QuestFromChallengeCompleted( val questId: String, val challengeId: String, val questName: String, val challengeName: String, val durationTracked: Duration<Minute> ) : Data() data class QuestWithPomodoroFromChallengeCompleted( val questId: String, val challengeId: String, val questName: String, val challengeName: String, val pomodoroCount: Int ) : Data() data class HabitCompleted( val habitId: String, val habitName: String, val habitDate : LocalDate, val challengeId: String?, val challengeName: String?, val isGood: Boolean, val streak: Int, val bestStreak: Int ) : Data() } data class Reaction( val playerId: String, val reactionType: ReactionType, val createdAt: Instant ) enum class ReactionType { LIKE, LOVE, COOL, WOW, BAD, ANGRY } } enum class AndroidReactionType( @StringRes val title: Int, @DrawableRes val image: Int, val animation: String ) { LIKE( R.string.like, R.drawable.react_like, "like.json" ), LOVE( R.string.love, R.drawable.react_love, "heart.json" ), COOL( R.string.cool, R.drawable.react_cool, "cool.json" ), WOW( R.string.wow, R.drawable.react_wow, "wow.json" ), BAD( R.string.bad, R.drawable.react_bad, "bad.json" ), ANGRY( R.string.angry, R.drawable.react_angry, "angry.json" ) }
gpl-3.0
08160b53adf784c04ac4c9ad1b8049a7
25.556291
89
0.603143
4.348156
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConvertNaNEqualityInspection.kt
4
2817
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ConvertNaNEqualityInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return binaryExpressionVisitor { expression -> if (expression.left.isNaNExpression() || expression.right.isNaNExpression()) { val inverted = when (expression.operationToken) { KtTokens.EXCLEQ -> true KtTokens.EQEQ -> false else -> return@binaryExpressionVisitor } holder.registerProblem( expression, KotlinBundle.message("equality.check.with.nan.should.be.replaced.with.isnan"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ConvertNaNEqualityQuickFix(inverted) ) } } } } private class ConvertNaNEqualityQuickFix(val inverted: Boolean) : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.na.n.equality.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtBinaryExpression ?: return val other = when { element.left.isNaNExpression() -> element.right ?: return element.right.isNaNExpression() -> element.left ?: return else -> return } val pattern = if (inverted) "!$0.isNaN()" else "$0.isNaN()" element.replace(KtPsiFactory(element).createExpressionByPattern(pattern, other)) } } private val NaNSet = setOf("kotlin.Double.Companion.NaN", "java.lang.Double.NaN", "kotlin.Float.Companion.NaN", "java.lang.Float.NaN") private fun KtExpression?.isNaNExpression(): Boolean { if (this?.text?.endsWith("NaN") != true) return false val fqName = this.resolveToCall()?.resultingDescriptor?.fqNameUnsafe?.asString() return NaNSet.contains(fqName) }
apache-2.0
2a86a70a692b2a68b4da1683f315c447
43.714286
134
0.70536
4.873702
false
false
false
false
GunoH/intellij-community
platform/diff-impl/src/com/intellij/diff/actions/impl/MutableDiffRequestChain.kt
2
7648
// 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.intellij.diff.actions.impl import com.intellij.diff.DiffContext import com.intellij.diff.DiffContextEx import com.intellij.diff.DiffRequestFactory import com.intellij.diff.chains.DiffRequestChain import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.FileContent import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeys.ThreeSideDiffColors import com.intellij.diff.util.Side import com.intellij.diff.util.ThreeSide import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import javax.swing.JComponent class MutableDiffRequestChain( var content1: DiffContent, var baseContent: DiffContent?, var content2: DiffContent ) : UserDataHolderBase(), DiffRequestChain { private val producer = MyDiffRequestProducer() private val requestUserData: MutableMap<Key<*>, Any> = mutableMapOf() var windowTitle: String? = null var title1: String? = getTitleFor(content1) var title2: String? = getTitleFor(content2) var baseTitle: String? = baseContent?.let { getTitleFor(it) } var baseColorMode: ThreeSideDiffColors = ThreeSideDiffColors.LEFT_TO_RIGHT constructor(content1: DiffContent, content2: DiffContent) : this(content1, null, content2) fun <T : Any> putRequestUserData(key: Key<T>, value: T) { requestUserData.put(key, value) } override fun getRequests(): List<DiffRequestProducer> = listOf(producer) override fun getIndex(): Int = 0 private inner class MyDiffRequestProducer : DiffRequestProducer { override fun getName(): String { return DiffBundle.message("diff.files.generic.request.title") } override fun getContentType(): FileType? = content1.contentType ?: content2.contentType override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { val request = if (baseContent != null) { SimpleDiffRequest(windowTitle, content1, baseContent!!, content2, title1, baseTitle, title2).also { putUserData(DiffUserDataKeys.THREESIDE_DIFF_COLORS_MODE, baseColorMode) } } else { SimpleDiffRequest(windowTitle, content1, content2, title1, title2) } request.putUserData(CHAIN_KEY, this@MutableDiffRequestChain) requestUserData.forEach { key, value -> @Suppress("UNCHECKED_CAST") request.putUserData(key as Key<Any>, value) } return request } } companion object { private val CHAIN_KEY = Key.create<MutableDiffRequestChain>("Diff.MutableDiffRequestChain") fun createHelper(context: DiffContext, request: DiffRequest): Helper? { if (context !is DiffContextEx) return null val chain = request.getUserData(CHAIN_KEY) ?: return null return Helper(chain, context) } fun createHelper(dataContext: DataContext): Helper? { val context = dataContext.getData(DiffDataKeys.DIFF_CONTEXT) ?: return null val request = dataContext.getData(DiffDataKeys.DIFF_REQUEST) ?: return null return createHelper(context, request) } } data class Helper(val chain: MutableDiffRequestChain, val context: DiffContextEx) { fun setContent(newContent: DiffContent, side: Side) { setContent(newContent, getTitleFor(newContent), side) } fun setContent(newContent: DiffContent, side: ThreeSide) { setContent(newContent, getTitleFor(newContent), side) } fun setContent(newContent: DiffContent, title: String?, side: Side) { setContent(newContent, title, side.selectNotNull(ThreeSide.LEFT, ThreeSide.RIGHT)) } fun setContent(newContent: DiffContent, title: String?, side: ThreeSide) { when (side) { ThreeSide.LEFT -> { chain.content1 = newContent chain.title1 = title } ThreeSide.RIGHT -> { chain.content2 = newContent chain.title2 = title } ThreeSide.BASE -> { chain.baseContent = newContent chain.baseTitle = title } } } fun fireRequestUpdated() { chain.requestUserData.clear() context.reloadDiffRequest() } } } internal class SwapDiffSidesAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isEnabledAndVisible = helper.chain.baseContent == null } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext)!! val oldContent1 = helper.chain.content1 val oldContent2 = helper.chain.content2 val oldTitle1 = helper.chain.title1 val oldTitle2 = helper.chain.title2 helper.setContent(oldContent1, oldTitle1, Side.RIGHT) helper.setContent(oldContent2, oldTitle2, Side.LEFT) helper.fireRequestUpdated() } } internal class SwapThreeWayColorModeAction : ComboBoxAction() { override fun update(e: AnActionEvent) { val presentation = e.presentation val helper = MutableDiffRequestChain.createHelper(e.dataContext) if (helper != null) { presentation.text = getText(helper.chain.baseColorMode) presentation.isEnabledAndVisible = true && helper.chain.baseContent != null } else { presentation.isEnabledAndVisible = false } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun createPopupActionGroup(button: JComponent, context: DataContext): DefaultActionGroup { return DefaultActionGroup(ThreeSideDiffColors.values().map { MyAction(getText(it), it) }) } private fun getText(option: ThreeSideDiffColors): @NlsActions.ActionText String { return when (option) { ThreeSideDiffColors.MERGE_CONFLICT -> DiffBundle.message("option.three.side.color.policy.merge.conflict") ThreeSideDiffColors.MERGE_RESULT -> DiffBundle.message("option.three.side.color.policy.merge.resolved") ThreeSideDiffColors.LEFT_TO_RIGHT -> DiffBundle.message("option.three.side.color.policy.left.to.right") } } private inner class MyAction(text: @NlsActions.ActionText String, val option: ThreeSideDiffColors) : DumbAwareAction(text) { override fun actionPerformed(e: AnActionEvent) { val helper = MutableDiffRequestChain.createHelper(e.dataContext) ?: return helper.chain.baseColorMode = option helper.fireRequestUpdated() } } } private fun getTitleFor(content: DiffContent) = if (content is FileContent) DiffRequestFactory.getInstance().getContentTitle(content.file) else null
apache-2.0
2273fd0aae106dc1571f6079514bf1b4
36.307317
140
0.743201
4.475132
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/fetch/GitFetchSupportImpl.kt
2
14508
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.fetch import com.intellij.dvcs.MultiMessage import com.intellij.dvcs.MultiRootMessage import com.intellij.externalProcessAuthHelper.AuthenticationGate import com.intellij.externalProcessAuthHelper.RestrictingAuthenticationGate import com.intellij.notification.NotificationType import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.Pair import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.VcsNotifier.STANDARD_NOTIFICATION import com.intellij.openapi.vcs.changes.actions.VcsStatisticsCollector import com.intellij.util.concurrency.AppExecutorUtil import git4idea.GitNotificationIdsHolder import git4idea.GitUtil.findRemoteByName import git4idea.GitUtil.mention import git4idea.commands.Git import git4idea.commands.GitAuthenticationListener.GIT_AUTHENTICATION_SUCCESS import git4idea.commands.GitImpl import git4idea.config.GitConfigUtil import git4idea.i18n.GitBundle import git4idea.repo.GitRemote import git4idea.repo.GitRemote.ORIGIN import git4idea.repo.GitRepository import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern private val LOG = logger<GitFetchSupportImpl>() private val PRUNE_PATTERN = Pattern.compile("\\s*x\\s*\\[deleted\\].*->\\s*(\\S*)") // x [deleted] (none) -> origin/branch private const val MAX_SSH_CONNECTIONS = 10 // by default SSH server has a limit of 10 multiplexed ssh connection internal class GitFetchSupportImpl(private val project: Project) : GitFetchSupport { private val git get() = Git.getInstance() as GitImpl private val progressManager get() = ProgressManager.getInstance() private val fetchQueue = GitRemoteOperationQueueImpl() private val fetchRequestCounter = AtomicInteger() override fun getDefaultRemoteToFetch(repository: GitRepository): GitRemote? { val remotes = repository.remotes return when { remotes.isEmpty() -> null remotes.size == 1 -> remotes.first() else -> { // this emulates behavior of the native `git fetch`: // if current branch doesn't give a hint, then return "origin"; if there is no "origin", don't guess and fail repository.currentBranch?.findTrackedBranch(repository)?.remote ?: findRemoteByName(repository, ORIGIN) } } } override fun fetchDefaultRemote(repositories: Collection<GitRepository>): GitFetchResult { val remotesToFetch = mutableListOf<RemoteRefCoordinates>() for (repository in repositories) { val remote = getDefaultRemoteToFetch(repository) if (remote != null) remotesToFetch.add(RemoteRefCoordinates(repository, remote)) else LOG.info("No remote to fetch found in $repository") } return fetch(remotesToFetch) } override fun fetchAllRemotes(repositories: Collection<GitRepository>): GitFetchResult { val remotesToFetch = mutableListOf<RemoteRefCoordinates>() for (repository in repositories) { if (repository.remotes.isEmpty()) { LOG.info("No remote to fetch found in $repository") } else { for (remote in repository.remotes) { remotesToFetch.add(RemoteRefCoordinates(repository, remote)) } } } return fetch(remotesToFetch) } override fun fetch(repository: GitRepository, remote: GitRemote): GitFetchResult { return fetch(listOf(RemoteRefCoordinates(repository, remote))) } override fun fetch(repository: GitRepository, remote: GitRemote, refspec: @NonNls String): GitFetchResult { return fetch(listOf(RemoteRefCoordinates(repository, remote, refspec))) } override fun fetchRemotes(remotes: Collection<Pair<GitRepository, GitRemote>>): GitFetchResult { return fetch(remotes.map { RemoteRefCoordinates(it.first, it.second) }) } private fun fetch(arguments: List<RemoteRefCoordinates>): GitFetchResult { try { fetchRequestCounter.incrementAndGet() return withIndicator { val activity = VcsStatisticsCollector.FETCH_ACTIVITY.started(project) val tasks = fetchInParallel(arguments) val results = waitForFetchTasks(tasks) val mergedResults = mutableMapOf<GitRepository, RepoResult>() val succeedResults = mutableListOf<SingleRemoteResult>() for (result in results) { val res = mergedResults[result.repository] mergedResults[result.repository] = mergeRepoResults(res, result) if (result.success()) succeedResults.add(result) } val successFetchesMap = succeedResults.groupBy({ it.repository }, { it.remote }) if (successFetchesMap.isNotEmpty()) { GitFetchHandler.afterSuccessfulFetch(project, successFetchesMap, progressManager.progressIndicator ?: EmptyProgressIndicator()) } activity.finished() FetchResultImpl(project, VcsNotifier.getInstance(project), mergedResults) } } finally { fetchRequestCounter.decrementAndGet() } } private fun mergeRepoResults(firstResult: RepoResult?, secondResult: SingleRemoteResult): RepoResult { if (firstResult == null) { return RepoResult(mapOf(secondResult.remote to secondResult)) } else { return RepoResult(firstResult.results + (secondResult.remote to secondResult)) } } override fun isFetchRunning() = fetchRequestCounter.get() > 0 private fun fetchInParallel(remotes: List<RemoteRefCoordinates>): List<FetchTask> { val tasks = mutableListOf<FetchTask>() val maxThreads = getMaxThreads(remotes.mapTo(HashSet()) { it.repository }, remotes.size) LOG.debug("Fetching $remotes using $maxThreads threads") val executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("GitFetch pool", maxThreads) val commonIndicator = progressManager.progressIndicator ?: EmptyProgressIndicator() val authenticationGate = RestrictingAuthenticationGate() for ((repository, remote, refspec) in remotes) { LOG.debug("Fetching $remote in $repository") val future: Future<SingleRemoteResult> = executor.submit<SingleRemoteResult> { commonIndicator.checkCanceled() lateinit var result: SingleRemoteResult ProgressManager.getInstance().executeProcessUnderProgress({ commonIndicator.checkCanceled() result = fetchQueue.executeForRemote(repository, remote) { doFetch(repository, remote, refspec, authenticationGate) } }, commonIndicator) result } tasks.add(FetchTask(repository, remote, future)) } return tasks } private fun getMaxThreads(repositories: Collection<GitRepository>, numberOfRemotes: Int): Int { val config = Registry.intValue("git.parallel.fetch.threads") val maxThreads = when { config > 0 -> config config == -1 -> Runtime.getRuntime().availableProcessors() config == -2 -> numberOfRemotes config == -3 -> Math.min(numberOfRemotes, Runtime.getRuntime().availableProcessors() * 2) else -> 1 } if (isStoreCredentialsHelperUsed(repositories)) { return 1 } return Math.min(maxThreads, MAX_SSH_CONNECTIONS) } private fun isStoreCredentialsHelperUsed(repositories: Collection<GitRepository>): Boolean { return repositories.any { GitConfigUtil.getValue(project, it.root, "credential.helper").equals("store", ignoreCase = true) } } private fun waitForFetchTasks(tasks: List<FetchTask>): List<SingleRemoteResult> { val results = mutableListOf<SingleRemoteResult>() for (task in tasks) { try { results.add(task.future.get()) } catch (e: CancellationException) { throw ProcessCanceledException(e) } catch (e: InterruptedException) { throw ProcessCanceledException(e) } catch (e: ExecutionException) { if (e.cause is ProcessCanceledException) throw e.cause as ProcessCanceledException results.add(SingleRemoteResult(task.repository, task.remote, e.cause?.message ?: GitBundle.message("error.dialog.title"), emptyList())) LOG.error(e) } } return results } private fun <T> withIndicator(operation: () -> T): T { val indicator = progressManager.progressIndicator val prevText = indicator?.text indicator?.text = GitBundle.message("git.fetch.progress") try { return operation() } finally { indicator?.text = prevText } } private fun doFetch(repository: GitRepository, remote: GitRemote, refspec: String?, authenticationGate: AuthenticationGate? = null) : SingleRemoteResult { val recurseSubmodules = "--recurse-submodules=no" val params = if (refspec == null) arrayOf(recurseSubmodules) else arrayOf(refspec, recurseSubmodules) val result = git.fetch(repository, remote, emptyList(), authenticationGate, *params) val pruned = result.output.mapNotNull { getPrunedRef(it) } if (result.success()) { BackgroundTaskUtil.syncPublisher(repository.project, GIT_AUTHENTICATION_SUCCESS).authenticationSucceeded(repository, remote) repository.update() } val error = if (result.success()) null else result.errorOutputAsJoinedString return SingleRemoteResult(repository, remote, error, pruned) } private fun getPrunedRef(line: String): String? { val matcher = PRUNE_PATTERN.matcher(line) return if (matcher.matches()) matcher.group(1) else null } private data class RemoteRefCoordinates(val repository: GitRepository, val remote: GitRemote, val refspec: String? = null) private class FetchTask(val repository: GitRepository, val remote: GitRemote, val future: Future<SingleRemoteResult>) private class RepoResult(val results: Map<GitRemote, SingleRemoteResult>) { fun totallySuccessful() = results.values.all { it.success() } fun error(): @Nls String { val errorMessage = multiRemoteMessage(true) for ((remote, result) in results) { if (result.error != null) errorMessage.append(remote, result.error) } return errorMessage.asString() } fun prunedRefs(): @NlsSafe String { val prunedRefs = multiRemoteMessage(false) for ((remote, result) in results) { if (result.prunedRefs.isNotEmpty()) prunedRefs.append(remote, result.prunedRefs.joinToString("\n")) } return prunedRefs.asString() } /* For simplicity, remote and repository results are merged separately. It means that they are not merged, if two repositories have two remotes, and then fetch succeeds for the first remote in both repos, and fails for the second remote in both repos. Such cases are rare, and can be handled when actual problem is reported. */ private fun multiRemoteMessage(remoteInPrefix: Boolean) = MultiMessage(results.keys, GitRemote::getName, GitRemote::getName, remoteInPrefix) } private class SingleRemoteResult(val repository: GitRepository, val remote: GitRemote, val error: @Nls String?, val prunedRefs: List<String>) { fun success() = error == null } private class FetchResultImpl(val project: Project, val vcsNotifier: VcsNotifier, val results: Map<GitRepository, RepoResult>) : GitFetchResult { private val isFailed = results.values.any { !it.totallySuccessful() } override fun showNotification() { doShowNotification() } override fun showNotificationIfFailed(): Boolean { if (isFailed) doShowNotification(null) return !isFailed } override fun showNotificationIfFailed(title: @Nls String): Boolean { if (isFailed) doShowNotification(title) return !isFailed } private fun doShowNotification(failureTitle: @Nls String? = null) { val type = if (!isFailed) NotificationType.INFORMATION else NotificationType.ERROR val message = buildMessage(failureTitle) val notification = STANDARD_NOTIFICATION.createNotification(message, type) notification.setDisplayId(if (!isFailed) GitNotificationIdsHolder.FETCH_RESULT else GitNotificationIdsHolder.FETCH_RESULT_ERROR) vcsNotifier.notify(notification) } override fun throwExceptionIfFailed() { if (isFailed) throw VcsException(buildMessage(null)) } private fun buildMessage(failureTitle: @Nls String?): @Nls String { val roots = results.keys.map { it.root } val errorMessage = MultiRootMessage(project, roots, true) val prunedRefs = MultiRootMessage(project, roots) val failed = results.filterValues { !it.totallySuccessful() } for ((repo, result) in failed) { errorMessage.append(repo.root, result.error()) } for ((repo, result) in results) { prunedRefs.append(repo.root, result.prunedRefs()) } val sb = HtmlBuilder() if (!isFailed) { sb.append(HtmlChunk.text(GitBundle.message("notification.title.fetch.success")).bold()) } else { sb.append(HtmlChunk.text(failureTitle ?: GitBundle.message("notification.title.fetch.failure")).bold()) if (failed.size != roots.size) { sb.append(mention(failed.keys)) } } appendDetails(sb, errorMessage) appendDetails(sb, prunedRefs) return sb.toString() } private fun appendDetails(sb: HtmlBuilder, details: MultiRootMessage) { val text = details.asString() if (text.isNotEmpty()) { sb.br().append(text) } } } }
apache-2.0
ba008d7c8eaf5371ff23f4c5c5d226cb
40.333333
145
0.706231
4.663452
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/util/ThemedFragment.kt
2
1206
package org.thoughtcrime.securesms.util import android.os.Bundle import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.annotation.StyleRes import androidx.fragment.app.Fragment /** * "Mixin" to theme a Fragment with the given themeResId. This is making me wish Kotlin * had a stronger generic type system. */ object ThemedFragment { private const val UNSET = -1 private const val THEME_RES_ID = "ThemedFragment::theme_res_id" @JvmStatic val Fragment.themeResId: Int get() = arguments?.getInt(THEME_RES_ID) ?: UNSET @JvmStatic fun Fragment.themedInflate(@LayoutRes layoutId: Int, inflater: LayoutInflater, container: ViewGroup?): View? { return if (themeResId != UNSET) { inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)).inflate(layoutId, container, false) } else { inflater.inflate(layoutId, container, false) } } @JvmStatic fun Fragment.withTheme(@StyleRes themeId: Int): Fragment { arguments = (arguments ?: Bundle()).apply { putInt(THEME_RES_ID, themeId) } return this } }
gpl-3.0
ce084560855e73a5cd569ea555f12cde
28.414634
116
0.740464
4.246479
false
false
false
false
jk1/intellij-community
plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.kt
1
3359
// 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.github.extensions import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.project.Project import com.intellij.util.AuthData import git4idea.remote.GitHttpAuthDataProvider import org.jetbrains.plugins.github.api.GithubApiTaskExecutor import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import java.io.IOException class GithubHttpAuthDataProvider(private val authenticationManager: GithubAuthenticationManager, private val apiTaskExecutor: GithubApiTaskExecutor, private val accountInformationProvider: GithubAccountInformationProvider, private val authenticationFailureManager: GithubAccountGitAuthenticationFailureManager) : GitHttpAuthDataProvider { private val LOG = logger<GithubHttpAuthDataProvider>() override fun getAuthData(project: Project, url: String): GithubAccountAuthData? { return getSuitableAccounts(project, url, null).singleOrNull()?.let { account -> try { val token = authenticationManager.getTokenForAccount(account) ?: return null val username = apiTaskExecutor.execute(DumbProgressIndicator(), account, accountInformationProvider.usernameTask, true) GithubAccountAuthData(account, username, token) } catch (e: IOException) { LOG.info("Cannot load username for $account", e) null } } } override fun getAuthData(project: Project, url: String, login: String): GithubAccountAuthData? { return getSuitableAccounts(project, url, login).singleOrNull()?.let { account -> return authenticationManager.getTokenForAccount(account)?.let { GithubAccountAuthData(account, login, it) } } } override fun forgetPassword(url: String, authData: AuthData) { if (authData is GithubAccountAuthData) { authenticationFailureManager.ignoreAccount(url, authData.account) } } fun getSuitableAccounts(project: Project, url: String, login: String?): Set<GithubAccount> { var potentialAccounts = authenticationManager.getAccounts() .filter { it.server.matches(url) } .filter { !authenticationFailureManager.isAccountIgnored(url, it) } if (login != null) { potentialAccounts = potentialAccounts.filter { try { apiTaskExecutor.execute(DumbProgressIndicator(), it, accountInformationProvider.usernameTask, true) == login } catch (e: IOException) { LOG.info("Cannot load username for $it", e) false } } } val defaultAccount = authenticationManager.getDefaultAccount(project) if (defaultAccount != null && potentialAccounts.contains(defaultAccount)) return setOf(defaultAccount) return potentialAccounts.toSet() } class GithubAccountAuthData(val account: GithubAccount, login: String, password: String) : AuthData(login, password) }
apache-2.0
2e47982b83a15c004abad7922c256520
45.027397
148
0.727597
5.215839
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyboard/sticker/StickerInsetSetter.kt
3
885
package org.thoughtcrime.securesms.keyboard.sticker import android.graphics.Rect import android.view.View import androidx.appcompat.widget.AppCompatTextView import androidx.recyclerview.widget.RecyclerView import org.thoughtcrime.securesms.util.InsetItemDecoration import org.thoughtcrime.securesms.util.ViewUtil private val horizontalInset: Int = ViewUtil.dpToPx(8) private val verticalInset: Int = ViewUtil.dpToPx(8) /** * Set insets for sticker items in a [RecyclerView]. For use in [InsetItemDecoration]. */ class StickerInsetSetter : InsetItemDecoration.SetInset() { override fun setInset(outRect: Rect, view: View, parent: RecyclerView) { val isHeader = view.javaClass == AppCompatTextView::class.java outRect.left = horizontalInset outRect.right = horizontalInset outRect.top = verticalInset outRect.bottom = if (isHeader) 0 else verticalInset } }
gpl-3.0
dd66e90eeaae947242a7969d496d23a6
34.4
86
0.79096
4.338235
false
false
false
false
JetBrains-Research/viktor
src/test/kotlin/org/jetbrains/bio/viktor/F64ArraySlicingTest.kt
1
6926
package org.jetbrains.bio.viktor import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Test import kotlin.test.assertFailsWith class F64FlatArraySlicingTest { @Test fun slice() { val v = F64Array.of(1.0, 2.0, 3.0) val slice = v.slice(1, 2) assertEquals(1, slice.length) assertEquals(F64Array.of(2.0), slice) slice[0] = 42.0 assertEquals(F64Array.of(1.0, 42.0, 3.0), v) } @Test fun sliceMatrix() { val m = F64Array.of( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 ).reshape(2, 3) assertEquals( F64Array.of(1.0, 2.0, 3.0).reshape(1, 3), m.slice(0, 1) ) assertEquals( F64Array.of(4.0, 5.0, 6.0).reshape(1, 3), m.slice(1, 2) ) assertEquals( F64Array.of( 1.0, 4.0 ).reshape(2, 1), m.slice(0, 1, axis = 1) ) assertEquals( F64Array.of( 2.0, 3.0, 5.0, 6.0 ).reshape(2, 2), m.slice(1, 3, axis = 1) ) } @Test fun sliceWithStep() { val v = F64Array.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0) v.slice(step = 2).let { assertEquals(3, it.length) assertEquals(F64Array.of(1.0, 3.0, 5.0), it) } v.slice(1, step = 2).let { assertEquals(3, it.length) assertEquals(F64Array.of(2.0, 4.0, 6.0), it) } v.slice(1, step = 3).let { assertEquals(2, it.length) assertEquals(F64Array.of(2.0, 5.0), it) } v.slice(1, step = 4).let { assertEquals(2, it.length) assertEquals(F64Array.of(2.0, 6.0), it) } } @Test(expected = IllegalStateException::class) fun sliceOutOfBounds() { F64Array(7).slice(10, 42) } @Test(expected = IllegalArgumentException::class) fun sliceFromNegative() { F64Array(7).slice(-1, 5) } @Test(expected = IllegalArgumentException::class) fun sliceToBeforeFrom() { F64Array(7).slice(3, 1) } @Test(expected = IllegalArgumentException::class) fun sliceStepNegative() { F64Array(7).slice(3, 5, -1) } @Test(expected = IllegalArgumentException::class) fun sliceInvalidAxis() { F64Array(7).slice(1, 3, axis = 1) } } class F64ArraySlicing { @Test fun rowView() { val m = F64Array.of( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 ).reshape(3, 2) assertEquals(F64Array.of(0.0, 1.0), m.V[0]) assertEquals(F64Array.of(2.0, 3.0), m.V[1]) assertEquals(F64Array.of(4.0, 5.0), m.V[2]) assertFailsWith<IndexOutOfBoundsException> { m.V[42] } } @Test fun columnView() { val m = F64Array.of( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 ).reshape(3, 2) assertEquals(F64Array.of(0.0, 2.0, 4.0), m.V[_I, 0]) assertEquals(F64Array.of(1.0, 3.0, 5.0), m.V[_I, 1]) assertFailsWith<IndexOutOfBoundsException> { m.V[_I, 42] } } @Test fun view() { val m = F64Array.of( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 ).reshape(3, 1, 2) assertEquals(F64Array.of(0.0, 1.0).reshape(1, 2), m.V[0]) assertEquals(F64Array.of(2.0, 3.0).reshape(1, 2), m.V[1]) assertEquals(F64Array.of(4.0, 5.0).reshape(1, 2), m.V[2]) assertFailsWith<IndexOutOfBoundsException> { m.V[42] } } @Test fun reshape2() { val v = F64Array.of(0.0, 1.0, 2.0, 3.0, 4.0, 5.0) assertArrayEquals( arrayOf( doubleArrayOf(0.0, 1.0, 2.0), doubleArrayOf(3.0, 4.0, 5.0) ), v.reshape(2, 3).toGenericArray() ) assertArrayEquals( arrayOf( doubleArrayOf(0.0, 1.0), doubleArrayOf(2.0, 3.0), doubleArrayOf(4.0, 5.0) ), v.reshape(3, 2).toGenericArray() ) } @Test fun reshape2WithStride() { val v = F64FlatArray.create( doubleArrayOf( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 ), 0, size = 4, stride = 2 ) assertArrayEquals( arrayOf(doubleArrayOf(0.0, 2.0), doubleArrayOf(4.0, 6.0)), v.reshape(2, 2).toGenericArray() ) } @Test fun reshape3() { val v = F64Array.of( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 ) assertArrayEquals( arrayOf( arrayOf(doubleArrayOf(0.0, 1.0)), arrayOf(doubleArrayOf(2.0, 3.0)), arrayOf(doubleArrayOf(4.0, 5.0)) ), v.reshape(3, 1, 2).toGenericArray() ) assertArrayEquals( arrayOf( arrayOf(doubleArrayOf(0.0), doubleArrayOf(1.0)), arrayOf(doubleArrayOf(2.0), doubleArrayOf(3.0)), arrayOf(doubleArrayOf(4.0), doubleArrayOf(5.0)) ), v.reshape(3, 2, 1).toGenericArray() ) } @Test fun reshape3WithStride() { val v = F64FlatArray.create(doubleArrayOf(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0), 0, size = 4, stride = 2) assertArrayEquals( arrayOf( arrayOf(doubleArrayOf(0.0, 2.0)), arrayOf(doubleArrayOf(4.0, 6.0)) ), v.reshape(2, 1, 2).toGenericArray() ) assertArrayEquals( arrayOf( arrayOf(doubleArrayOf(0.0), doubleArrayOf(2.0)), arrayOf(doubleArrayOf(4.0), doubleArrayOf(6.0)) ), v.reshape(2, 2, 1).toGenericArray() ) } @Test fun along0() { val a = F64Array.of( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 ).reshape(2, 3) a.along(0).forEach { it /= it[0] } assertEquals( F64Array.of( 1.0, 2.0, 3.0, 1.0, 5.0 / 4.0, 6.0 / 4.0 ).reshape(2, 3), a ) } @Test fun along1() { val a = F64Array.of(1.0, 2.0, 3.0, 4.0, 5.0, 6.0).reshape(2, 3) a.along(1).forEach { it /= it[1] } assertEquals( F64Array.of( 1.0 / 4.0, 2.0 / 5.0, 3.0 / 6.0, 1.0, 1.0, 1.0 ).reshape(2, 3), a ) } @Test fun view2() { val a = DoubleArray(8) { it.toDouble() }.asF64Array().reshape(2, 2, 2) val aView = a.view(0, 1) assertEquals(F64Array.of(0.0, 1.0, 4.0, 5.0).reshape(2, 2), aView) aView.expInPlace() assertEquals(F64Array.of(2.0, 3.0, 6.0, 7.0).reshape(2, 2), a.view(1, 1)) } }
mit
5f3b2d1a0598c22ab924cd40314a3fe0
26.59761
81
0.469824
3.133937
false
true
false
false
FountainMC/FountainAPI
src/main/kotlin/org/fountainmc/api/world/block/plants/GrowingPlant.kt
1
1207
package org.fountainmc.api.world.block.plants import org.fountainmc.api.BlockType import javax.annotation.Nonnegative interface GrowingPlant : Plant { override val blockType: BlockType<GrowingPlant> val growthPercentage: Double get() = growth / maxGrowth.toDouble() // NOTE a utility wither for 'withGrowthPercentage' is left out here because // plugins should explicitly handle getMaxGrowth() val growth: Int /** * Get a copy of this plant with the given growth level * * @param growth the growth level * @return the new plant * @throws IllegalArgumentException if the growth level is negative or greater than [maxGrowth] */ fun withGrowth(growth: Int) = copy(growth = growth) /** * Return a copy of this state with the specified values. */ fun copy(growth: Int = this.growth): GrowingPlant /** * A utility method to get this type of plant's maximum growth height * * All block states of the same type must have the same maximum growth height. * @return the maximum growth height */ @get:Nonnegative val maxGrowth: Int val isFresh: Boolean get() = growth == 0 }
mit
492b49fea5d99d581b1195f86e933f68
26.431818
99
0.675228
4.373188
false
false
false
false
pureal-code/pureal-os
tests.traits/src/net/pureal/tests/traits/ComposedSpecs.kt
1
1574
package net.pureal.tests.traits.math import org.jetbrains.spek.api.* import net.pureal.traits.* import net.pureal.traits.graphics.* import net.pureal.traits.math.* class ComposedSpecs : Spek() {init { given("a composed element of a rectangle and a circle") { val c = coloredElement(shape = circle(0.6), fill = Fills.solid(Colors.red)) val r = coloredElement(shape = rectangle(vector(1, 1)), fill = Fills.solid(Colors.blue)) val x = composed(observableIterable(listOf(c, r) map { transformedElement(it) : TransformedElement<*> })) on("getting the shape") { val s = x.shape it("should be the concatenated shape") { shouldBeTrue(s.contains(vector(0, 0.59))) shouldBeTrue(s.contains(vector(0.499, 0.499))) shouldBeFalse(s.contains(vector(0.51, 0.35))) } } on("getting the elements at a location contained by all elements") { val e = x.elementsAt(vector(0, 0)) it("should return all elements") { shouldEqual(2, e.count()) shouldEqual(c.shape, e.elementAt(0).element.shape) shouldEqual(r.shape, e.elementAt(1).element.shape) } } on("getting the elements at a location contained only by the circle") { val e = x.elementsAt(vector(0, 0.59)) it("should return the circle") { shouldEqual(c.shape, e.single().element.shape) } } } } }
bsd-3-clause
ab6057e52d0f077dac6f9b9faaf36047
34.604651
113
0.566709
4.005089
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/basic/ArrowExample.kt
2
4610
package graphics.scenery.tests.examples.basic import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.primitives.Arrow import graphics.scenery.attribute.material.DefaultMaterial import graphics.scenery.attribute.material.Material import graphics.scenery.utils.extensions.minus import kotlin.concurrent.thread import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin /** * Simple example to demonstrate the drawing of 3D arrows/vectors. * * This example will draw a circle made of vectors using * the [Arrow] class. One vector will, however, always * illuminate differently, and the position of such will * circulate... * * @author Vladimir Ulman <[email protected]> */ class ArrowExample : SceneryBase("ArrowExample") { override fun init() { renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) setupScene() useScene() } private fun setupScene() { //boundaries of our world val hull = Box(Vector3f(50.0f, 50.0f, 50.0f), insideNormals = true) hull.material { diffuse = Vector3f(0.2f, 0.2f, 0.2f) cullingMode = Material.CullingMode.Front } scene.addChild(hull) //lights and camera var pl = emptyArray<PointLight>() for (i in 0..3) { val l = PointLight(radius = 200.0f) l.intensity = 5.0f l.emissionColor = Vector3f(1.0f) scene.addChild(l) pl = pl.plus(l) } pl[0].spatial().position = Vector3f(0f,10f,0f) pl[1].spatial().position = Vector3f(0f,-10f,0f) pl[2].spatial().position = Vector3f(-10f,0f,0f) pl[3].spatial().position = Vector3f(10f,0f,0f) val cam: Camera = DetachedHeadCamera() cam.spatial().position = Vector3f(0.0f, 0.0f, 15.0f) cam.perspectiveCamera(50.0f, windowWidth, windowHeight) scene.addChild(cam) } private fun useScene() { //we shall have faint and bright vectors... val matBright = DefaultMaterial() matBright.diffuse = Vector3f(0.0f, 1.0f, 0.0f) matBright.ambient = Vector3f(1.0f, 1.0f, 1.0f) matBright.specular = Vector3f(1.0f, 1.0f, 1.0f) matBright.cullingMode = Material.CullingMode.None val matFaint = DefaultMaterial() matFaint.diffuse = Vector3f(0.0f, 0.6f, 0.6f) matFaint.ambient = Vector3f(1.0f, 1.0f, 1.0f) matFaint.specular = Vector3f(1.0f, 1.0f, 1.0f) matFaint.cullingMode = Material.CullingMode.None //... arranged along a circle val circleCentre = Vector3f(0.0f) val circleRadius = 6.0f val arrowsInCircle = 30 //create the circle of vectors var al = emptyArray<Arrow>() var lastPos = Vector3f(circleRadius,0f,0f) var currPos : Vector3f for (i in 1..arrowsInCircle) { val curAng = (i*2.0f* PI/arrowsInCircle).toFloat() currPos = Vector3f(circleRadius*cos(curAng) +circleCentre.x(), circleRadius*sin(curAng) +circleCentre.y(), circleCentre.z()) // ========= this is how you create an Arrow ========= val a = Arrow(currPos - lastPos) //shape of the vector itself a.spatial { position = lastPos //position/base of the vector } a.addAttribute(Material::class.java, matFaint) //usual stuff follows... a.edgeWidth = 0.5f scene.addChild(a) // if you want to change the shape and position of the vector later, // you can use this (instead of creating a new vector) // a.reshape( newVector ) // a.position = newBase // ========= this is how you create an Arrow ========= al = al.plus(a) lastPos = currPos } //finally, have some fun... thread { var i = 0 while (true) { al[i].addAttribute(Material::class.java, matFaint) i = (i+1).rem(arrowsInCircle) al[i].addAttribute(Material::class.java, matBright) Thread.sleep(150) } } } override fun inputSetup() { setupCameraModeSwitching(keybinding = "C") } companion object { @JvmStatic fun main(args: Array<String>) { ArrowExample().main() } } }
lgpl-3.0
c6f8a4aa8a62f891fff02f509749a0e0
31.237762
107
0.58243
3.772504
false
false
false
false
google/android-fhir
datacapture/src/main/java/com/google/android/fhir/datacapture/views/QuestionnaireItemRadioGroupViewHolderFactory.kt
1
6162
/* * Copyright 2022 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.google.android.fhir.datacapture.views import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RadioButton import androidx.constraintlayout.helper.widget.Flow import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.children import com.google.android.fhir.datacapture.ChoiceOrientationTypes import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.choiceOrientation import com.google.android.fhir.datacapture.displayString import com.google.android.fhir.datacapture.validation.Invalid import com.google.android.fhir.datacapture.validation.NotValidated import com.google.android.fhir.datacapture.validation.Valid import com.google.android.fhir.datacapture.validation.ValidationResult import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse internal object QuestionnaireItemRadioGroupViewHolderFactory : QuestionnaireItemViewHolderFactory(R.layout.questionnaire_item_radio_group_view) { override fun getQuestionnaireItemViewHolderDelegate() = object : QuestionnaireItemViewHolderDelegate { private lateinit var header: QuestionnaireItemHeaderView private lateinit var radioGroup: ConstraintLayout private lateinit var flow: Flow override lateinit var questionnaireItemViewItem: QuestionnaireItemViewItem override fun init(itemView: View) { header = itemView.findViewById(R.id.header) radioGroup = itemView.findViewById(R.id.radio_group) flow = itemView.findViewById(R.id.flow) } override fun bind(questionnaireItemViewItem: QuestionnaireItemViewItem) { val questionnaireItem = questionnaireItemViewItem.questionnaireItem header.bind(questionnaireItem) // Keep the Flow layout which is the first child radioGroup.removeViews(1, radioGroup.childCount - 1) val choiceOrientation = questionnaireItem.choiceOrientation ?: ChoiceOrientationTypes.VERTICAL when (choiceOrientation) { ChoiceOrientationTypes.HORIZONTAL -> { flow.setOrientation(Flow.HORIZONTAL) flow.setWrapMode(Flow.WRAP_CHAIN) } ChoiceOrientationTypes.VERTICAL -> { flow.setOrientation(Flow.VERTICAL) flow.setWrapMode(Flow.WRAP_NONE) } } questionnaireItemViewItem.answerOption .map { answerOption -> View.generateViewId() to answerOption } .onEach { populateViewWithAnswerOption(it.first, it.second, choiceOrientation) } .map { it.first } .let { flow.referencedIds = it.toIntArray() } } override fun displayValidationResult(validationResult: ValidationResult) { when (validationResult) { is NotValidated, Valid -> header.showErrorText(isErrorTextVisible = false) is Invalid -> { header.showErrorText(errorText = validationResult.getSingleStringValidationMessage()) } } } override fun setReadOnly(isReadOnly: Boolean) { // The Flow layout has index 0. The radio button indices start from 1. for (i in 1 until radioGroup.childCount) { val view = radioGroup.getChildAt(i) view.isEnabled = !isReadOnly } } private fun populateViewWithAnswerOption( viewId: Int, answerOption: Questionnaire.QuestionnaireItemAnswerOptionComponent, choiceOrientation: ChoiceOrientationTypes ) { val radioButtonItem = LayoutInflater.from(radioGroup.context) .inflate(R.layout.questionnaire_item_radio_button, null) var isCurrentlySelected = questionnaireItemViewItem.isAnswerOptionSelected(answerOption) val radioButton = radioButtonItem.findViewById<RadioButton>(R.id.radio_button).apply { id = viewId text = answerOption.displayString layoutParams = ViewGroup.LayoutParams( when (choiceOrientation) { ChoiceOrientationTypes.HORIZONTAL -> ViewGroup.LayoutParams.WRAP_CONTENT ChoiceOrientationTypes.VERTICAL -> ViewGroup.LayoutParams.MATCH_PARENT }, ViewGroup.LayoutParams.WRAP_CONTENT ) isChecked = isCurrentlySelected setOnClickListener { radioButton -> isCurrentlySelected = !isCurrentlySelected when (isCurrentlySelected) { true -> { updateAnswer(answerOption) val buttons = radioGroup.children.asIterable().filterIsInstance<RadioButton>() buttons.forEach { button -> uncheckIfNotButtonId(radioButton.id, button) } } false -> { questionnaireItemViewItem.clearAnswer() (radioButton as RadioButton).isChecked = false } } } } radioGroup.addView(radioButton) flow.addView(radioButton) } private fun uncheckIfNotButtonId(checkedId: Int, button: RadioButton) { if (button.id != checkedId) button.isChecked = false } private fun updateAnswer(answerOption: Questionnaire.QuestionnaireItemAnswerOptionComponent) { questionnaireItemViewItem.setAnswer( QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent().apply { value = answerOption.value } ) } } }
apache-2.0
86dd3d3cade2e468735e229aada2e7fa
40.918367
100
0.688413
5.280206
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/view/MaxHeightScrollView.kt
1
1823
package jp.juggler.subwaytooter.view import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.widget.ScrollView import jp.juggler.subwaytooter.R import kotlin.math.min class MaxHeightScrollView : ScrollView { var maxHeight: Int = 0 constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val a = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView) parseAttr(a) a.recycle() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { val a = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView, defStyleAttr, 0) parseAttr(a) a.recycle() } private fun parseAttr(a: TypedArray) { maxHeight = a.getDimensionPixelSize(R.styleable.MaxHeightScrollView_maxHeight, 0) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var heightMeasureSpec2 = heightMeasureSpec if (maxHeight > 0) { val hSize = MeasureSpec.getSize(heightMeasureSpec) when (MeasureSpec.getMode(heightMeasureSpec)) { MeasureSpec.AT_MOST -> heightMeasureSpec2 = MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.AT_MOST) MeasureSpec.UNSPECIFIED -> heightMeasureSpec2 = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST) MeasureSpec.EXACTLY -> heightMeasureSpec2 = MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.EXACTLY) } } super.onMeasure(widthMeasureSpec, heightMeasureSpec2) } }
apache-2.0
c7e135dd2a3de03a3b91b5c65f8955f7
36.787234
123
0.677455
4.953804
false
false
false
false
airbnb/epoxy
epoxy-composesample/src/main/java/com/airbnb/epoxy/compose/sample/ui/theme/Type.kt
1
809
package com.airbnb.epoxy.compose.sample.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
apache-2.0
36c25011cb5fdb925fa5db0654becca8
27.892857
50
0.692213
4.372973
false
false
false
false
cbeust/klaxon
kobalt/src/Build.kt
1
1378
import com.beust.kobalt.plugin.java.javaCompiler import com.beust.kobalt.plugin.kotlin.kotlinCompiler import com.beust.kobalt.plugin.packaging.assemble import com.beust.kobalt.plugin.publish.bintray import com.beust.kobalt.project object Version { val klaxon = "5.0.14-SNAPSHOT" val kotlin = "1.3.70" } val klaxon = project { name = "klaxon" group = "com.beust" artifactId = name version = Version.klaxon directory = "klaxon" dependencies { compile("org.jetbrains.kotlin:kotlin-reflect:${Version.kotlin}", "org.jetbrains.kotlin:kotlin-stdlib:${Version.kotlin}") } dependenciesTest { compile("org.testng:testng:6.13.1", "org.assertj:assertj-core:3.5.2", "org.jetbrains.kotlin:kotlin-test:${Version.kotlin}") } assemble { mavenJars {} } bintray { publish = true } javaCompiler { args("-source", "1.7", "-target", "1.7") } kotlinCompiler { args("-no-stdlib") } } val jackson = project(klaxon) { name = "klaxon-jackson" directory = "$name" group = "com.beust" artifactId = name version = "1.0.0" dependencies { compile("com.fasterxml.jackson.core:jackson-databind:2.9.6") } bintray { publish = true } assemble { mavenJars {} } }
apache-2.0
9bbdab09c51007a45a7513a8adb668f8
19.878788
72
0.597968
3.724324
false
true
false
false
paplorinc/intellij-community
plugins/editorconfig/src/org/editorconfig/language/schema/parser/handlers/impl/EditorConfigListDescriptorParseHandler.kt
4
2948
// 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.editorconfig.language.schema.parser.handlers.impl import com.google.gson.JsonObject import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigConstantDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigListDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigNumberDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigUnionDescriptor import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.ALLOW_REPETITIONS import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.LIST import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.MIN_LENGTH import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.OPTION import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.PAIR import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.TYPE import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaConstants.VALUES import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaException import org.editorconfig.language.schema.parser.EditorConfigJsonSchemaParser import org.editorconfig.language.schema.parser.handlers.EditorConfigDescriptorParseHandlerBase class EditorConfigListDescriptorParseHandler : EditorConfigDescriptorParseHandlerBase() { override val requiredKeys = listOf(TYPE, VALUES) override val optionalKeys = super.optionalKeys + listOf(MIN_LENGTH, ALLOW_REPETITIONS) override val forbiddenChildren = listOf(PAIR, LIST, OPTION) override fun doHandle(jsonObject: JsonObject, parser: EditorConfigJsonSchemaParser): EditorConfigDescriptor { val minLength = tryGetInt(jsonObject, MIN_LENGTH) ?: 0 val allowRepetitions = tryGetBoolean(jsonObject, ALLOW_REPETITIONS) ?: false val values = jsonObject[VALUES] if (!values.isJsonArray) throw EditorConfigJsonSchemaException(jsonObject) val children = values.asJsonArray.map(parser::parse) if (!children.all(::isAcceptable)) throw EditorConfigJsonSchemaException(jsonObject) val documentation = tryGetString(jsonObject, EditorConfigJsonSchemaConstants.DOCUMENTATION) val deprecation = tryGetString(jsonObject, EditorConfigJsonSchemaConstants.DEPRECATION) return EditorConfigListDescriptor(minLength, allowRepetitions, children, documentation, deprecation) } private fun isAcceptable(descriptor: EditorConfigDescriptor) = when (descriptor) { is EditorConfigConstantDescriptor -> true is EditorConfigNumberDescriptor -> true is EditorConfigUnionDescriptor -> true else -> false } }
apache-2.0
c51f3582eb82d87362a87a20bb9b8b3f
57.96
140
0.845658
5.245552
false
true
false
false
vladmm/intellij-community
platform/script-debugger/protocol/protocol-reader/src/GlobalScope.kt
1
2105
package org.jetbrains.protocolReader import gnu.trove.THashMap import gnu.trove.THashSet import java.util.* fun GlobalScope(typeWriters: Collection<TypeWriter<*>?>, basePackages: Collection<Map<Class<*>, String>>) = GlobalScope(State(typeWriters, basePackages)) open class GlobalScope(val state: State) { fun getTypeImplReference(typeWriter: TypeWriter<*>) = state.getTypeImplReference(typeWriter) fun requireFactoryGenerationAndGetName(typeWriter: TypeWriter<*>) = state.requireFactoryGenerationAndGetName(typeWriter) fun getTypeImplShortName(typeWriter: TypeWriter<*>) = state.getTypeImplShortName(typeWriter) fun newFileScope(output: StringBuilder) = FileScope(this, output) fun getTypeFactories() = state.typesWithFactoriesList } private class State(typeWriters: Collection<TypeWriter<*>?>, private val basePackages: Collection<Map<Class<*>, String>>) { private var typeToName: Map<TypeWriter<*>, String> private val typesWithFactories = THashSet<TypeWriter<*>>() val typesWithFactoriesList = ArrayList<TypeWriter<*>>(); init { var uniqueCode = 0 val result = THashMap<TypeWriter<*>, String>(typeWriters.size()) for (handler in typeWriters) { val conflict = result.put(handler, "M${Integer.toString(uniqueCode++, Character.MAX_RADIX)}") if (conflict != null) { throw RuntimeException() } } typeToName = result } fun getTypeImplReference(typeWriter: TypeWriter<*>): String { val localName = typeToName.get(typeWriter) if (localName != null) { return localName } for (base in basePackages) { val result = base.get(typeWriter.typeClass) if (result != null) { return result } } throw RuntimeException() } public fun requireFactoryGenerationAndGetName(typeWriter: TypeWriter<*>): String { val name = getTypeImplShortName(typeWriter) if (typesWithFactories.add(typeWriter)) { typesWithFactoriesList.add(typeWriter) } return name } fun getTypeImplShortName(typeWriter: TypeWriter<*>): String { return typeToName.get(typeWriter)!! } }
apache-2.0
aca911fac1d06606a6c7607b92f03ebc
31.384615
153
0.719715
4.488273
false
false
false
false
BenDoan/playground
kotlin/tools/src/logo/Logo.kt
1
496
package logo import react.* import react.dom.* import kotlinext.js.* import kotlinx.html.style @JsModule("src/logo/react.svg") external val reactLogo: dynamic @JsModule("src/logo/kotlin.svg") external val kotlinLogo: dynamic fun RBuilder.logo(height: Int = 100) { div("Logo") { attrs.jsStyle.height = height img(alt = "React logo.logo", src = reactLogo, classes = "Logo-react") {} img(alt = "Kotlin logo.logo", src = kotlinLogo, classes = "Logo-kotlin") {} } }
mit
25fb1e2aaa37c8838d24ba016245f257
25.105263
83
0.669355
3.351351
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InnerClassConversion.kt
2
1825
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.isLocalClass import org.jetbrains.kotlin.nj2k.tree.JKClass import org.jetbrains.kotlin.nj2k.tree.JKOtherModifierElement import org.jetbrains.kotlin.nj2k.tree.JKTreeElement import org.jetbrains.kotlin.nj2k.tree.OtherModifier class InnerClassConversion(context : NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) return recurseArmed(element, element) } private fun recurseArmed(element: JKTreeElement, outer: JKClass): JKTreeElement { return applyRecursive(element, outer, ::applyArmed) } private fun applyArmed(element: JKTreeElement, outer: JKClass): JKTreeElement { if (element !is JKClass) return recurseArmed(element, outer) if (element.classKind == JKClass.ClassKind.COMPANION) return recurseArmed(element, outer) if (element.isLocalClass()) return recurseArmed(element, outer) val static = element.otherModifierElements.find { it.otherModifier == OtherModifier.STATIC } if (static != null) { element.otherModifierElements -= static } else if (element.classKind != JKClass.ClassKind.INTERFACE && outer.classKind != JKClass.ClassKind.INTERFACE && element.classKind != JKClass.ClassKind.ENUM ) { element.otherModifierElements += JKOtherModifierElement(OtherModifier.INNER) } return recurseArmed(element, element) } }
apache-2.0
0830292d77a15bc219d44e975e070748
47.052632
158
0.738082
4.39759
false
false
false
false
JetBrains/intellij-community
spellchecker/src/com/intellij/spellchecker/settings/SettingsTransferActivity.kt
1
979
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.spellchecker.settings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectPostStartupActivity import com.intellij.spellchecker.SpellCheckerManager.DictionaryLevel import com.intellij.spellchecker.state.ProjectDictionaryState internal class SettingsTransferActivity : ProjectPostStartupActivity { override suspend fun execute(project: Project) { val settings = SpellCheckerSettings.getInstance(project) if (settings.isSettingsTransferred) { return } if (settings.isUseSingleDictionaryToSave && DictionaryLevel.PROJECT.getName() == settings.dictionaryToSave && project.getService(ProjectDictionaryState::class.java).projectDictionary.words.isEmpty()) { settings.dictionaryToSave = DictionaryLevel.APP.getName() } settings.isSettingsTransferred = true } }
apache-2.0
4de1f387061e5e4a22f52a92899aeab4
45.666667
120
0.798774
4.729469
false
false
false
false