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
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/ml/SSDOcr.kt
1
7472
package com.stripe.android.stripecardscan.payment.ml import android.content.Context import android.graphics.Bitmap import android.graphics.Rect import android.util.Size import androidx.annotation.VisibleForTesting import com.stripe.android.camera.framework.image.cropCameraPreviewToViewFinder import com.stripe.android.camera.framework.image.hasOpenGl31 import com.stripe.android.camera.framework.image.scale import com.stripe.android.stripecardscan.framework.FetchedData import com.stripe.android.stripecardscan.framework.image.MLImage import com.stripe.android.stripecardscan.framework.image.toMLImage import com.stripe.android.stripecardscan.framework.ml.TFLAnalyzerFactory import com.stripe.android.stripecardscan.framework.ml.TensorFlowLiteAnalyzer import com.stripe.android.stripecardscan.framework.ml.ssd.adjustLocations import com.stripe.android.stripecardscan.framework.ml.ssd.softMax import com.stripe.android.stripecardscan.framework.ml.ssd.toRectForm import com.stripe.android.stripecardscan.framework.util.reshape import com.stripe.android.stripecardscan.payment.card.isValidPan import com.stripe.android.stripecardscan.payment.ml.ssd.OcrFeatureMapSizes import com.stripe.android.stripecardscan.payment.ml.ssd.combinePriors import com.stripe.android.stripecardscan.payment.ml.ssd.determineLayoutAndFilter import com.stripe.android.stripecardscan.payment.ml.ssd.extractPredictions import com.stripe.android.stripecardscan.payment.ml.ssd.rearrangeOCRArray import org.tensorflow.lite.Interpreter import java.nio.ByteBuffer /** Training images are normalized with mean 127.5 and std 128.5. */ private const val IMAGE_MEAN = 127.5f private const val IMAGE_STD = 128.5f /** * We use the output from last two layers with feature maps 19x19 and 10x10 * and for each feature map activation we have 6 priors, so total priors are * 19x19x6 + 10x10x6 = 2766 */ private const val NUM_OF_PRIORS = 3420 /** * For each activation in our feature map, we have predictions for 6 bounding boxes * of different aspect ratios */ private const val NUM_OF_PRIORS_PER_ACTIVATION = 3 /** * We can detect a total of 10 numbers (0 - 9) plus the background class */ private const val NUM_OF_CLASSES = 11 /** * Each prior or bounding box can be represented by 4 coordinates * XMin, YMin, XMax, YMax. */ private const val NUM_OF_COORDINATES = 4 /** * Represents the total number of data points for locations */ private const val NUM_LOC = NUM_OF_COORDINATES * NUM_OF_PRIORS /** * Represents the total number of data points for classes */ private const val NUM_CLASS = NUM_OF_CLASSES * NUM_OF_PRIORS private const val PROB_THRESHOLD = 0.50f private const val IOU_THRESHOLD = 0.50f private const val CENTER_VARIANCE = 0.1f private const val SIZE_VARIANCE = 0.2f private const val LIMIT = 20 @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal const val VERTICAL_THRESHOLD = 2.0f private val FEATURE_MAP_SIZES = OcrFeatureMapSizes( layerOneWidth = 38, layerOneHeight = 24, layerTwoWidth = 19, layerTwoHeight = 12 ) /** * This value should never change, and is thread safe. */ private val PRIORS = combinePriors(SSDOcr.Factory.TRAINED_IMAGE_SIZE) /** * This model performs SSD OCR recognition on a card. */ internal class SSDOcr private constructor(interpreter: Interpreter) : TensorFlowLiteAnalyzer< SSDOcr.Input, Array<ByteBuffer>, SSDOcr.Prediction, Map<Int, Array<FloatArray>> >(interpreter) { data class Input(val ssdOcrImage: MLImage) data class Prediction(val pan: String?) { /** * Force a generic toString method to prevent leaking information about this class' * parameters after R8. Without this method, this `data class` will automatically generate a * toString which retains the original names of the parameters even after obfuscation. */ override fun toString(): String { return "Prediction" } } companion object { /** * Convert a camera preview image into a SSDOcr input */ fun cameraPreviewToInput( cameraPreviewImage: Bitmap, previewBounds: Rect, cardFinder: Rect ) = Input( cropCameraPreviewToViewFinder(cameraPreviewImage, previewBounds, cardFinder) .scale(Factory.TRAINED_IMAGE_SIZE) .toMLImage(mean = IMAGE_MEAN, std = IMAGE_STD) ) } override suspend fun transformData(data: Input): Array<ByteBuffer> = arrayOf(data.ssdOcrImage.getData()) override suspend fun interpretMLOutput( data: Input, mlOutput: Map<Int, Array<FloatArray>> ): Prediction { val outputClasses = mlOutput[0] ?: arrayOf(FloatArray(NUM_CLASS)) val outputLocations = mlOutput[1] ?: arrayOf(FloatArray(NUM_LOC)) val boxes = rearrangeOCRArray( locations = outputLocations, featureMapSizes = FEATURE_MAP_SIZES, numberOfPriors = NUM_OF_PRIORS_PER_ACTIVATION, locationsPerPrior = NUM_OF_COORDINATES ).reshape(NUM_OF_COORDINATES) boxes.adjustLocations( priors = PRIORS, centerVariance = CENTER_VARIANCE, sizeVariance = SIZE_VARIANCE ) boxes.forEach { it.toRectForm() } val scores = rearrangeOCRArray( locations = outputClasses, featureMapSizes = FEATURE_MAP_SIZES, numberOfPriors = NUM_OF_PRIORS_PER_ACTIVATION, locationsPerPrior = NUM_OF_CLASSES ).reshape(NUM_OF_CLASSES) scores.forEach { it.softMax() } val detectedBoxes = determineLayoutAndFilter( extractPredictions( scores = scores, boxes = boxes, probabilityThreshold = PROB_THRESHOLD, intersectionOverUnionThreshold = IOU_THRESHOLD, limit = LIMIT, classifierToLabel = { if (it == 10) 0 else it } ), VERTICAL_THRESHOLD ) val predictedNumber = detectedBoxes.map { it.label }.joinToString("") return if (isValidPan(predictedNumber)) { Prediction(predictedNumber) } else { Prediction(null) } } override suspend fun executeInference( tfInterpreter: Interpreter, data: Array<ByteBuffer> ): Map<Int, Array<FloatArray>> { val mlOutput = mapOf( 0 to arrayOf(FloatArray(NUM_CLASS)), 1 to arrayOf(FloatArray(NUM_LOC)) ) tfInterpreter.runForMultipleInputsOutputs(data, mlOutput) return mlOutput } /** * A factory for creating instances of this analyzer. */ class Factory( context: Context, fetchedModel: FetchedData, threads: Int = DEFAULT_THREADS ) : TFLAnalyzerFactory<Input, Prediction, SSDOcr>(context, fetchedModel) { companion object { private const val USE_GPU = false private const val DEFAULT_THREADS = 4 val TRAINED_IMAGE_SIZE = Size(600, 375) } override val tfOptions: Interpreter.Options = Interpreter .Options() .setUseNNAPI(USE_GPU && hasOpenGl31(context.applicationContext)) .setNumThreads(threads) override suspend fun newInstance(): SSDOcr? = createInterpreter()?.let { SSDOcr(it) } } }
mit
573b4d6f526004cf5ea471f81474b872
33.753488
100
0.684288
4.197753
false
false
false
false
06needhamt/LINQ-For-Java
src/linq/collections/LinqListFunctionsJava7.kt
1
48189
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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 linq.collections import linq.lamdba.Java7Lambda import java.util.* /** * Created by Tom Needham on 23/02/2016. */ class LinqListFunctionsJava7 { companion object LINQJava7 { //TODO Implement Aggregate /** * Determines whether all elements of a sequence satisfy a [condition]. * @param list The collection to search * @param condition a [Java7Lambda] that returns true or false to indicate whether all elements meet the [condition] * @return whether all elements meet the condition */ @JvmStatic() fun<ElementType> All(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : Boolean { for (item: ElementType? in list) { val cond: Boolean? = condition.Call() if (cond == null || !cond) { return false } } return true } /** * Determines whether all elements of a sequence satisfy a [condition]. * @param list The collection to search * @param condition a [Java7Lambda] that returns true or false to indicate whether the collection contains any elements * that meet the specified [condition] * @return whether the collection contains any elements that meet the specified [condition] **/ @JvmStatic() fun<ElementType> HasAny(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : Boolean{ if (list.size == 0) { return false } for (item: ElementType? in list) { val cond: Boolean? = condition.Call() ?: return false if (cond!!) { return true } } return false } /** * Determines whether all elements of a sequence satisfy a condition. * @param list The collection to search * @return whether the collection contains any elements **/ @JvmStatic() fun<ElementType> HasAny(list: AbstractList<ElementType?>): Boolean { return list.size > 0 } /** * Retuns the inputted list as an [AbstractList<Any>] * @param list The collection to convert * @return the inputted list as an [AbstractList<Any>] */ @JvmStatic() fun<ElementType> AsAbstractList(list: AbstractList<ElementType?>): AbstractList<ElementType?> { return list } /** * Returns the average of a list of numbers * @param list the list to average * @return the average value of the numbers */ @JvmStatic() fun<ElementType : Number> Average(list: AbstractList<ElementType?>): ElementType? { var dtotal: Double = 0.0 var ftotal: Float = 0.0f var itotal: Int = 0 var ltotal: Long = 0L var stotal: Short = 0 if (list.size == 0) { println("Cannot take average of 0 elements") return null } for (item: Any? in list) { if (item is Double) { dtotal += item dtotal /= list.size } else if (item is Float) { ftotal += item ftotal /= list.size } else if (item is Int) { itotal += item itotal /= list.size } else if (item is Long) { ltotal += item ltotal /= list.size } else if (item is Short) { stotal = (stotal + item).toShort() stotal = (stotal / list.size).toShort() } else println("ERROR: Cannot Take average of type " + item!!.javaClass.toString()) } if (list[0] is Double) return dtotal as ElementType? else if (list[0] is Float) return ftotal as ElementType? else if (list[0] is Int) return itotal as ElementType? else if (list[0] is Long) return ltotal as ElementType? else if (list[0] is Short) return stotal as ElementType? else return null } /** * Casts all items in the list to the specified type * @param list the collection to cast * @return a collection containing the casted values */ @JvmStatic() fun<ElementType> Cast(list: AbstractList<Any?>): AbstractList<ElementType?> { var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: Any? in list) { if (item as ElementType? != null) { ret.add(item) } } return ret } /** * Concatenates two collections * @param list the first list * @param list2 the second list * @return the Concatenated collection */ @JvmStatic() fun<ElementType> Concat(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>): AbstractList<ElementType?> { var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() ret.addAll(list) ret.addAll(list2) return ret } /** * Determines whether a sequence contains a specified [element] by using the default equality function * @param list the collection to search * @param element the element to check for * @return whether the collection contains the item */ @JvmStatic() fun<ElementType> Contains(list: AbstractList<ElementType?>, element: ElementType?): Boolean { for (item: ElementType? in list) { if (element?.equals(item)!!) { return true } } return false } /** * Determines whether a sequence contains a specified element by using the passed equality function [comparator] * @param list the collection to search * @param element the element to check for * @param comparator A [Java7Lambda] to use to compare the items * @throws RuntimeException if an invalid [Java7Lambda] is passed * @return whether the collection contains the item */ @JvmStatic() fun<ElementType> Contains(list: AbstractList<ElementType?>,element: ElementType?, comparator: Java7Lambda<Boolean>) : Boolean { if(comparator.parameters.size != 2) throw RuntimeException("Expected Lambda to have 2 parameters found: " + comparator.parameters.size + "Parameters"); for(item: ElementType? in list){ val cond: Boolean? = comparator.Call() ?: return false if(cond!!){ return true } } return false } /** * Returns the amount of items in the [list] * @param list the list to count * @return the number of items in the [list] */ @JvmStatic() fun<ElementType> Count(list: AbstractList<ElementType?>): Int { return list.size } /** * Returns the amount of items in the list that meet the [condition] * @param list the list to count * @param condition the [Java7Lambda] to be used as a condition * @return the number of items in the list that meet the [condition] */ @JvmStatic() fun<ElementType> Count(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : Int{ var count : Int = 0 for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return 0 if(cond!!){ count++ } } return count } /** * Returns the collection or the default value if it is empty * @param list the list to return * @return the list or the types default value if it is empty */ @JvmStatic() fun<ElementType> DefaultIfEmpty(list: AbstractList<ElementType?>): AbstractList<ElementType?> { if (list.isEmpty()) { return ArrayList<ElementType?>() } return list } /** * Returns the collection or [element] if it is empty * @param list the list to return * @param element the value to return if the list is empty * @return the List or [element] if it is empty */ @JvmStatic() fun<ElementType> DefaultIfEmpty(list: AbstractList<ElementType?>, element: ElementType?): AbstractList<ElementType?> { if (list.isEmpty()) { var def: ArrayList<ElementType?> = ArrayList<ElementType?>() def.add(element) return def } return list } /** * Returns a list containing all distinct elements * @param list the collection to search * @return a [AbstractList] containing the distinct items */ @JvmStatic() fun<ElementType> Distinct(list: AbstractList<ElementType?>): AbstractList<ElementType?> { var ret: AbstractList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { if (Contains(ret, item)) { ret.add(item) } } return ret } /** * Returns a list containing all distinct elements that meet the specified [comparator] * @param list the collection to search * @param comparator the [Java7Lambda] to use to compare the items * @return a [AbstractList] containing the distinct items */ @JvmStatic() fun<ElementType> Distinct(list: AbstractList<ElementType?>, comparator: Java7Lambda<Boolean>) : AbstractList<ElementType?>{ var ret : AbstractList<ElementType?> = ArrayList<ElementType?>() for(item: ElementType? in list){ val cond : Boolean? = comparator.Call() ?: return ArrayList<ElementType?>() if(!Contains(ret,item) && !cond!!){ ret.add(item) } } return ret } /** * Returns the element at the specified [index] in [list] * @param list the collection * @param index the index of the item to return * @return the item at the specified [index] in [list] */ @JvmStatic() fun<ElementType> ElementAt(list: AbstractList<ElementType?>, index: Int): ElementType? { if (list.size - 1 < index) return null else return list[index] } /** * Returns the element at the specified [index] in [list] or null if the index is out of range * @param list the collection * @param index the index of the item to return * @return the item at the specified [index] in [list] */ @JvmStatic() fun<ElementType> ElementAtOrDefault(list: AbstractList<ElementType?>, index: Int): ElementType? { return list[index] } /** * Returns an empty list of the specified type * @return an empty list of the specified type */ @JvmStatic() fun<ElementType> Empty(): AbstractList<ElementType?> { return ArrayList() } /** * Returns a collection containing items that are not contained in both [list] and [list2] * @param list the first collection * @param list2 the second collection * @return An [AbstractList] containing items that are not contained in both [list] and [list2] */ @JvmStatic() fun<ElementType> Except(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>): AbstractList<ElementType?> { var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { if (!Contains(list2, item)) { ret.add(item) } } return ret } /** * Returns a collection containing items that are not contained in both [list] and [list2] * @param list the first collection * @param list2 the second collection * @param condition the [Java7Lambda] to compare the items with * @return An [AbstractList] containing items that are not contained in both [list] and [list2] */ @JvmStatic() fun<ElementType> Except(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : AbstractList<ElementType?>{ var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return ArrayList<ElementType?>() if(!Contains(list2,item) && cond!!){ ret.add(item) } } return ret } /** * Returns the first Element in [list] * @param list The collection to search * @return The First element in [list] */ @JvmStatic() fun<ElementType> First(list: AbstractList<ElementType?>): ElementType? { if (list.size > 0) return ElementAt(list, 0) else throw IllegalArgumentException("List must contain at least one element") } /** * Returns the first Element in the collection that meets the specified [condition] * @param list The collection to search * @param condition a [Java7Lambda] that returns true or false to indicate whether the [condition] is met * @return The First element that matches the [condition] */ @JvmStatic() fun<ElementType> First(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : ElementType?{ for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return null if(cond!!){ return item } } throw IllegalArgumentException("List must contain at least one element") } /** * Returns the first Element in the collection * @param list The collection to search * @return The First element in the collection */ @JvmStatic() fun<ElementType> FirstOrDefault(list: AbstractList<ElementType?>) : ElementType? { if (list.size > 0) return ElementAt(list, 0) else return null } /** Returns the first Element in the collection that meets the specified condition * @param list The collection to search * @param condition a [Java7Lambda] that returns true or false to indicate whether the condition is met * @return The First element that matches the condition or null */ @JvmStatic() fun<ElementType> FirstOrDefault(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : ElementType?{ for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return null if(cond!!){ return item } } return null } //TODO Add GroupBy /** * Returns a list containing all of the distinct items in [list] that also appear in [list2] * @param list the first collection * @param list2 the second collection * @return list containing all of the distinct items in [list] that also appear in [list2] */ @JvmStatic() fun<ElementType> Intersect(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>): AbstractList<ElementType?> { var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in Distinct(list)) { if (Contains(Distinct(list2), item)) { ret.add(item) } } return ret } /** * Returns a list containing all of the distinct items in [list] that also appear in [list2] * @param list the first collection * @param list2 the second collection * @param condition the [Java7Lambda] to compare the elements against * @return list containing all of the distinct items in [list] that also appear in [list2] */ @JvmStatic() fun<ElementType> Intersect(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : AbstractList<ElementType?> { var ret: ArrayList<ElementType?> = ArrayList<ElementType?>() for(item: ElementType? in Distinct(list,condition)){ val cond : Boolean? = condition.Call() ?: return ArrayList<ElementType?>() if(Contains(Distinct(list2,condition),item)){ ret.add(item) } } return ret } //TODO Implement Join /** * Returns the last item contained in [list] * @param list The Collection * @return the last item contained in [list] */ @JvmStatic() fun<ElementType> Last(list: AbstractList<ElementType?>): ElementType? { return list[list.count() - 1] } /** * Returns the last item contained in [list] that meets the [condition] * @param list The Collection * @param condition the [Java7Lambda] to check the items against * @return the last item contained in [list] that meets the [condition] */ @JvmStatic() fun<ElementType> Last(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>) : ElementType?{ var lastMatch: ElementType? = null for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return null if(item != null && cond!!){ lastMatch = item } } return lastMatch } /** * Returns the Largest item in the list * @param list the list to search * @return the Largest item in the list */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>): ElementType? { var dmax: Double = Double.MIN_VALUE var fmax: Float = Float.MIN_VALUE var imax: Int = Int.MIN_VALUE var lmax: Long = Long.MIN_VALUE var smax: Short = Short.MIN_VALUE if (list.size == 0) { println("Cannot take maximum of 0 elements") return null } for (item: ElementType? in list) { if (item is Double) { if (item > dmax) dmax = item.toDouble() } else if (item is Float) { if (item > fmax) fmax = item.toFloat() } else if (item is Int) { if (item > imax) imax = item.toInt() } else if (item is Long) { if (item > lmax) lmax = item.toLong() } else if (item is Short) { if (item > smax) smax = item.toShort() } else println("ERROR: Cannot Take maximum of type " + item!!.javaClass.toString()) } if (list[0] is Double) return dmax as ElementType? else if (list[0] is Float) return fmax as ElementType? else if (list[0] is Int) return imax as ElementType? else if (list[0] is Long) return lmax as ElementType? else if (list[0] is Short) return smax as ElementType? else return null } /** * Returns the maximum double value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the maximum double value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>, comparator: Java7Lambda<Double>): Double { var max: Double = 0.0 for (item: ElementType? in list) { val cond : Double? = comparator.Call() ?: return 0.0 if (item is Double) { if (cond!! > max ) max = item.toDouble() } } return max } /** * Returns the maximum Float value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the maximum Float value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>, comparator: Java7Lambda<Float>): Float { var max: Float = 0.0f for (item: ElementType? in list) { val cond : Float? = comparator.Call() ?: return 0.0f if (item is Float) { if (cond!! > max ) max = item.toFloat() } } return max } /** * Returns the maximum Int value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the maximum Int value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>, comparator: Java7Lambda<Int>): Int { var max: Int = 0 for (item: ElementType? in list) { val cond : Int? = comparator.Call() ?: return 0 if (item is Int) { if (cond!! > max ) max = item.toInt() } } return max } /** * Returns the maximum Long value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the maximum Long value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>, comparator: Java7Lambda<Long>): Long { var max: Long = 0L for (item: ElementType? in list) { val cond : Long? = comparator.Call() ?: return 0L if (item is Long) { if (cond!! > max ) max = item.toLong() } } return max } /** * Returns the maximum Short value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the maximum Short value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Max(list: AbstractList<ElementType?>, comparator: Java7Lambda<Short>): Short { var max: Short = 0 for (item: ElementType? in list) { val cond : Short? = comparator.Call() ?: return 0 if (item is Short) { if (cond!! > max ) max = item.toShort() } } return max } /** * Returns the Smallest item in the list * @param list the list to search * @return the Smallest item in the list */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>): ElementType? { var dmin: Double = Double.MAX_VALUE var fmin: Float = Float.MAX_VALUE var imin: Int = Int.MAX_VALUE var lmin: Long = Long.MAX_VALUE var smin: Short = Short.MAX_VALUE if (list.size == 0) { println("Cannot take minimum of 0 elements") return null } for (item: ElementType? in list) { if (item is Double) { if (item < dmin) dmin = item.toDouble() } else if (item is Float) { if (item < fmin) fmin = item.toFloat() } else if (item is Int) { if (item < imin) imin = item.toInt() } else if (item is Long) { if (item < lmin) lmin = item.toLong() } else if (item is Short) { if (item < smin) smin.toShort() } else println("ERROR: Cannot Take minimum of type " + item!!.javaClass.toString()) } if (list[0] is Double) return dmin as ElementType? else if (list[0] is Float) return fmin as ElementType? else if (list[0] is Int) return imin as ElementType? else if (list[0] is Long) return lmin as ElementType? else if (list[0] is Short) return smin as ElementType? else return null } /** * Returns the minimum double value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the minimum double value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>, comparator: Java7Lambda<Double>): Double { var min: Double = 0.0 for (item: ElementType? in list) { val cond : Double? = comparator.Call() ?: return 0.0 if (item is Double) { if (cond!! < min ) min = item.toDouble() } } return min } /** * Returns the minimum Float value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the minimum Float value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>, comparator: Java7Lambda<Float>): Float { var min: Float = 0.0f for (item: ElementType? in list) { val cond : Float? = comparator.Call() ?: return 0.0f if (item is Float) { if (cond!! < min ) min = item.toFloat() } } return min } /** * Returns the minimum Int value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the minimum Int value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>, comparator: Java7Lambda<Int>): Int { var min: Int = 0 for (item: ElementType? in list) { val cond : Int? = comparator.Call() ?: return 0 if (item is Int) { if (cond!! < min ) min = item.toInt() } } return min } /** * Returns the minimum Long value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the minimum Long value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>, comparator: Java7Lambda<Long>): Long { var min: Long = 0L for (item: ElementType? in list) { val cond : Long? = comparator.Call() ?: return 0L if (item is Long) { if (cond!! < min ) min = item.toLong() } } return min } /** * Returns the minimum Short value in the list based on [comparator] * @param list the list to search * @param comparator the [Java7Lambda] function to use * @return the minimum Short value in the list based on [comparator] */ @JvmStatic() fun<ElementType : Number> Min(list: AbstractList<ElementType?>, comparator: Java7Lambda<Short>): Short { var min: Short = 0 for (item: ElementType? in list) { val cond : Short? = comparator.Call() ?: return 0 if (item is Short) { if (cond!! < min ) min = item.toShort() } } return min } ///** // * Returns all the elements of a specified type from the list [list] // * @param list the list to search // * @return an [AbstractList] containing all the elements of the specified type // */ // @JvmStatic() //inline fun<reified ElementType> OfType(list: AbstractList<Any?>) : AbstractList<ElementType?>{ // var result : AbstractList<ElementType?> = ArrayList<ElementType?>() // for(item: Any? in list){ // if(item is ElementType?){ // result.add(item) // } // } // return result //} ///** /** * Returns all the elements of a specified type from the list [list] * @param list the list to search * @return an [ArrayList] containing all the elements of the specified type */ @JvmStatic() fun<ElementType> OfType(list: AbstractList<Any?>): ArrayList<Any?> { var result: ArrayList<Any?> = ArrayList<Any?>() for (i in list.indices) { val item: ElementType? = list.get(i) as ElementType? if (item != null) result.add(item) } return result } //TODO Implement Order By //@JvmStatic() //fun<ElementType,KeyType> OrderBy(list: AbstractList<ElementType?>, key: String) : AbstractList<ElementType?>{ // val persistentClass : Class<ElementType> = (ElementType::class.java as ParameterizedType).javaClass.genericSuperclass.typeName as Class<ElementType> /** * Generates a sequence of [amount] integers starting with value [start] * @param start the number at the start of the sequence * @param amount the amount of numbers that should be in the sequence * @return An [ArrayList] containing the sequence of integers */ @JvmStatic() fun Range(start: Int, amount: Int): ArrayList<Int> { var sequence: ArrayList<Int> = ArrayList<Int>(amount) for (i in IntRange(start, start + amount)) { sequence.add(i) } return sequence } /** * Returns a list containing the [element] repeated [times] times * @param element the value to repeat * @param times the amount of times to repeat the [element] * @return An [ArrayList] containing the [element] repeated [times] times */ @JvmStatic() fun<ElementType> Repeat(element: ElementType?, times: Int): ArrayList<ElementType?> { var result: ArrayList<ElementType?> = ArrayList<ElementType?>(times) for (i in IntRange(0, times)) { result.add(element) } return result } /** * Reverses the order of the items in list[list] * @param list the list to reverse * @return the reversed list */ @JvmStatic() fun<ElementType> Reverse(list: AbstractList<ElementType?>): AbstractList<ElementType?> { list.reverse() return list } //TODO implement Select /** * Returns the only element of [list], and throws Exception if there is not exactly one element in the [list]. * @throws Exception if there is not exactly one element in the [list] * @param list the list to return the only element of * @return the only element of the [list] */ @JvmStatic() fun<ElementType> Single(list: AbstractList<ElementType?>): ElementType? { if (list.size == 1) return First(list) else throw Exception("There was more than one element in the list") } /** * Returns the only element of [list] or null if there were no items in the list that met the condition * and throws Exception if there is not exactly one element in the [list]. * @throws Exception if there is not exactly one element in the [list] * @param list the list to return the only element of or null * @return the only element of the [list] or null */ @JvmStatic() fun<ElementType> Single(list: AbstractList<ElementType?>, condition: (ElementType?) -> Boolean): ElementType? { var matches: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { if (condition.invoke(item)) { matches.add(item) } } if (matches.size > 1) throw Exception("There was more than one element in the list") else return First(list) } /** * Returns the only element of [list] or null if there were no items in the list * and throws Exception if there is not exactly one element in the [list]. * @throws Exception if there is not exactly one element in the [list] * @param list the list to return the only element of or null * @return the only element of the [list] or null */ @JvmStatic() fun<ElementType> SingleOrDefault(list: AbstractList<ElementType?>): ElementType? { if (list.isEmpty()) return null else if (list.size == 1) return First(list) else throw Exception("There was more than one element in the list") } /** * Returns the only element of [list] or null if there were no items in the list that met the condition * and throws Exception if there is not exactly one element in the [list]. * @throws Exception if there is not exactly one element in the [list] * @param list the list to return the only element of or null * @return the only element of the [list] or null */ @JvmStatic() fun<ElementType> SingleOrDefault(list: AbstractList<ElementType?>, condition: (ElementType?) -> Boolean): ElementType? { var matches: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { if (condition.invoke(item)) { matches.add(item) } } if (matches.isEmpty()) return null else if (matches.size > 1) throw Exception("There was more than one element in the list") else return First(list) } /** * Returns the contents of [list] after skipping [amount] items * @param list The list of items * @param amount the amount of items to skip * @return the contents of [list] after skipping [amount] items */ @JvmStatic() fun<ElementType> Skip(list: AbstractList<ElementType?>, amount: Int): ArrayList<ElementType?> { var result: ArrayList<ElementType?> = ArrayList<ElementType?>() if (list.size < amount) return result for (i in IntRange(amount, list.size - 1)) { result.add(list[i]) } return result } /** * Returns the contents of [list] after skipping items while the [condition] is true * @param list The list of items * @param condition the [Java7Lambda] to skip items while true * @return the contents of [list] after skipping items while [condition] is true */ @JvmStatic() fun<ElementType> SkipWhile(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>): ArrayList<ElementType?>{ var result: ArrayList<ElementType?> = ArrayList<ElementType?>() if(condition.parameters.size == 1 || condition.parameters.size == 2) { for (i in IntRange(0, list.size - 1)) { val cond: Boolean? = condition.Call() ?: return ArrayList<ElementType?>() if (cond!!) { continue } else { result.add(list.get(i)) } } } else{ throw RuntimeException("Expected a Lambda with 1 or 2 parameters found: " + condition.parameters.size + " Parameters") } return result } /** * Returns the sum of all items within the [list] * @param list the list to sum * @return the sum of all the items within the [list] */ @JvmStatic() fun<ElementType : Number> Sum(list: AbstractList<ElementType?>): ElementType? { var dtotal: Double = 0.0 var ftotal: Float = 0.0f var itotal: Int = 0 var ltotal: Long = 0L var stotal: Short = 0 for (item: ElementType? in list) { if (item is Double) { dtotal += item } else if (item is Float) { ftotal += item } else if (item is Int) { itotal += item } else if (item is Long) { ltotal += item } else if (item is Short) { stotal = (stotal + item).toShort() } else println("ERROR: Cannot Take sum of type " + item!!.javaClass.toString()) } if (list[0] is Double) return dtotal as ElementType? else if (list[0] is Float) return ftotal as ElementType? else if (list[0] is Int) return itotal as ElementType? else if (list[0] is Long) return ltotal as ElementType? else if (list[0] is Short) return stotal as ElementType? else return null } /** * Returns the sum of all items within the [list] after applying transform function [comparator] * @param list the list to sum * @param comparator a [Java7Lambda] to apply to each element * @return the sum of all the items within the [list] after applying transform function [comparator] */ @JvmStatic() fun<ElementType> Sum(list: AbstractList<ElementType?>, condition: Java7Lambda<ElementType?>): ElementType? { var dtotal: Double = 0.0 var ftotal: Float = 0.0f var itotal: Int = 0 var ltotal: Long = 0L var stotal: Short = 0 for (item: ElementType? in list) { val cond : Number? = condition.Call() as Number? ?: return null val value: ElementType? = cond!! as ElementType? if (value is Double) { dtotal += value } else if (value is Float) { ftotal += value } else if (value is Int) { itotal += value } else if (value is Long) { ltotal += value } else if (value is Short) { stotal = (stotal + value).toShort() } else println("ERROR: Cannot Take sum of type " + (value!! as Any).javaClass.toString()) } if (list[0] is Double) return dtotal as ElementType? else if (list[0] is Float) return ftotal as ElementType? else if (list[0] is Int) return itotal as ElementType? else if (list[0] is Long) return ltotal as ElementType? else if (list[0] is Short) return stotal as ElementType? else return null } /** * Returns [amount] items from the [list] * @param list the list to return items from * @param [amount] the amount of items to return * @throws Exception when there are less than [amount] items in the [list] * @return the first [amount] items in the [list] */ @JvmStatic() fun<ElementType> Take(list: AbstractList<ElementType?>, amount: Int): ArrayList<ElementType?> { if (list.size < amount) throw Exception("Can not take " + amount + " Elements form a list with " + list.size + " Elements") var result: ArrayList<ElementType?> = ArrayList<ElementType?>(amount) for (i in IntRange(0, amount)) { result.add(list.get(i)) } return result } /** * Returns items from the [list] while the [condition] is true * @param list the list to return items from * @param condition the [Java7Lambda] on which to return items * @return the items which meet [condition] */ @JvmStatic() fun<ElementType> TakeWhile(list: AbstractList<ElementType?>, condition: Java7Lambda<Boolean>): ArrayList<ElementType?>{ var result: ArrayList<ElementType?> = ArrayList<ElementType?>() for(item: ElementType? in list){ val cond : Boolean? = condition.Call() ?: return ArrayList<ElementType?>() if (cond!!) { result.add(item) } else break } return result } //TODO Implement ThenBy /** * Converts a list of items to an array of items * @param list the list of items * @return an array containing all the items contained in the list */ @JvmStatic() fun<ElementType> ToArray(list: AbstractList<ElementType?>): Array<ElementType?> { var result: Array<Any?> = list.toTypedArray() return result as Array<ElementType?> } //TODO implement ToDictionary //TODO implement ToLookup /** * Performs a Union between [list] and [list2] using the default equality function * @param list the first list * @param list2 the second list * @return the result of the union */ @JvmStatic() fun<ElementType> Union(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>): ArrayList<ElementType?> { var result: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { for (item2: ElementType? in list2) { if (item != null && item2 != null) result.add(item2) } } return result } @JvmStatic() fun<ElementType> Union(list: AbstractList<ElementType?>, list2: AbstractList<ElementType?>, comparator: Java7Lambda<Boolean>): ArrayList<ElementType?> { var result: ArrayList<ElementType?> = ArrayList<ElementType?>() for (item: ElementType? in list) { val cond : Boolean? = comparator.Call() ?: return ArrayList<ElementType?>(); for (item2: ElementType? in list2) { if (cond!!) result.add(item2) } } return result } /** * Filters a [list] of values based on a [condition] and the elements index if it was passed to the [condition]. * @param list the list to filter * @param condition the condition to filter the elements with * @throws RuntimeException if an invalid [Java7Lambda] is passed * @return the filtered list */ @JvmStatic() fun<ElementType> Where(list: AbstractList<ElementType?>,condition: Java7Lambda<Boolean>): ArrayList<ElementType?>{ if(condition.parameters.size == 1 || condition.parameters.size == 2){ var result: ArrayList<ElementType?> = ArrayList<ElementType?>() for (i in IntRange(0,list.size)){ val cond : Boolean? = condition.Call() ?: return ArrayList<ElementType?>() if(cond!!){ result.add(list.get(i)) } } return result } else{ throw RuntimeException("Expected Lambda to have 2 parameters found: " + condition.parameters.size + "Parameters"); } } @JvmStatic() fun<TypeFirst, TypeSecond, TypeResult> Zip(list: AbstractList<TypeFirst?>, list2: AbstractList<TypeSecond?>): ArrayList<TypeResult?> { var result: ArrayList<TypeResult?> = ArrayList<TypeResult?>() throw Exception("Not Implemented Yet") } } }
mit
f2fcc05273f47e85813e2018a08bf366
39.631535
162
0.530723
4.997304
false
false
false
false
exponent/exponent
packages/expo-battery/android/src/test/java/expo/modules/battery/BatteryModuleTest.kt
2
3795
package expo.modules.battery import android.content.Context import android.content.IntentFilter import android.os.Build import android.os.Bundle import io.mockk.mockk import io.mockk.verify import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.unimodules.test.core.PromiseMock import org.unimodules.test.core.assertResolved import org.unimodules.test.core.moduleRegistryMock import org.robolectric.annotation.Config import org.unimodules.test.core.mockInternalModule @RunWith(RobolectricTestRunner::class) class BatteryModuleTest { private lateinit var module: BatteryModule private var moduleRegistry = moduleRegistryMock() private val context = mockContext() private val eventEmitter = mockEventEmitter() @Before fun initializeMock() { module = BatteryModule(context) moduleRegistry.mockInternalModule(eventEmitter) module.onCreate(moduleRegistry) } @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) @Test fun batteryLevelReceiver() { val receiver = BatteryLevelReceiver(eventEmitter) receiver.onReceive(context, mockk()) verify(exactly = 1) { context.applicationContext.registerReceiver(null, any() as IntentFilter) } verify(exactly = 1) { eventEmitter.emit(any() as String, any() as Bundle) } } @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) @Test fun batteryStateReceiver() { val receiver = BatteryStateReceiver(eventEmitter) receiver.onReceive(context, MockBatteryIntent()) verify(exactly = 1) { eventEmitter.emit(any() as String, any() as Bundle) } } @Config(sdk = [Build.VERSION_CODES.M]) @Test fun powerSaverReceiver() { mockPowerManager(context) val receiver = PowerSaverReceiver(eventEmitter) receiver.onReceive(context, mockk()) verify(exactly = 1) { context.applicationContext.getSystemService(Context.POWER_SERVICE) } verify(exactly = 1) { eventEmitter.emit(any() as String, any() as Bundle) } } @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) @Test fun getBatteryLevel() { val promise = PromiseMock() val expectedBatteryLevel = 50.0f module.getBatteryLevelAsync(promise) assertEquals(expectedBatteryLevel, promise.resolveValue) verify(exactly = 1) { context.applicationContext.registerReceiver(null, any() as IntentFilter) } } @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) @Test fun getBatteryState() { val promise = PromiseMock() val expectedBatteryState = BatteryModule.BatteryState.FULL.value module.getBatteryStateAsync(promise) assertEquals(expectedBatteryState, promise.resolveValue) verify(exactly = 1) { context.applicationContext.registerReceiver(null, any() as IntentFilter) } } @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) @Test fun isBatteryOptimizationEnabledOlderSdk() { val promise = PromiseMock() module.isBatteryOptimizationEnabledAsync(promise) val expectedResult = false assertEquals(expectedResult, promise.resolveValue) } @Config(sdk = [Build.VERSION_CODES.M]) @Test fun isBatteryOptimizationEnabled() { val promise = PromiseMock() mockPowerManager(context) module.isBatteryOptimizationEnabledAsync(promise) val expectedResult = true assertEquals(expectedResult, promise.resolveValue) } @Config(sdk = [Build.VERSION_CODES.M]) @Test fun isLowPowerModeEnabled() { val promise = PromiseMock() mockPowerManager(context) module.isLowPowerModeEnabledAsync(promise) assertResolved(promise) assertEquals(true, promise.resolveValue) verify(exactly = 1) { context.applicationContext.getSystemService(Context.POWER_SERVICE) } } }
bsd-3-clause
efd7389976180106c3c786423aac338f
29.119048
78
0.740448
4.221357
false
true
false
false
AndroidX/androidx
camera/integration-tests/diagnosetestapp/src/test/java/androidx/camera/integration/diagnose/TestUtils.kt
3
1835
/* * Copyright 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 * * 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.camera.integration.diagnose import android.graphics.Bitmap import com.google.common.truth.Truth.assertThat import java.io.BufferedReader const val JPEG_ENCODE_ERROR_TOLERANCE = 3 /** * Asserting bitmap color and dimension is as expected */ fun assertBitmapColorAndSize(bitmap: Bitmap, color: Int, width: Int, height: Int) { for (x in 0 until bitmap.width) { for (y in 0 until bitmap.height) { val pixelColor = bitmap.getPixel(x, y) // compare the RGB of the pixel to the given color for (shift in 16 until 0 step 8) { val pixelRgb = (pixelColor shr shift) and 0xFF val rgb = (color shr shift) and 0xFF val rgbDifference = kotlin.math.abs(pixelRgb.minus(rgb)) assertThat(rgbDifference).isLessThan(JPEG_ENCODE_ERROR_TOLERANCE) } } } assertThat(bitmap.width).isEqualTo(width) assertThat(bitmap.height).isEqualTo(height) } /** * Reading and returning complete String from buffer */ fun readText(br: BufferedReader): String { var lines = StringBuilder() while (br.ready()) { lines.append(br.readLine()) } return lines.toString() }
apache-2.0
9d3da94468a00eca9c60b8b8843540f4
33
83
0.682834
4.095982
false
false
false
false
yechaoa/YUtils
yutilskt/src/main/java/com/yechaoa/yutilskt/YUtils.kt
1
8027
package com.yechaoa.yutilskt import android.app.Activity import android.app.Application import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.pm.PackageManager import android.telephony.TelephonyManager import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.util.Base64 import android.util.DisplayMetrics import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.TextView import com.yechaoa.yutilskt.widget.YLoadingDialog import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.util.regex.Matcher import java.util.regex.Pattern /** * Created by yechao on 2020/1/7. * Describe : 快速开发工具集合 * <p> * GitHub : https://github.com/yechaoa * CSDN : http://blog.csdn.net/yechaoa */ object YUtils { private lateinit var mApp: Application private var yLoadingDialog: YLoadingDialog? = null @Deprecated("简化调用,使用init(app)即可", ReplaceWith("YUtils.init(app)")) fun initialize(app: Application) { mApp = app app.registerActivityLifecycleCallbacks(ActivityUtil.activityLifecycleCallbacks) } fun init(app: Application) { mApp = app app.registerActivityLifecycleCallbacks(ActivityUtil.activityLifecycleCallbacks) } @Deprecated("简化调用,使用getApp()即可", ReplaceWith("YUtils.getApp()")) fun getApplication(): Application { return mApp } fun getApp(): Application { if (this::mApp.isInitialized) { return mApp } else { throw UninitializedPropertyAccessException("YUtils is not initialized in application") } } fun getAppContext(): Context { return getApp().applicationContext } /** * 获取屏幕宽度 */ @Deprecated("拆分处理,使用DisplayUtil.getScreenWidth()即可", ReplaceWith("DisplayUtil.getScreenWidth()")) fun getScreenWidth(): Int { val dm = DisplayMetrics() ActivityUtil.currentActivity!!.windowManager.defaultDisplay.getMetrics(dm) return dm.widthPixels } /** * 获取屏幕高度 */ @Deprecated("拆分处理,使用DisplayUtil.getScreenHeight()即可", ReplaceWith("DisplayUtil.getScreenHeight()")) fun getScreenHeight(): Int { val dm = DisplayMetrics() ActivityUtil.currentActivity!!.windowManager.defaultDisplay.getMetrics(dm) return dm.heightPixels } /** * Loading加载框 */ fun showLoading(activity: Activity, msg: String, cancelable: Boolean = true, cancelListener: (() -> Unit)? = null) { yLoadingDialog = YLoadingDialog(activity, msg, cancelable, cancelListener = cancelListener) yLoadingDialog?.show() } /** * dismissLoading */ fun hideLoading() { if (null != yLoadingDialog && yLoadingDialog?.isShowing!!) { yLoadingDialog?.dismiss() yLoadingDialog = null } } /** * getLoadingDialog */ fun getLoadingDialog(): YLoadingDialog? { return yLoadingDialog } /** * loading是否显示,需在showLoading()之后调用,否则为null */ fun loadingIsShowing(): Boolean? = yLoadingDialog?.isShowing /** * 根据时间休眠然后关闭当前页面 * 比如:5秒自动返回 * 或者只需要后台给一个结果而已 */ fun finishBySleep(millis: Long) { object : Thread() { override fun run() { try { sleep(millis) ActivityUtil.currentActivity?.finish() } catch (e: InterruptedException) { e.printStackTrace() } } }.start() } /** * 获取版本名 */ fun getVersionName(): String { return try { val packageManager = getApp().packageManager val packageInfo = packageManager.getPackageInfo(getApp().packageName, 0) packageInfo.versionName } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() "" } } /** * 获取版本号 */ fun getVersionCode(): Int { return try { val packageManager = getApp().packageManager val packageInfo = packageManager.getPackageInfo(getApp().packageName, 0) packageInfo.versionCode } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() 0 } } /** * 检验手机号 */ fun checkPhoneNumber(number: String): Boolean { var p: Pattern? = null var m: Matcher? = null var b = false p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$") m = p.matcher(number) b = m.matches() return b } /** * MD5加密 */ fun MD5(data: String): String { var md5: MessageDigest? = null try { md5 = MessageDigest.getInstance("MD5") } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } md5!!.update(data.toByteArray()) val m = md5.digest() return Base64.encodeToString(m, Base64.DEFAULT) } /** * dp2px */ @Deprecated("拆分处理,使用DisplayUtil.dp2px()即可", ReplaceWith("DisplayUtil.dp2px(dp)")) fun dp2px(dp: Float): Int { val density = getApp().resources.displayMetrics.density return (dp * density + 0.5f).toInt() } /** * px2dp */ @Deprecated("拆分处理,使用DisplayUtil.px2dp()即可", ReplaceWith("DisplayUtil.px2dp(px)")) fun px2dp(px: Int): Float { val density = getApp().resources.displayMetrics.density return px / density } /** * 复制文本到粘贴板 */ fun copyToClipboard(text: String?) { val cm = getApp().getSystemService(Activity.CLIPBOARD_SERVICE) as ClipboardManager cm.setPrimaryClip(ClipData.newPlainText(getApp().packageName, text)) } /** * 字体高亮 */ fun foreground(view: View?, color: Int, start: Int, end: Int): View? { if (view is Button) { // 获取文字 val span: Spannable = SpannableString(view.text.toString()) //设置颜色和起始位置 span.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) view.text = span return view } else if (view is TextView) { //EditText extends TextView val span: Spannable = SpannableString(view.text.toString()) span.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) view.text = span return view } return null } /** * 弹出软键盘 */ fun showSoftKeyboard(view: View) { val inputManger = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManger.showSoftInput(view, InputMethodManager.SHOW_FORCED) } /** * 关闭软键盘 */ fun closeSoftKeyboard() { val inputManger = ActivityUtil.currentActivity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManger.hideSoftInputFromWindow(ActivityUtil.currentActivity?.window?.decorView?.windowToken, 0) } /** * 是否有sim卡 即设备是否可以拨打电话等 */ fun hasSim(): Boolean { val telephonyManager = getApp().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager var result = true when (telephonyManager.simState) { TelephonyManager.SIM_STATE_ABSENT -> result = false TelephonyManager.SIM_STATE_UNKNOWN -> result = false } return result } }
apache-2.0
bd2dc29f4b2f210f246467ce41cd22e2
28.030418
124
0.620825
4.426087
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve2/ModCollector.kt
1
25020
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve2 import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS import com.intellij.psi.PsiAnchor import com.intellij.psi.StubBasedPsiElement import com.intellij.psi.stubs.StubElement import com.intellij.psi.stubs.StubTreeLoader import org.rust.lang.RsConstants import org.rust.lang.RsFileType import org.rust.lang.core.crate.Crate import org.rust.lang.core.macros.MacroCallBody import org.rust.lang.core.psi.RsBlock import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.RsFileBase import org.rust.lang.core.psi.RsModItem import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.ENUM_VARIANT_NS import org.rust.lang.core.resolve.processModDeclResolveVariants import org.rust.lang.core.resolve2.util.DollarCrateHelper import org.rust.lang.core.resolve2.util.DollarCrateMap import org.rust.lang.core.resolve2.util.buildStub import org.rust.lang.core.stubs.* import org.rust.openapiext.fileId import org.rust.openapiext.findFileByMaybeRelativePath import org.rust.openapiext.pathAsPath import org.rust.openapiext.toPsiFile class ModCollectorContext( val defMap: CrateDefMap, val context: CollectorContext, val macroDepth: Int = 0, /** * called when new [RsItemElement] is found * default behaviour: just add it to [ModData.visibleItems] * behaviour when processing expanded items: * add it to [ModData.visibleItems] and propagate to modules which have glob import from [ModData] * returns true if [ModData.visibleItems] were changed */ val onAddItem: (ModData, String, PerNs, Visibility) -> Boolean = { containingMod, name, perNs, _ -> containingMod.addVisibleItem(name, perNs) } ) { val isHangingMode: Boolean get() = context.isHangingMode } typealias LegacyMacros = Map<String, DeclMacroDefInfo> fun collectScope( scope: RsItemsOwner, modData: ModData, context: ModCollectorContext, modMacroIndex: MacroIndex = modData.macroIndex, dollarCrateHelper: DollarCrateHelper? = null, includeMacroFile: VirtualFile? = null, propagateLegacyMacros: Boolean = false, ): LegacyMacros { val hashCalculator = HashCalculator(modData.isEnabledByCfgInner) .takeIf { modData.isNormalCrate } val collector = ModCollector(modData, context, modMacroIndex, hashCalculator, dollarCrateHelper, includeMacroFile) collector.collectMod(scope.getOrBuildStub() ?: return emptyMap(), propagateLegacyMacros) if (hashCalculator != null && scope is RsFile) { val fileHash = hashCalculator.getFileHash() context.defMap.addVisitedFile(scope, modData, fileHash) } return collector.legacyMacros } fun collectExpandedElements( expandedFile: RsFileStub, call: MacroCallInfo, context: ModCollectorContext, dollarCrateHelper: DollarCrateHelper? ) { val collector = ModCollector( call.containingMod, context, call.macroIndex, hashCalculator = null, dollarCrateHelper, includeMacroFile = null ) collector.collectMod(expandedFile, propagateLegacyMacros = true) } /** * Collects explicitly declared items in all modules of crate. * Also populates [CollectorContext.imports] and [CollectorContext.macroCalls] in [context]. */ private class ModCollector( private val modData: ModData, private val context: ModCollectorContext, /** * When collecting explicit items in [modData] - equal to `modData.macroIndex`. * When collecting expanded items - equal to macroIndex of macro call. */ private val parentMacroIndex: MacroIndex, private val hashCalculator: HashCalculator?, private val dollarCrateHelper: DollarCrateHelper?, /** containing file, if it is `include!`-ed */ private val includeMacroFile: VirtualFile?, ) : ModVisitor { private val defMap: CrateDefMap = context.defMap private val macroDepth: Int = context.macroDepth private val onAddItem: (ModData, String, PerNs, Visibility) -> Boolean = context.onAddItem private val crate: Crate = context.context.crate private val project: Project = context.context.project /** * Stores collected legacy macros, as well as macros from collected mods with macro_use attribute. * Will be propagated to (lexically) succeeding modules. * See [propagateLegacyMacros]. */ val legacyMacros: MutableMap<String, DeclMacroDefInfo> = hashMapOf() fun collectMod(mod: StubElement<out RsItemsOwner>, propagateLegacyMacros: Boolean = false) { val visitor = if (hashCalculator != null) { val stdlibAttributes = defMap.stdlibAttributes.takeIf { modData.isNormalCrate && modData.isCrateRoot } val hashVisitor = hashCalculator.getVisitor(crate, modData.fileRelativePath, stdlibAttributes) CompositeModVisitor(hashVisitor, this) } else { this } ModCollectorBase.collectMod(mod, modData.isDeeplyEnabledByCfg, visitor, crate) if (propagateLegacyMacros) propagateLegacyMacros(modData) } override fun collectImport(import: ImportLight) { val usePath = if (dollarCrateHelper != null && !import.isExternCrate) { dollarCrateHelper.convertPath(import.usePath, import.offsetInExpansion) } else { import.usePath } context.context.imports += Import( containingMod = modData, usePath = usePath, nameInScope = import.nameInScope, visibility = convertVisibility(import.visibility, import.isDeeplyEnabledByCfg), isGlob = import.isGlob, isExternCrate = import.isExternCrate, isPrelude = import.isPrelude ) if (import.isDeeplyEnabledByCfg && import.isExternCrate && import.isMacroUse && !context.isHangingMode) { defMap.importExternCrateMacros(import.usePath.single()) } } override fun collectSimpleItem(item: SimpleItemLight) { val name = item.name val visItem = convertToVisItem(item, isModOrEnum = false, forceCfgDisabledVisibility = false) val perNs = PerNs.from(visItem, item.namespaces) onAddItem(modData, name, perNs, visItem.visibility) /** See also [DefCollector.tryTreatAsIdentityMacro] */ if (item.procMacroKind != null) { modData.procMacros[name] = item.procMacroKind } } override fun collectModOrEnumItem(item: ModOrEnumItemLight, stub: RsNamedStub) { val name = item.name // could be null if `.resolve()` on `RsModDeclItem` returns null val childModData = tryCollectChildModule(item, stub, item.macroIndexInParent) val forceCfgDisabledVisibility = childModData != null && !childModData.isEnabledByCfgInner val visItem = convertToVisItem(item, isModOrEnum = true, forceCfgDisabledVisibility) childModData?.asVisItem = visItem check(visItem.isModOrEnum) if (childModData == null) return val perNs = PerNs.types(visItem) val changed = onAddItem(modData, name, perNs, visItem.visibility) // We have to check `changed` to be sure that `childModules` and `visibleItems` are consistent. // Note that here we choose first mod if there are multiple mods with same visibility (e.g. CfgDisabled). if (changed) { modData.childModules[name] = childModData } } private fun convertToVisItem(item: ItemLight, isModOrEnum: Boolean, forceCfgDisabledVisibility: Boolean): VisItem { val visibility = if (forceCfgDisabledVisibility) { Visibility.CfgDisabled } else { convertVisibility(item.visibility, item.isDeeplyEnabledByCfg) } val itemPath = modData.path.append(item.name) return VisItem(itemPath, visibility, isModOrEnum) } private fun tryCollectChildModule(item: ModOrEnumItemLight, stub: RsNamedStub, index: Int): ModData? { if (stub is RsEnumItemStub) return collectEnumAsModData(item, stub) val parentOwnedDirectory = includeMacroFile?.parent ?: modData.getOwnedDirectory() val childMod = when (stub) { is RsModItemStub -> ChildMod.Inline(stub, item.name, item.hasMacroUse) is RsModDeclItemStub -> { val childModPsi = resolveModDecl(item.name, item.pathAttribute, parentOwnedDirectory) ?: return null val hasMacroUse = item.hasMacroUse || childModPsi.hasMacroUseInner(crate) ChildMod.File(childModPsi, item.name, hasMacroUse) } else -> return null } val isDeeplyEnabledByCfgOuter = item.isDeeplyEnabledByCfg val isEnabledByCfgInner = childMod !is ChildMod.File || childMod.file.isEnabledByCfgSelf(crate) val (childModData, childModLegacyMacros) = collectChildModule( childMod, isDeeplyEnabledByCfgOuter, isEnabledByCfgInner, item.pathAttribute, index, parentOwnedDirectory ) if (childMod.hasMacroUse && childModData.isDeeplyEnabledByCfg) { modData.addLegacyMacros(childModLegacyMacros) legacyMacros += childModLegacyMacros } if (childModData.isRsFile && childModData.hasPathAttributeRelativeToParentFile && childModData.fileId != null) { recordChildFileInUnusualLocation(modData, childModData.fileId) } return childModData } private fun collectChildModule( childMod: ChildMod, isDeeplyEnabledByCfgOuter: Boolean, isEnabledByCfgInner: Boolean, pathAttribute: String?, index: Int, parentOwnedDirectory: VirtualFile? ): Pair<ModData, LegacyMacros> { ProgressManager.checkCanceled() val childModPath = modData.path.append(childMod.name) val (fileId, fileRelativePath) = when (childMod) { is ChildMod.File -> childMod.file.virtualFile.fileId to "" is ChildMod.Inline -> modData.fileId to "${modData.fileRelativePath}::${childMod.name}" } val childModData = ModData( parent = modData, crate = modData.crate, path = childModPath, macroIndex = parentMacroIndex.append(index), isDeeplyEnabledByCfgOuter = isDeeplyEnabledByCfgOuter, isEnabledByCfgInner = isEnabledByCfgInner, fileId = fileId, fileRelativePath = fileRelativePath, ownedDirectoryId = childMod.getOwnedDirectory(modData, parentOwnedDirectory, pathAttribute)?.fileId, hasPathAttribute = pathAttribute != null, hasMacroUse = childMod.hasMacroUse, crateDescription = defMap.crateDescription ) for ((name, defs) in modData.legacyMacros) { childModData.legacyMacros[name] = defs } val childModLegacyMacros = when (childMod) { is ChildMod.Inline -> { val collector = ModCollector( childModData, context, childModData.macroIndex, hashCalculator, dollarCrateHelper, includeMacroFile ) collector.collectMod(childMod.mod) collector.legacyMacros } is ChildMod.File -> collectScope(childMod.file, childModData, context) } return Pair(childModData, childModLegacyMacros) } private fun collectEnumAsModData(enum: ModOrEnumItemLight, enumStub: RsEnumItemStub): ModData { val enumName = enum.name val enumPath = modData.path.append(enumName) val enumData = ModData( parent = modData, crate = modData.crate, path = enumPath, macroIndex = MacroIndex(intArrayOf() /* Not used anyway */), isDeeplyEnabledByCfgOuter = enum.isDeeplyEnabledByCfg, isEnabledByCfgInner = true, fileId = modData.fileId, fileRelativePath = "${modData.fileRelativePath}::$enumName", ownedDirectoryId = modData.ownedDirectoryId, // actually can use any value here hasPathAttribute = modData.hasPathAttribute, isEnum = true, hasMacroUse = false, crateDescription = defMap.crateDescription ) for (variantPsi in enumStub.variants) { val variantName = variantPsi.name ?: continue val variantPath = enumPath.append(variantName) val isVariantDeeplyEnabledByCfg = enumData.isDeeplyEnabledByCfg && variantPsi.isEnabledByCfgSelf(crate) val variantVisibility = if (isVariantDeeplyEnabledByCfg) Visibility.Public else Visibility.CfgDisabled val variant = VisItem(variantPath, variantVisibility) val variantPerNs = PerNs.from(variant, ENUM_VARIANT_NS) enumData.addVisibleItem(variantName, variantPerNs) } return enumData } override fun collectMacroCall(call: MacroCallLight, stub: RsMacroCallStub) { require(modData.isDeeplyEnabledByCfg) { "for performance reasons cfg-disabled macros should not be collected" } val bodyHash = call.bodyHash if (bodyHash == null && call.path.last() != "include") return val path = dollarCrateHelper?.convertPath(call.path, call.pathOffsetInExpansion) ?: call.path val dollarCrateMap = dollarCrateHelper?.getDollarCrateMap( call.bodyStartOffsetInExpansion, call.bodyEndOffsetInExpansion ) ?: DollarCrateMap.EMPTY val macroIndex = parentMacroIndex.append(call.macroIndexInParent) context.context.macroCalls += MacroCallInfo( modData, macroIndex, path, MacroCallBody.FunctionLike(call.body), bodyHash, containingFileId = includeMacroFile?.fileId ?: modData.fileId, macroDepth, dollarCrateMap ) } override fun collectProcMacroCall(call: ProcMacroCallLight) { require(modData.isDeeplyEnabledByCfg) { "for performance reasons cfg-disabled macros should not be collected" } val (body, bodyHash) = call.lowerBody(project, crate) ?: return val macroIndex = parentMacroIndex.append(call.macroIndexInParent) val path = dollarCrateHelper?.convertPath(call.attrPath, call.attrPathStartOffsetInExpansion) ?: call.attrPath val dollarCrateMap = dollarCrateHelper?.getDollarCrateMap( call.bodyStartOffsetInExpansion, call.bodyEndOffsetInExpansion ) ?: DollarCrateMap.EMPTY val originalItem = call.originalItem?.let { val visItem = convertToVisItem(it, isModOrEnum = false, forceCfgDisabledVisibility = false) Triple(visItem, it.namespaces, it.procMacroKind) } context.context.macroCalls += MacroCallInfo( modData, macroIndex, path, body, bodyHash, containingFileId = null, // will not be used macroDepth, dollarCrateMap, originalItem ) } override fun collectMacroDef(def: MacroDefLight) { val bodyHash = def.bodyHash ?: return val macroPath = modData.path.append(def.name) val macroIndex = parentMacroIndex.append(def.macroIndexInParent) val defInfo = DeclMacroDefInfo( modData.crate, macroPath, macroIndex, def.body, bodyHash, def.hasMacroExport, def.hasLocalInnerMacros, def.hasRustcBuiltinMacro, project ) modData.addLegacyMacro(def.name, defInfo) legacyMacros[def.name] = defInfo if (def.hasMacroExport && !context.isHangingMode) { val visibility = Visibility.Public val visItem = VisItem(macroPath, visibility) val perNs = PerNs.macros(visItem) onAddItem(defMap.root, def.name, perNs, visibility) } } override fun collectMacro2Def(def: Macro2DefLight) { // save macro body for later use modData.macros2[def.name] = DeclMacro2DefInfo( crate = modData.crate, path = modData.path.append(def.name), def.body, def.bodyHash, def.hasRustcBuiltinMacro, project ) // add macro to scope val visibility = convertVisibility(def.visibility, isDeeplyEnabledByCfg = true) val visItem = VisItem(modData.path.append(def.name), visibility) val perNs = PerNs.macros(visItem) onAddItem(modData, def.name, perNs, visibility) } /** * Propagates macro defs expanded from `foo!()` to `mod2`: * ``` * mod mod1; * foo!(); * mod mod2; * ``` */ private fun propagateLegacyMacros(modData: ModData) { if (legacyMacros.isEmpty()) return for (childMod in modData.childModules.values) { if (!childMod.isEnum && MacroIndex.shouldPropagate(parentMacroIndex, childMod.macroIndex)) { childMod.visitDescendants { it.addLegacyMacros(legacyMacros) } } } if (modData.hasMacroUse) { val parent = modData.parent ?: return parent.addLegacyMacros(legacyMacros) propagateLegacyMacros(parent) } } private fun convertVisibility(visibility: VisibilityLight, isDeeplyEnabledByCfg: Boolean): Visibility { if (!isDeeplyEnabledByCfg) return Visibility.CfgDisabled return when (visibility) { VisibilityLight.Public -> Visibility.Public VisibilityLight.RestrictedCrate -> defMap.root.visibilityInSelf VisibilityLight.Private -> modData.visibilityInSelf is VisibilityLight.Restricted -> { resolveRestrictedVisibility(visibility.inPath, modData) ?: defMap.root.visibilityInSelf } } } /** See also [processModDeclResolveVariants] */ private fun resolveModDecl(name: String, pathAttribute: String?, parentOwnedDirectory: VirtualFile?): RsFile? { val (parentDirectory, fileNames) = if (pathAttribute == null) { val fileNames = arrayOf("$name.rs", "$name/mod.rs") if (parentOwnedDirectory == null) return null parentOwnedDirectory to fileNames } else { // https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute val parentDirectory = if (modData.isRsFile) { // For path attributes on modules not inside inline module blocks, // the file path is relative to the directory the source file is located. val containingFile = modData.asVirtualFile() ?: return null containingFile.parent } else { // Paths for path attributes inside inline module blocks are relative to // the directory of file including the inline module components as directories. parentOwnedDirectory } ?: return null val explicitPath = FileUtil.toSystemIndependentName(pathAttribute) parentDirectory to arrayOf(explicitPath) } val virtualFiles = fileNames.mapNotNull { parentDirectory.findFileByMaybeRelativePath(it) } // Note: It is possible that [virtualFiles] is not empty, // but result is null, when e.g. file is too big (thus will be [PsiFile] and not [RsFile]) if (virtualFiles.isEmpty() && !context.isHangingMode) { for (fileName in fileNames) { val path = parentDirectory.pathAsPath.resolve(fileName) defMap.missedFiles.add(path) } } return virtualFiles.singleOrNull()?.toPsiFile(project) as? RsFile } } @Suppress("UNCHECKED_CAST") private fun RsItemsOwner.getOrBuildStub(): StubElement<out RsItemsOwner>? { if (this is RsFileBase) return getOrBuildFileStub() /** * Note that [greenStub] and [buildStub] have consistent (equal) [RsPathStub.startOffset]. * See also [createDollarCrateHelper]. */ (this as? StubBasedPsiElement<*>)?.greenStub?.let { return it as StubElement<out RsItemsOwner> } if (this is RsBlock) return buildStub() if (this is RsModItem) { val containingFile = containingFile as? RsFile ?: return null // In theory `greenStub` can be null after `calcStubTree` (it is linked to PSI with soft references) val stubIndex = PsiAnchor.calcStubIndex(this) if (stubIndex == -1) return null return containingFile.calcStubTree().plainList[stubIndex] as StubElement<out RsItemsOwner> } return null } fun RsFileBase.getOrBuildFileStub(): RsFileStub? { val virtualFile = viewProvider.virtualFile val stubTree = greenStubTree ?: StubTreeLoader.getInstance().readOrBuild(project, virtualFile, this) val stub = stubTree?.root as? RsFileStub if (stub == null) RESOLVE_LOG.error("No stub for file ${virtualFile.path}") return stub } // `#[macro_use] extern crate <name>;` - import macros fun CrateDefMap.importExternCrateMacros(externCrateName: String) { val externCrateDefMap = resolveExternCrateAsDefMap(externCrateName) ?: return importAllMacrosExported(externCrateDefMap) } // https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself private fun resolveRestrictedVisibility(path: Array<String>, containingMod: ModData): Visibility.Restricted? { // Note: complex cases like `pub(in self::super::foo)` are not supported return if (path.all { it == "super" }) { val modData = containingMod.getNthParent(path.size) modData?.visibilityInSelf } else { // Note: Can't use `childModules` here, because it will not contain our parent modules (yet) val parents = containingMod.parents.toMutableList() parents.reverse() parents.getOrNull(path.size) ?.takeIf { path.contentEquals(it.path.segments) } ?.visibilityInSelf } } private fun ModData.getOwnedDirectory(): VirtualFile? { val ownedDirectoryId = ownedDirectoryId ?: return null return PersistentFS.getInstance().findFileById(ownedDirectoryId) } private fun ModData.asVirtualFile(): VirtualFile? { check(isRsFile) return PersistentFS.getInstance().findFileById(fileId ?: return null) ?: run { RESOLVE_LOG.error("Can't find VirtualFile for $this") return null } } private sealed class ChildMod(val name: String, val hasMacroUse: Boolean) { class Inline(val mod: RsModItemStub, name: String, hasMacroUse: Boolean) : ChildMod(name, hasMacroUse) class File(val file: RsFile, name: String, hasMacroUse: Boolean) : ChildMod(name, hasMacroUse) } /** * Have to pass [pathAttribute], because [RsFile.pathAttribute] triggers resolve. * See also: [RsMod.getOwnedDirectory] */ private fun ChildMod.getOwnedDirectory( parentMod: ModData, parentOwnedDirectory: VirtualFile?, pathAttribute: String? ): VirtualFile? { if (this is ChildMod.File && name == RsConstants.MOD_RS_FILE) return file.virtualFile.parent val (parentDirectory, path) = if (pathAttribute != null) { when { this is ChildMod.File -> return file.virtualFile.parent parentMod.isRsFile -> parentMod.asVirtualFile()?.parent to pathAttribute else -> parentOwnedDirectory to pathAttribute } } else { parentOwnedDirectory to name } if (parentDirectory == null) return null // Don't use `FileUtil#getNameWithoutExtension` to correctly process relative paths like `./foo` val directoryPath = FileUtil.toSystemIndependentName(path).removeSuffix(".${RsFileType.defaultExtension}") return parentDirectory.findFileByMaybeRelativePath(directoryPath) } fun recordChildFileInUnusualLocation(parent: ModData, childFileId: FileId) { val persistentFS = PersistentFS.getInstance() val childFile = persistentFS.findFileById(childFileId) ?: return val childDirectory = childFile.parent ?: return for (modData in parent.parents) { val containedDirectory = persistentFS.findFileById(modData.directoryContainedAllChildFiles ?: continue) ?: continue if (VfsUtil.isAncestor(containedDirectory, childDirectory, false)) return val commonAncestor = VfsUtil.getCommonAncestor(containedDirectory, childDirectory) ?: continue modData.directoryContainedAllChildFiles = commonAncestor.fileId } }
mit
216fb59fbf437be0d445588d96a61d33
41.55102
123
0.672502
4.471051
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/TeamPlan.kt
2
710
package com.habitrpg.android.habitica.models import com.google.gson.annotations.SerializedName import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class TeamPlan : RealmObject(), BaseObject { @PrimaryKey var id: String = "" var userID: String? = null var summary: String = "" @SerializedName("leader") var leaderID: String? = null // var managers: RealmList<String> = RealmList() var isActive: Boolean = false override fun equals(other: Any?): Boolean { if (other is TeamPlan) { return this.id == other.id } return super.equals(other) } override fun hashCode(): Int { return id.hashCode() } }
gpl-3.0
67178b5575c7bb02166bfaf63b52b3ef
24.357143
52
0.650704
4.277108
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/tutionfees/TuitionFeesActivity.kt
1
2820
package de.tum.`in`.tumcampusapp.component.tumui.tutionfees import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.button.MaterialButton import android.support.v4.content.ContextCompat import android.widget.TextView import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.other.generic.activity.ActivityForAccessingTumOnline import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.model.TuitionList import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import java.util.* /** * Activity to show the user's tuition fees status */ class TuitionFeesActivity : ActivityForAccessingTumOnline<TuitionList>(R.layout.activity_tuitionfees) { private val amountTextView by lazy { findViewById<TextView>(R.id.amountTextView) } private val deadlineTextView by lazy { findViewById<TextView>(R.id.deadlineTextView) } private val semesterTextView by lazy { findViewById<TextView>(R.id.semesterTextView) } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val button = findViewById<MaterialButton>(R.id.financialAidButton) button.setOnClickListener { val url = getString(R.string.student_financial_aid_link) val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } refreshData(CacheControl.USE_CACHE) } override fun onRefresh() { refreshData(CacheControl.BYPASS_CACHE) } private fun refreshData(cacheControl: CacheControl) { val apiCall = apiClient.getTuitionFeesStatus(cacheControl) fetch(apiCall) } override fun onDownloadSuccessful(response: TuitionList) { val tuition = response.tuitions.first() val amountText = tuition.getAmountText(this) amountTextView.text = amountText val deadline = tuition.deadline val formatter = DateTimeFormat.longDate().withLocale(Locale.getDefault()) val formattedDeadline = formatter.print(deadline) deadlineTextView.text = getString(R.string.due_on_format_string, formattedDeadline) semesterTextView.text = tuition.semester if (tuition.isPaid) { amountTextView.setTextColor(ContextCompat.getColor(this, R.color.sections_green)) } else { // check if the deadline is less than a week from now val nextWeek = DateTime().plusWeeks(1) if (nextWeek.isAfter(deadline)) { amountTextView.setTextColor(ContextCompat.getColor(this, R.color.error)) } else { amountTextView.setTextColor(ContextCompat.getColor(this, R.color.black)) } } } }
gpl-3.0
141f589f052b084ca2e3d5963ee7c911
37.108108
103
0.715248
4.305344
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/electronico/comprobantes/retencion/Retencion.kt
1
1716
package com.quijotelui.electronico.comprobantes.retencion import com.quijotelui.electronico.comprobantes.InformacionTributaria import comprobantes.InformacionAdicional import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement import javax.xml.bind.annotation.XmlType @XmlRootElement(name = "comprobanteRetencion") @XmlType(propOrder = arrayOf( "informacionTributaria", "informacionRetencion", "impuestos", "informacionAdicional" )) class Retencion{ @XmlAttribute private var id : String? = null @XmlAttribute private var version : String? = null @XmlElement(name = "infoTributaria") private var informacionTributaria = InformacionTributaria() @XmlElement(name = "infoCompRetencion") private var informacionRetencion = InformacionRetencion() @XmlElement private var impuestos = Impuestos() @XmlElement(name = "infoAdicional") private var informacionAdicional : InformacionAdicional? = null fun setId(id : String) { this.id = id } fun setVersion(version : String) { this.version = version } fun setInformacionTributaria(informacionTributaria : InformacionTributaria) { this.informacionTributaria = informacionTributaria } fun setInformacionRetencion(informacionRetencion : InformacionRetencion) { this.informacionRetencion = informacionRetencion } fun setImpuestos(impuestos : Impuestos) { this.impuestos = impuestos } fun setInformacionAdicional(informacionAdicional : InformacionAdicional) { this.informacionAdicional = informacionAdicional } }
gpl-3.0
61901ce373ff9da2ca3caa62e40b6477
27.147541
81
0.736597
4.766667
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/google/GoogleJotiMap.kt
1
6563
package nl.rsdt.japp.jotial.maps.wrapper.google import android.graphics.Bitmap import android.location.Location import android.util.Pair import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.* import nl.rsdt.japp.jotial.maps.misc.CameraUtils import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter import nl.rsdt.japp.jotial.maps.wrapper.* import kotlin.collections.HashMap /** * Created by mattijn on 07/08/17. */ class GoogleJotiMap private constructor(private val view: MapView) : IJotiMap, GoogleMap.OnInfoWindowClickListener { override fun onInfoWindowClick(m: Marker?) { val marker = markers[m] if ( m != null) { marker?.onClick() } } var googleMap: GoogleMap? = null private set override val previousCameraPosition:ICameraPosition get() { return GoogleCameraPosition(googleMap!!.cameraPosition) } private val markers: MutableMap<Marker, GoogleMarker> = HashMap() private var previousCameraPositionLatLng: LatLng = LatLng(0.0,0.0) private var previousZoom: Int = 0 private var previousRotation: Float = 0.toFloat() override val uiSettings: IUiSettings get() = GoogleUiSettings(googleMap!!.uiSettings) override fun delete() { for (entry in google_instances){ if (entry.value == this){ google_instances.remove(entry.key) } } } override fun setPreviousCameraPosition(latitude: Double, longitude: Double) { previousCameraPositionLatLng = LatLng(latitude, longitude) } override fun setPreviousZoom(zoom: Int) { previousZoom = zoom } override fun setPreviousRotation(rotation: Float) { this.previousRotation = rotation } override fun followLocation(followLocation: Boolean, keepNorth: Boolean) { TODO("Not yet implemented") } override fun setInfoWindowAdapter(infoWindowAdapter: CustomInfoWindowAdapter) { googleMap!!.setInfoWindowAdapter(infoWindowAdapter) } override fun setGMapType(mapType: Int) { googleMap!!.mapType = mapType } override fun setMapStyle(mapStyleOptions: MapStyleOptions): Boolean { return googleMap!!.setMapStyle(mapStyleOptions) } override fun animateCamera(latLng: LatLng, zoom: Int) { googleMap!!.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom.toFloat())) } override fun addMarker(markerOptions: Pair<MarkerOptions, Bitmap?>): IMarker { if (markerOptions.second != null) { markerOptions.first.icon(BitmapDescriptorFactory.fromBitmap(markerOptions.second)) } else { markerOptions.first.icon(BitmapDescriptorFactory.defaultMarker()) } val gMarker = googleMap!!.addMarker(markerOptions.first) val marker = GoogleMarker(gMarker) markers[gMarker] = marker return marker } override fun addPolyline(polylineOptions: PolylineOptions): IPolyline { return GooglePolyline(googleMap!!.addPolyline(polylineOptions)) } override fun addPolygon(polygonOptions: PolygonOptions): IPolygon { return GooglePolygon(googleMap!!.addPolygon(polygonOptions)) } override fun addCircle(circleOptions: CircleOptions): ICircle { return GoogleCircle(googleMap!!.addCircle(circleOptions)) } override fun setOnMapClickListener(onMapClickListener: IJotiMap.OnMapClickListener?) { if (onMapClickListener == null) { googleMap?.setOnMapClickListener(null) } else { googleMap?.setOnMapClickListener { latLng -> onMapClickListener.onMapClick(latLng) } } } override fun snapshot(snapshotReadyCallback: IJotiMap.SnapshotReadyCallback?) { if (snapshotReadyCallback != null) { googleMap?.snapshot { bitmap -> snapshotReadyCallback.onSnapshotReady(bitmap) } } else { googleMap?.snapshot(null) } } override fun animateCamera(latLng: LatLng, zoom: Int, cancelableCallback: IJotiMap.CancelableCallback?) { val cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom.toFloat()) if (cancelableCallback != null) { googleMap?.animateCamera(cameraUpdate, object : GoogleMap.CancelableCallback { override fun onFinish() { cancelableCallback.onFinish() } override fun onCancel() { cancelableCallback.onCancel() } }) } else { googleMap!!.animateCamera(cameraUpdate, null) } } override fun setOnCameraMoveStartedListener(onCameraMoveStartedListener: GoogleMap.OnCameraMoveStartedListener?) { if (onCameraMoveStartedListener != null) { googleMap!!.setOnCameraMoveStartedListener(onCameraMoveStartedListener) } else { googleMap!!.setOnCameraMoveStartedListener(null) } } override fun cameraToLocation(b: Boolean, location: Location, zoom: Float, aoa: Float, bearing: Float) { CameraUtils.cameraToLocation(b, googleMap, location, zoom, aoa, bearing) } override fun clear() { googleMap!!.clear() } override fun setOnInfoWindowLongClickListener(onInfoWindowLongClickListener: GoogleMap.OnInfoWindowLongClickListener?) { googleMap!!.setOnInfoWindowLongClickListener(onInfoWindowLongClickListener) } override fun setMarkerOnClickListener(listener: IJotiMap.OnMarkerClickListener?) { GoogleMarker.setAllOnClickLister(listener) } override fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) { val t = this view.getMapAsync { map -> googleMap = map map.setOnInfoWindowClickListener(this) map.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(previousCameraPositionLatLng, previousZoom.toFloat(), previousRotation, 0f))) callback.onMapReady(t) } } companion object { private val google_instances = HashMap<MapView, GoogleJotiMap>() fun getJotiMapInstance(map: MapView): GoogleJotiMap? { if (!google_instances.containsKey(map)) { val jm = GoogleJotiMap(map) google_instances[map] = jm } return google_instances[map] } } }
apache-2.0
db5105dc258f21a7b67b1dc13550e5df
33.361257
160
0.672863
5.044581
false
false
false
false
androidx/androidx
compose/ui/ui-graphics/src/commonMain/kotlin/androidx/compose/ui/graphics/colorspace/Rgb.kt
3
51439
/* * Copyright 2019 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.colorspace import kotlin.math.abs import kotlin.math.pow /** * An RGB color space is an additive color space using the * [RGB][ColorModel.Rgb] color model (a color is therefore represented * by a tuple of 3 numbers). * * A specific RGB color space is defined by the following properties: * * * Three chromaticities of the red, green and blue primaries, which * define the gamut of the color space. * * A white point chromaticity that defines the stimulus to which * color space values are normalized (also just called "white"). * * An opto-electronic transfer function, also called opto-electronic * conversion function or often, and approximately, gamma function. * * An electro-optical transfer function, also called electo-optical * conversion function or often, and approximately, gamma function. * * A range of valid RGB values (most commonly `[0..1]`). * * The most commonly used RGB color space is [sRGB][ColorSpaces.Srgb]. * * ### Primaries and white point chromaticities * * In this implementation, the chromaticity of the primaries and the white * point of an RGB color space is defined in the CIE xyY color space. This * color space separates the chromaticity of a color, the x and y components, * and its luminance, the Y component. Since the primaries and the white * point have full brightness, the Y component is assumed to be 1 and only * the x and y components are needed to encode them. * * For convenience, this implementation also allows to define the * primaries and white point in the CIE XYZ space. The tristimulus XYZ values * are internally converted to xyY. * * [sRGB primaries and white point](https://developer.android.com/reference/android/images/graphics/colorspace_srgb.png) * * ### Transfer functions * * A transfer function is a color component conversion function, defined as * a single variable, monotonic mathematical function. It is applied to each * individual component of a color. They are used to perform the mapping * between linear tristimulus values and non-linear electronic signal value. * * The *opto-electronic transfer function* (OETF or OECF) encodes * tristimulus values in a scene to a non-linear electronic signal value. * An OETF is often expressed as a power function with an exponent between * 0.38 and 0.55 (the reciprocal of 1.8 to 2.6). * * The *electro-optical transfer function* (EOTF or EOCF) decodes * a non-linear electronic signal value to a tristimulus value at the display. * An EOTF is often expressed as a power function with an exponent between * 1.8 and 2.6. * * Transfer functions are used as a compression scheme. For instance, * linear sRGB values would normally require 11 to 12 bits of precision to * store all values that can be perceived by the human eye. When encoding * sRGB values using the appropriate OETF (see [sRGB][ColorSpaces.Srgb] for * an exact mathematical description of that OETF), the values can be * compressed to only 8 bits precision. * * When manipulating RGB values, particularly sRGB values, it is safe * to assume that these values have been encoded with the appropriate * OETF (unless noted otherwise). Encoded values are often said to be in * "gamma space". They are therefore defined in a non-linear space. This * in turns means that any linear operation applied to these values is * going to yield mathematically incorrect results (any linear interpolation * such as gradient generation for instance, most image processing functions * such as blurs, etc.). * * To properly process encoded RGB values you must first apply the * EOTF to decode the value into linear space. After processing, the RGB * value must be encoded back to non-linear ("gamma") space. Here is a * formal description of the process, where `f` is the processing * function to apply: * * [See RGB equation](https://developer.android.com/reference/android/graphics/ColorSpace.Rgb) * * If the transfer functions of the color space can be expressed as an * ICC parametric curve as defined in ICC.1:2004-10, the numeric parameters * can be retrieved from [transferParameters]. This can * be useful to match color spaces for instance. * * Some RGB color spaces, such as [ColorSpaces.Aces] and * [scRGB][ColorSpaces.LinearExtendedSrgb], are said to be linear because * their transfer functions are the identity function: `f(x) = x`. * If the source and/or destination are known to be linear, it is not * necessary to invoke the transfer functions. * * ### Range * * Most RGB color spaces allow RGB values in the range `[0..1]`. There * are however a few RGB color spaces that allow much larger ranges. For * instance, [scRGB][ColorSpaces.ExtendedSrgb] is used to manipulate the * range `[-0.5..7.5]` while [ACES][ColorSpaces.Aces] can be used throughout * the range `[-65504, 65504]`. * * [Extended sRGB and its large range](https://developer.android.com/reference/android/images/graphics/colorspace_scrgb.png) * * ### Converting between RGB color spaces * * Conversion between two color spaces is achieved by using an intermediate * color space called the profile connection space (PCS). The PCS used by * this implementation is CIE XYZ. The conversion operation is defined * as such: * * [See RGB equation](https://developer.android.com/reference/android/graphics/ColorSpace.Rgb) * * Where `Tsrc` is the [RGB to XYZ transform][getTransform] * of the source color space and `Tdst^-1` the * [XYZ to RGB transform][getInverseTransform] of the destination color space. * * Many RGB color spaces commonly used with electronic devices use the * standard illuminant [D65][Illuminant.D65]. Care must be take however * when converting between two RGB color spaces if their white points do not * match. This can be achieved by either calling * [adapt] to adapt one or both color spaces to * a single common white point. This can be achieved automatically by calling * [ColorSpace.connect], which also handles * non-RGB color spaces. * * To learn more about the white point adaptation process, refer to the * documentation of [Adaptation]. */ class Rgb /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as a [WhitePoint] * @param transform Computed transform matrix that converts from RGB to XYZ, or * `null` to compute it from `primaries` and `whitePoint`. * @param oetf Opto-electronic transfer function, cannot be null * @param eotf Electro-optical transfer function, cannot be null * @param min The minimum valid value in this color space's RGB range * @param max The maximum valid value in this color space's RGB range * @param transferParameters Parameters for the transfer functions * @param id ID of this color space as an integer between [ColorSpace.MinId] and * [ColorSpace.MaxId] * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * The OETF is null or the EOTF is null. * * The minimum valid value is >= the maximum valid value. * * The ID is not between [ColorSpace.MinId] and [ColorSpace.MaxId]. */ internal constructor( name: String, primaries: FloatArray, val whitePoint: WhitePoint, transform: FloatArray?, oetf: (Double) -> Double, eotf: (Double) -> Double, private val min: Float, private val max: Float, /** * Returns the parameters used by the [electro-optical][eotf] * and [opto-electronic][oetf] transfer functions. If the transfer * functions do not match the ICC parametric curves defined in ICC.1:2004-10 * (section 10.15), this method returns null. * * See [TransferParameters] for a full description of the transfer * functions. * * @return An instance of [TransferParameters] or null if this color * space's transfer functions do not match the equation defined in * [TransferParameters] */ val transferParameters: TransferParameters?, id: Int ) : ColorSpace(name, ColorModel.Rgb, id) { internal val primaries: FloatArray internal val transform: FloatArray internal val inverseTransform: FloatArray internal val oetfOrig = oetf /** * Returns the opto-electronic transfer function (OETF) of this color space. * The inverse function is the electro-optical transfer function (EOTF) returned * by [eotf]. These functions are defined to satisfy the following * equality for x ∈ `[0..1]`: * * OETF(EOTF(x) = EOTF(OETF(x)) = x * * For RGB colors, this function can be used to convert from linear space * to "gamma space" (gamma encoded). The terms gamma space and gamma encoded * are frequently used because many OETFs can be closely approximated using * a simple power function of the form x^γ (the * approximation of the [sRGB][ColorSpaces.Srgb] OETF uses γ = 2.2 * for instance). * * @return A transfer function that converts from linear space to "gamma space" * * @see eotf * @see Rgb.transferParameters */ val oetf: (Double) -> Double = { x -> oetfOrig(x).coerceIn(min.toDouble(), max.toDouble()) } internal val eotfOrig = eotf /** * Returns the electro-optical transfer function (EOTF) of this color space. * The inverse function is the opto-electronic transfer function (OETF) * returned by [oetf]. These functions are defined to satisfy the * following equality for x in `[0..1]`: * * OETF(EOTF(x) = EOTF(OETF(x)) = x * * For RGB colors, this function can be used to convert from "gamma space" * (gamma encoded) to linear space. The terms gamma space and gamma encoded * are frequently used because many EOTFs can be closely approximated using * a simple power function of the form x^γ (the approximation of the * [sRGB][ColorSpaces.Srgb] EOTF uses γ = 2.2 for instance). * * @return A transfer function that converts from "gamma space" to linear space * * @see oetf * @see Rgb.transferParameters */ val eotf: (Double) -> Double = { x -> eotfOrig(x.coerceIn(min.toDouble(), max.toDouble())) } override val isWideGamut: Boolean override val isSrgb: Boolean init { if (primaries.size != 6 && primaries.size != 9) { throw IllegalArgumentException( ( "The color space's primaries must be " + "defined as an array of 6 floats in xyY or 9 floats in XYZ" ) ) } if (min >= max) { throw IllegalArgumentException( "Invalid range: min=$min, max=$max; min must " + "be strictly < max" ) } this.primaries = xyPrimaries(primaries) if (transform == null) { this.transform = computeXYZMatrix(this.primaries, this.whitePoint) } else { if (transform.size != 9) { throw IllegalArgumentException( ( "Transform must have 9 entries! Has " + "${transform.size}" ) ) } this.transform = transform } inverseTransform = inverse3x3(this.transform) // A color space is wide-gamut if its area is >90% of NTSC 1953 and // if it entirely contains the Color space definition in xyY isWideGamut = isWideGamut(this.primaries, min, max) isSrgb = isSrgb(this.primaries, this.whitePoint, oetf, eotf, min, max, id) } /** * Returns the primaries of this color space as a new array of 6 floats. * The Y component is assumed to be 1 and is therefore not copied into * the destination. The x and y components of the first primary are * written in the array at positions 0 and 1 respectively. * * @return A new non-null array of 2 floats * * @see whitePoint */ /*@Size(6)*/ fun getPrimaries(): FloatArray = primaries.copyOf() /** * Returns the transform of this color space as a new array. The * transform is used to convert from RGB to XYZ (with the same white * point as this color space). To connect color spaces, you must first * [adapt][ColorSpace.adapt] them to the * same white point. * * It is recommended to use [ColorSpace.connect] * to convert between color spaces. * * @return A new array of 9 floats * * @see getInverseTransform */ /*@Size(9)*/ fun getTransform(): FloatArray = transform.copyOf() /** * Returns the inverse transform of this color space as a new array. * The inverse transform is used to convert from XYZ to RGB (with the * same white point as this color space). To connect color spaces, you * must first [adapt][ColorSpace.adapt] them * to the same white point. * * It is recommended to use [ColorSpace.connect] * to convert between color spaces. * * @return A new array of 9 floats * * @see getTransform */ /*@Size(9)*/ fun getInverseTransform(): FloatArray = inverseTransform.copyOf() /** * Creates a new RGB color space using a 3x3 column-major transform matrix. * The transform matrix must convert from the RGB space to the profile connection * space CIE XYZ. * * The range of the color space is imposed to be `[0..1]`. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param toXYZ 3x3 column-major transform matrix from RGB to the profile * connection space CIE XYZ as an array of 9 floats, cannot be null * @param oetf Opto-electronic transfer function, cannot be null * @param eotf Electro-optical transfer function, cannot be null * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The OETF is null or the EOTF is null. * * The minimum valid value is >= the maximum valid value. */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(9)*/ toXYZ: FloatArray, oetf: (Double) -> Double, eotf: (Double) -> Double ) : this( name, computePrimaries(toXYZ), computeWhitePoint(toXYZ), null, oetf, eotf, 0.0f, 1.0f, null, MinId ) /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats * @param oetf Opto-electronic transfer function, cannot be null * @param eotf Electro-optical transfer function, cannot be null * @param min The minimum valid value in this color space's RGB range * @param max The maximum valid value in this color space's RGB range * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * The OETF is null or the EOTF is null. * * The minimum valid value is >= the maximum valid value. */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(min = 6, max = 9)*/ primaries: FloatArray, whitePoint: WhitePoint, oetf: (Double) -> Double, eotf: (Double) -> Double, min: Float, max: Float ) : this(name, primaries, whitePoint, null, oetf, eotf, min, max, null, MinId) /** * Creates a new RGB color space using a 3x3 column-major transform matrix. * The transform matrix must convert from the RGB space to the profile connection * space CIE XYZ. * * The range of the color space is imposed to be `[0..1]`. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param toXYZ 3x3 column-major transform matrix from RGB to the profile * connection space CIE XYZ as an array of 9 floats, cannot be null * @param function Parameters for the transfer functions * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * Gamma is negative. */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(9)*/ toXYZ: FloatArray, function: TransferParameters ) : this(name, computePrimaries(toXYZ), computeWhitePoint(toXYZ), function, MinId) /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats * @param function Parameters for the transfer functions * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * The transfer parameters are invalid. */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(min = 6, max = 9)*/ primaries: FloatArray, whitePoint: WhitePoint, function: TransferParameters ) : this(name, primaries, whitePoint, function, MinId) /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats * @param function Parameters for the transfer functions * @param id ID of this color space as an integer between [ColorSpace.MinId] and * [ColorSpace.MaxId] * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * The ID is not between [ColorSpace.MinId] and [ColorSpace.MaxId]. * * The transfer parameters are invalid. * * @see get */ internal constructor( name: String, primaries: FloatArray, whitePoint: WhitePoint, function: TransferParameters, id: Int ) : this( name, primaries, whitePoint, null, if (function.e == 0.0 && function.f == 0.0) { x -> rcpResponse( x, function.a, function.b, function.c, function.d, function.gamma ) } else { x -> rcpResponse( x, function.a, function.b, function.c, function.d, function.e, function.f, function.gamma ) }, if (function.e == 0.0 && function.f == 0.0) { x -> response( x, function.a, function.b, function.c, function.d, function.gamma ) } else { x -> response( x, function.a, function.b, function.c, function.d, function.e, function.f, function.gamma ) }, 0.0f, 1.0f, function, id ) /** * Creates a new RGB color space using a 3x3 column-major transform matrix. * The transform matrix must convert from the RGB space to the profile connection * space CIE XYZ. * * The range of the color space is imposed to be `[0..1]`. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param toXYZ 3x3 column-major transform matrix from RGB to the profile * connection space CIE XYZ as an array of 9 floats, cannot be null * @param gamma Gamma to use as the transfer function * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * Gamma is negative. * * @see get */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(9)*/ toXYZ: FloatArray, gamma: Double ) : this( name, computePrimaries(toXYZ), computeWhitePoint(toXYZ), gamma, 0.0f, 1.0f, MinId ) /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats * @param gamma Gamma to use as the transfer function * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * Gamma is negative. * * @see get */ constructor( /*@Size(min = 1)*/ name: String, /*@Size(min = 6, max = 9)*/ primaries: FloatArray, whitePoint: WhitePoint, gamma: Double ) : this(name, primaries, whitePoint, gamma, 0.0f, 1.0f, MinId) /** * Creates a new RGB color space using a specified set of primaries * and a specified white point. * * The primaries and white point can be specified in the CIE xyY space * or in CIE XYZ. The length of the arrays depends on the chosen space: * * ``` * | Spaces | Primaries length | White point length | * |--------|------------------|--------------------| * | xyY | 6 | 2 | * | XYZ | 9 | 3 | * ``` * * When the primaries and/or white point are specified in xyY, the Y component * does not need to be specified and is assumed to be 1.0. Only the xy components * are required. * * @param name Name of the color space, cannot be null, its length must be >= 1 * @param primaries RGB primaries as an array of 6 (xy) or 9 (XYZ) floats * @param whitePoint Reference white as an array of 2 (xy) or 3 (XYZ) floats * @param gamma Gamma to use as the transfer function * @param min The minimum valid value in this color space's RGB range * @param max The maximum valid value in this color space's RGB range * @param id ID of this color space as an integer between [ColorSpace.MinId] and * [ColorSpace.MaxId] * * @throws IllegalArgumentException If any of the following conditions is met: * * The name is null or has a length of 0. * * The primaries array is null or has a length that is neither 6 or 9. * * The white point array is null or has a length that is neither 2 or 3. * * The minimum valid value is >= the maximum valid value. * * The ID is not between [ColorSpace.MinId] and [ColorSpace.MaxId]. * * Gamma is negative. * * @see get */ internal constructor( name: String, primaries: FloatArray, whitePoint: WhitePoint, gamma: Double, min: Float, max: Float, id: Int ) : this( name, primaries, whitePoint, null, if (gamma == 1.0) DoubleIdentity else { x -> (if (x < 0.0) 0.0 else x).pow(1.0 / gamma) }, if (gamma == 1.0) DoubleIdentity else { x -> (if (x < 0.0) 0.0 else x).pow(gamma) }, min, max, TransferParameters(gamma, 1.0, 0.0, 0.0, 0.0), id ) /** * Creates a copy of the specified color space with a new transform. * * @param colorSpace The color space to create a copy of */ internal constructor( colorSpace: Rgb, transform: FloatArray, whitePoint: WhitePoint ) : this( colorSpace.name, colorSpace.primaries, whitePoint, transform, colorSpace.oetfOrig, colorSpace.eotfOrig, colorSpace.min, colorSpace.max, colorSpace.transferParameters, MinId ) /** * Copies the primaries of this color space in specified array. The Y * component is assumed to be 1 and is therefore not copied into the * destination. The x and y components of the first primary are written * in the array at positions 0 and 1 respectively. * * @param primaries The destination array, cannot be null, its length * must be >= 6 * * @return [primaries] array, modified to contain the primaries of this color space. * * @see getPrimaries */ /*@Size(min = 6)*/ fun getPrimaries(/*@Size(min = 6)*/ primaries: FloatArray): FloatArray { return this.primaries.copyInto(primaries) } /** * Copies the transform of this color space in specified array. The * transform is used to convert from RGB to XYZ (with the same white * point as this color space). To connect color spaces, you must first * [adapt][ColorSpace.adapt] them to the * same white point. * * It is recommended to use [ColorSpace.connect] * to convert between color spaces. * * @param transform The destination array, cannot be null, its length * must be >= 9 * * @return [transform], modified to contain the transform for this color space. * * @see getInverseTransform */ /*@Size(min = 9)*/ fun getTransform(/*@Size(min = 9)*/ transform: FloatArray): FloatArray { return this.transform.copyInto(transform) } /** * Copies the inverse transform of this color space in specified array. * The inverse transform is used to convert from XYZ to RGB (with the * same white point as this color space). To connect color spaces, you * must first [adapt][ColorSpace.adapt] them * to the same white point. * * It is recommended to use [ColorSpace.connect] * to convert between color spaces. * * @param inverseTransform The destination array, cannot be null, its length * must be >= 9 * * @return The [inverseTransform] array passed as a parameter, modified to contain the * inverse transform of this color space. * * @see getTransform */ /*@Size(min = 9)*/ fun getInverseTransform(/*@Size(min = 9)*/ inverseTransform: FloatArray): FloatArray { return this.inverseTransform.copyInto(inverseTransform) } override fun getMinValue(component: Int): Float { return min } override fun getMaxValue(component: Int): Float { return max } /** * Decodes an RGB value to linear space. This is achieved by * applying this color space's electro-optical transfer function * to the supplied values. * * Refer to the documentation of [Rgb] for * more information about transfer functions and their use for * encoding and decoding RGB values. * * @param r The red component to decode to linear space * @param g The green component to decode to linear space * @param b The blue component to decode to linear space * @return A new array of 3 floats containing linear RGB values * * @see toLinear * @see fromLinear */ /*@Size(3)*/ fun toLinear(r: Float, g: Float, b: Float): FloatArray { return toLinear(floatArrayOf(r, g, b)) } /** * Decodes an RGB value to linear space. This is achieved by * applying this color space's electro-optical transfer function * to the first 3 values of the supplied array. The result is * stored back in the input array. * * Refer to the documentation of [Rgb] for * more information about transfer functions and their use for * encoding and decoding RGB values. * * @param v A non-null array of non-linear RGB values, its length * must be at least 3 * @return [v], containing linear RGB values * * @see toLinear * @see fromLinear */ /*@Size(min = 3)*/ fun toLinear(/*@Size(min = 3)*/ v: FloatArray): FloatArray { v[0] = eotf(v[0].toDouble()).toFloat() v[1] = eotf(v[1].toDouble()).toFloat() v[2] = eotf(v[2].toDouble()).toFloat() return v } /** * Encodes an RGB value from linear space to this color space's * "gamma space". This is achieved by applying this color space's * opto-electronic transfer function to the supplied values. * * Refer to the documentation of [Rgb] for * more information about transfer functions and their use for * encoding and decoding RGB values. * * @param r The red component to encode from linear space * @param g The green component to encode from linear space * @param b The blue component to encode from linear space * @return A new array of 3 floats containing non-linear RGB values * * @see fromLinear * @see toLinear */ /*@Size(3)*/ fun fromLinear(r: Float, g: Float, b: Float): FloatArray { return fromLinear(floatArrayOf(r, g, b)) } /** * Encodes an RGB value from linear space to this color space's * "gamma space". This is achieved by applying this color space's * opto-electronic transfer function to the first 3 values of the * supplied array. The result is stored back in the input array. * * Refer to the documentation of [Rgb] for * more information about transfer functions and their use for * encoding and decoding RGB values. * * @param v A non-null array of linear RGB values, its length * must be at least 3 * @return [v], containing non-linear RGB values * * @see fromLinear * @see toLinear */ /*@Size(min = 3)*/ fun fromLinear(/*@Size(min = 3) */v: FloatArray): FloatArray { v[0] = oetf(v[0].toDouble()).toFloat() v[1] = oetf(v[1].toDouble()).toFloat() v[2] = oetf(v[2].toDouble()).toFloat() return v } override fun toXyz(v: FloatArray): FloatArray { v[0] = eotf(v[0].toDouble()).toFloat() v[1] = eotf(v[1].toDouble()).toFloat() v[2] = eotf(v[2].toDouble()).toFloat() return mul3x3Float3(transform, v) } override fun fromXyz(v: FloatArray): FloatArray { mul3x3Float3(inverseTransform, v) v[0] = oetf(v[0].toDouble()).toFloat() v[1] = oetf(v[1].toDouble()).toFloat() v[2] = oetf(v[2].toDouble()).toFloat() return v } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false if (!super.equals(other)) return false val rgb = other as Rgb if (rgb.min.compareTo(min) != 0) return false if (rgb.max.compareTo(max) != 0) return false if (whitePoint != rgb.whitePoint) return false if (!(primaries contentEquals rgb.primaries)) return false if (transferParameters != null) { return transferParameters == rgb.transferParameters } else if (rgb.transferParameters == null) { return true } return if (oetfOrig != rgb.oetfOrig) false else eotfOrig == rgb.eotfOrig } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + whitePoint.hashCode() result = 31 * result + primaries.contentHashCode() result = 31 * result + (if (min != +0.0f) min.toBits() else 0) result = 31 * result + (if (max != +0.0f) max.toBits() else 0) result = ( 31 * result + if (transferParameters != null) transferParameters.hashCode() else 0 ) if (transferParameters == null) { result = 31 * result + oetfOrig.hashCode() result = 31 * result + eotfOrig.hashCode() } return result } // internal so that current.txt doesn't expose it: a 'private' companion object // is marked deprecated internal companion object { private val DoubleIdentity: (Double) -> Double = { d -> d } /** * Computes whether a color space is the sRGB color space or at least * a close approximation. * * @param primaries The set of RGB primaries in xyY as an array of 6 floats * @param whitePoint The white point in xyY as an array of 2 floats * @param OETF The opto-electronic transfer function * @param EOTF The electro-optical transfer function * @param min The minimum value of the color space's range * @param max The minimum value of the color space's range * @param id The ID of the color space * @return True if the color space can be considered as the sRGB color space * * @see isSrgb */ private fun isSrgb( primaries: FloatArray, whitePoint: WhitePoint, OETF: (Double) -> Double, EOTF: (Double) -> Double, min: Float, max: Float, id: Int ): Boolean { if (id == 0) return true if (!compare(primaries, ColorSpaces.SrgbPrimaries)) { return false } if (!compare(whitePoint, Illuminant.D65)) { return false } if (min != 0.0f) return false if (max != 1.0f) return false // We would have already returned true if this was SRGB itself, so // it is safe to reference it here. val srgb = ColorSpaces.Srgb var x = 0.0 while (x <= 1.0) { if (!compare( x, OETF, srgb.oetfOrig ) ) return false if (!compare( x, EOTF, srgb.eotfOrig ) ) return false x += 1 / 255.0 } return true } private fun compare( point: Double, a: (Double) -> Double, b: (Double) -> Double ): Boolean { val rA = a(point) val rB = b(point) return abs(rA - rB) <= 1e-3 } /** * Computes whether the specified CIE xyY or XYZ primaries (with Y set to 1) form * a wide color gamut. A color gamut is considered wide if its area is &gt; 90% * of the area of NTSC 1953 and if it contains the sRGB color gamut entirely. * If the conditions above are not met, the color space is considered as having * a wide color gamut if its range is larger than [0..1]. * * @param primaries RGB primaries in CIE xyY as an array of 6 floats * @param min The minimum value of the color space's range * @param max The minimum value of the color space's range * @return True if the color space has a wide gamut, false otherwise * * @see isWideGamut * @see area */ private fun isWideGamut( primaries: FloatArray, min: Float, max: Float ): Boolean { return ( ( ( area(primaries) / area( ColorSpaces.Ntsc1953Primaries ) > 0.9f && contains( primaries, ColorSpaces.SrgbPrimaries ) ) ) || (min < 0.0f && max > 1.0f) ) } /** * Computes the area of the triangle represented by a set of RGB primaries * in the CIE xyY space. * * @param primaries The triangle's vertices, as RGB primaries in an array of 6 floats * @return The area of the triangle * * @see isWideGamut */ private fun area(primaries: FloatArray): Float { val rx = primaries[0] val ry = primaries[1] val gx = primaries[2] val gy = primaries[3] val bx = primaries[4] val by = primaries[5] val det = rx * gy + ry * bx + gx * by - gy * bx - ry * gx - rx * by val r = 0.5f * det return if (r < 0.0f) -r else r } /** * Computes the cross product of two 2D vectors. * * @param ax The x coordinate of the first vector * @param ay The y coordinate of the first vector * @param bx The x coordinate of the second vector * @param by The y coordinate of the second vector * @return The result of a x b */ private fun cross(ax: Float, ay: Float, bx: Float, by: Float): Float { return ax * by - ay * bx } /** * Decides whether a 2D triangle, identified by the 6 coordinates of its * 3 vertices, is contained within another 2D triangle, also identified * by the 6 coordinates of its 3 vertices. * * In the illustration below, we want to test whether the RGB triangle * is contained within the triangle XYZ formed by the 3 vertices at * the "+" locations. * * * Y . * . + . * . .. * . . * . . * . G * * * * * * ** * * * ** * * * * ** * * * * * * * * ** * * * * * * ** * ** * R ... * * * ..... * * ***** .. * ** ************ . + * B * ************ . X * ......***** . * ...... . . * .. * + . * Z . * * RGB is contained within XYZ if all the following conditions are true * (with "x" the cross product operator): * * --> --> * GR x RX >= 0 * --> --> * RX x BR >= 0 * --> --> * RG x GY >= 0 * --> --> * GY x RG >= 0 * --> --> * RB x BZ >= 0 * --> --> * BZ x GB >= 0 * * @param p1 The enclosing triangle as 6 floats * @param p2 The enclosed triangle as 6 floats * @return True if the triangle p1 contains the triangle p2 * * @see isWideGamut */ private fun contains(p1: FloatArray, p2: FloatArray): Boolean { // Translate the vertices p1 in the coordinates system // with the vertices p2 as the origin val p0 = floatArrayOf( p1[0] - p2[0], p1[1] - p2[1], p1[2] - p2[2], p1[3] - p2[3], p1[4] - p2[4], p1[5] - p2[5] ) // Check the first vertex of p1 if (( cross( p0[0], p0[1], p2[0] - p2[4], p2[1] - p2[5] ) < 0 || cross( p2[0] - p2[2], p2[1] - p2[3], p0[0], p0[1] ) < 0 ) ) { return false } // Check the second vertex of p1 if (( cross( p0[2], p0[3], p2[2] - p2[0], p2[3] - p2[1] ) < 0 || cross( p2[2] - p2[4], p2[3] - p2[5], p0[2], p0[3] ) < 0 ) ) { return false } // Check the third vertex of p1 return !( cross( p0[4], p0[5], p2[4] - p2[2], p2[5] - p2[3] ) < 0 || cross( p2[4] - p2[0], p2[5] - p2[1], p0[4], p0[5] ) < 0 ) } /** * Computes the primaries of a color space identified only by * its RGB->XYZ transform matrix. This method assumes that the * range of the color space is [0..1]. * * @param toXYZ The color space's 3x3 transform matrix to XYZ * @return A new array of 6 floats containing the color space's * primaries in CIE xyY */ internal fun computePrimaries(toXYZ: FloatArray): FloatArray { val r = mul3x3Float3( toXYZ, floatArrayOf(1.0f, 0.0f, 0.0f) ) val g = mul3x3Float3( toXYZ, floatArrayOf(0.0f, 1.0f, 0.0f) ) val b = mul3x3Float3( toXYZ, floatArrayOf(0.0f, 0.0f, 1.0f) ) val rSum = r[0] + r[1] + r[2] val gSum = g[0] + g[1] + g[2] val bSum = b[0] + b[1] + b[2] return floatArrayOf( r[0] / rSum, r[1] / rSum, g[0] / gSum, g[1] / gSum, b[0] / bSum, b[1] / bSum ) } /** * Computes the white point of a color space identified only by * its RGB->XYZ transform matrix. This method assumes that the * range of the color space is [0..1]. * * @param toXYZ The color space's 3x3 transform matrix to XYZ * @return A new array of 2 floats containing the color space's * white point in CIE xyY */ private fun computeWhitePoint(toXYZ: FloatArray): WhitePoint { val w = mul3x3Float3( toXYZ, floatArrayOf(1.0f, 1.0f, 1.0f) ) val sum = w[0] + w[1] + w[2] return WhitePoint(w[0] / sum, w[1] / sum) } /** * Converts the specified RGB primaries point to xyY if needed. The primaries * can be specified as an array of 6 floats (in CIE xyY) or 9 floats * (in CIE XYZ). If no conversion is needed, the input array is copied. * * @param primaries The primaries in xyY or XYZ, in an array of 6 floats. * @return A new array of 6 floats containing the primaries in xyY */ private fun xyPrimaries(primaries: FloatArray): FloatArray { val xyPrimaries = FloatArray(6) // XYZ to xyY if (primaries.size == 9) { var sum: Float = primaries[0] + primaries[1] + primaries[2] xyPrimaries[0] = primaries[0] / sum xyPrimaries[1] = primaries[1] / sum sum = primaries[3] + primaries[4] + primaries[5] xyPrimaries[2] = primaries[3] / sum xyPrimaries[3] = primaries[4] / sum sum = primaries[6] + primaries[7] + primaries[8] xyPrimaries[4] = primaries[6] / sum xyPrimaries[5] = primaries[7] / sum } else { primaries.copyInto(xyPrimaries, endIndex = 6) } return xyPrimaries } /** * Computes the matrix that converts from RGB to XYZ based on RGB * primaries and a white point, both specified in the CIE xyY space. * The Y component of the primaries and white point is implied to be 1. * * @param primaries The RGB primaries in xyY, as an array of 6 floats * @param whitePoint The white point in xyY, as an array of 2 floats * @return A 3x3 matrix as a new array of 9 floats */ private fun computeXYZMatrix( primaries: FloatArray, whitePoint: WhitePoint ): FloatArray { val rx = primaries[0] val ry = primaries[1] val gx = primaries[2] val gy = primaries[3] val bx = primaries[4] val by = primaries[5] val wx = whitePoint.x val wy = whitePoint.y val oneRxRy = (1 - rx) / ry val oneGxGy = (1 - gx) / gy val oneBxBy = (1 - bx) / by val oneWxWy = (1 - wx) / wy val rxRy = rx / ry val gxGy = gx / gy val bxBy = bx / by val wxWy = wx / wy val byNumerator = (oneWxWy - oneRxRy) * (gxGy - rxRy) - (wxWy - rxRy) * (oneGxGy - oneRxRy) val byDenominator = (oneBxBy - oneRxRy) * (gxGy - rxRy) - (bxBy - rxRy) * (oneGxGy - oneRxRy) val bY = byNumerator / byDenominator val gY = (wxWy - rxRy - bY * (bxBy - rxRy)) / (gxGy - rxRy) val rY = 1f - gY - bY val rYRy = rY / ry val gYGy = gY / gy val bYBy = bY / by return floatArrayOf( rYRy * rx, rY, rYRy * (1f - rx - ry), gYGy * gx, gY, gYGy * (1f - gx - gy), bYBy * bx, bY, bYBy * (1f - bx - by) ) } } }
apache-2.0
a26968f5f3cc1825d6e995aaf3ea31a3
37.847432
124
0.56211
4.123547
false
false
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/CachedPagingData.kt
3
4567
/* * Copyright 2019 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.paging import androidx.annotation.CheckResult import androidx.annotation.VisibleForTesting import androidx.paging.ActiveFlowTracker.FlowType.PAGED_DATA_FLOW import androidx.paging.ActiveFlowTracker.FlowType.PAGE_EVENT_FLOW import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.shareIn /** * A PagingData wrapper that makes it "efficiently" share-able between multiple downstreams. * It flattens all previous pages such that a new subscriber will get all of them at once (and * also not deal with dropped pages, intermediate loading state changes etc). */ private class MulticastedPagingData<T : Any>( val scope: CoroutineScope, val parent: PagingData<T>, // used in tests val tracker: ActiveFlowTracker? = null ) { private val accumulated = CachedPageEventFlow( src = parent.flow, scope = scope ).also { tracker?.onNewCachedEventFlow(it) } fun asPagingData() = PagingData( flow = accumulated.downstreamFlow.onStart { tracker?.onStart(PAGE_EVENT_FLOW) }.onCompletion { tracker?.onComplete(PAGE_EVENT_FLOW) }, uiReceiver = parent.uiReceiver, hintReceiver = parent.hintReceiver ) suspend fun close() = accumulated.close() } /** * Caches the [PagingData] such that any downstream collection from this flow will share the same * [PagingData]. * * The flow is kept active as long as the given [scope] is active. To avoid leaks, make sure to * use a [scope] that is already managed (like a ViewModel scope) or manually cancel it when you * don't need paging anymore. * * A common use case for this caching is to cache [PagingData] in a ViewModel. This can ensure that, * upon configuration change (e.g. rotation), then new Activity will receive the existing data * immediately rather than fetching it from scratch. * * Calling [cachedIn] is required to allow calling * [submitData][androidx.paging.AsyncPagingDataAdapter] on the same instance of [PagingData] * emitted by [Pager] or any of its transformed derivatives, as reloading data from scratch on the * same generation of [PagingData] is an unsupported operation. * * Note that this does not turn the `Flow<PagingData>` into a hot stream. It won't execute any * unnecessary code unless it is being collected. * * @sample androidx.paging.samples.cachedInSample * * @param scope The coroutine scope where this page cache will be kept alive. */ @CheckResult public fun <T : Any> Flow<PagingData<T>>.cachedIn( scope: CoroutineScope ): Flow<PagingData<T>> = cachedIn(scope, null) internal fun <T : Any> Flow<PagingData<T>>.cachedIn( scope: CoroutineScope, // used in tests tracker: ActiveFlowTracker? = null ): Flow<PagingData<T>> { return this.simpleMapLatest { MulticastedPagingData( scope = scope, parent = it, tracker = tracker ) }.simpleRunningReduce { prev, next -> prev.close() next }.map { it.asPagingData() }.onStart { tracker?.onStart(PAGED_DATA_FLOW) }.onCompletion { tracker?.onComplete(PAGED_DATA_FLOW) }.shareIn( scope = scope, started = SharingStarted.Lazily, // replay latest multicasted paging data since it is re-connectable. replay = 1 ) } /** * This is only used for testing to ensure we don't leak resources */ @VisibleForTesting internal interface ActiveFlowTracker { fun onNewCachedEventFlow(cachedPageEventFlow: CachedPageEventFlow<*>) suspend fun onStart(flowType: FlowType) suspend fun onComplete(flowType: FlowType) enum class FlowType { PAGED_DATA_FLOW, PAGE_EVENT_FLOW } }
apache-2.0
1a186d3f50cd977fe160644450f5fa5f
33.598485
100
0.712503
4.280225
false
true
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/selection/handlers/KotlinElementSelectioner.kt
1
1450
package org.jetbrains.kotlin.ui.editors.selection.handlers import java.util.ArrayList import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement public object KotlinElementSelectioner { private val selectionHandlers = listOf( KotlinListSelectionHandler(), KotlinBlockSelectionHandler(), KotlinWhiteSpaceSelectionHandler(), KotlinDocSectionSelectionHandler(), KotlinDeclarationSelectionHandler(), KotlinStringTemplateSelectionHandler(), KotlinNonTraversableSelectionHanlder()//must be last ) private val defaultHandler = KotlinDefaultSelectionHandler() public fun selectEnclosing(enclosingElement:PsiElement, selectedRange:TextRange):TextRange = findHandler(enclosingElement).selectEnclosing(enclosingElement, selectedRange) public fun selectNext(enclosingElement:PsiElement, selectionCandidate:PsiElement, selectedRange:TextRange):TextRange = findHandler(enclosingElement).selectNext(enclosingElement, selectionCandidate, selectedRange) public fun selectPrevious(enclosingElement:PsiElement, selectionCandidate:PsiElement, selectedRange:TextRange):TextRange = findHandler(enclosingElement).selectPrevious(enclosingElement, selectionCandidate, selectedRange) private fun findHandler(enclosingElement:PsiElement) = selectionHandlers.firstOrNull { it.canSelect(enclosingElement) } ?: defaultHandler }
apache-2.0
37cea3323bcc6f20c3575d2eff5182c9
41.676471
124
0.791034
5.823293
false
false
false
false
overworld-hosting/overworld
core/src/test/kotlin/com/turtleboxgames/overworld/UUIDSpec.kt
1
1362
package com.turtleboxgames.overworld import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.* import com.natpryce.hamkrest.* import com.natpryce.hamkrest.assertion.* import java.util.* object UUIDSpec: Spek({ describe("UUID extensions") { val uuid_str = "dfc78d43-4cb0-46d4-8201-c00171ff383b" val uuid_str64 = "38eNQ0ywRtSCAcABcf84Ow" val uuid_bytes = byteArrayOf(-33, -57, -115, 67, 76, -80, 70, -44, -126, 1, -64, 1, 113, -1, 56, 59) val uuid = UUID.fromString(uuid_str) on("bytes") { val bytes = uuid.bytes() it("is 16 bytes long") { assert.that(bytes.size, equalTo(16)) } it("contains the expected bytes") { assert.that(Arrays.equals(bytes, uuid_bytes), equalTo(true)) } } on("base64") { val str = uuid.base64() it("is 22 characters") { assert.that(str, has(String::length, equalTo(22))) } it("contains the expected value") { assert.that(str, equalTo(uuid_str64)) } } on("getBase64UUID") { val ret = uuid_str64.getBase64UUID() it("returns the expected value") { assert.that(ret, equalTo(uuid)) } } } })
mit
485bf966a76028a5f9316b64417dfb60
27.395833
108
0.53304
3.632
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginModelGroupTestPsiImpl.kt
1
2506
/* * Copyright (C) 2019-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.plugin import com.intellij.lang.ASTNode import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.psi.ASTWrapperPsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmModelGroup import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginModelGroupTest class PluginModelGroupTestPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginModelGroupTest, XpmSyntaxValidationElement { companion object { private val TYPE_NAME = Key.create<String>("TYPE_NAME") } // region ASTDelegatePsiElement override fun subtreeChanged() { super.subtreeChanged() clearUserData(TYPE_NAME) } // endregion // region PluginModelGroupTest override val nodeName: XsQNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull() // endregion // region XdmSequenceType override val typeName: String get() = computeUserDataIfAbsent(TYPE_NAME) { nodeName?.let { "model-group(${qname_presentation(it)})" } ?: "model-group()" } override val itemType: XdmItemType get() = this override val lowerBound: Int = 1 override val upperBound: Int = 1 // endregion // region XdmItemType override val typeClass: Class<*> = XdmModelGroup::class.java // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = firstChild // endregion }
apache-2.0
c449f2236eb63d1afd9c2c5171c7ae60
32.413333
89
0.736233
4.33564
false
true
false
false
PublicXiaoWu/XiaoWuMySelf
app/src/main/java/com/xiaowu/myself/main/fragment/FragmentFactory.kt
1
1780
package com.xiaowu.myself.main.fragment import android.content.Context /** * Explanation: * @author LSX * Created on 2018/1/22. */ class FragmentFactory private constructor(context: Context) { companion object { var instance: FragmentFactory? = null fun getInstance(context: Context): FragmentFactory { if (instance == null) { synchronized(FragmentFactory::class) { if (instance == null) { instance = FragmentFactory(context) } } } return instance!! } } private var firstFragment: FirstFragment? = null private var twoFragment: TwoFragment? = null private var mThreefragment: ThreeFragment? = null /** * 首页 */ fun getHomeFragment(): FirstFragment { if (firstFragment == null) { synchronized(FirstFragment::class) { if (firstFragment == null) { firstFragment = FirstFragment() } } } return firstFragment!! } /** * 首页 */ fun getTwoFragment(): TwoFragment { if (twoFragment == null) { synchronized(FirstFragment::class) { if (twoFragment == null) { twoFragment = TwoFragment() } } } return twoFragment!! } /** * 首页 */ fun getThreeFragment(): ThreeFragment { if (mThreefragment == null) { synchronized(FirstFragment::class) { if (mThreefragment == null) { mThreefragment = ThreeFragment() } } } return mThreefragment!! } }
apache-2.0
6f448a26df168ead3c303503b3e6008e
24.242857
61
0.502831
5.017045
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/theme/compose/night/Color.kt
1
1644
package wangdaye.com.geometricweather.theme.compose.night import androidx.compose.ui.graphics.Color val night_md_theme_dark_primary = Color(0xFFa8c7ff) val night_md_theme_dark_onPrimary = Color(0xFF002f67) val night_md_theme_dark_primaryContainer = Color(0xFF004591) val night_md_theme_dark_onPrimaryContainer = Color(0xFFd6e3ff) val night_md_theme_dark_secondary = Color(0xFF5bd5f9) val night_md_theme_dark_onSecondary = Color(0xFF003542) val night_md_theme_dark_secondaryContainer = Color(0xFF004e60) val night_md_theme_dark_onSecondaryContainer = Color(0xFFb1ebff) val night_md_theme_dark_tertiary = Color(0xFFeec148) val night_md_theme_dark_onTertiary = Color(0xFF3f2e00) val night_md_theme_dark_tertiaryContainer = Color(0xFF5a4300) val night_md_theme_dark_onTertiaryContainer = Color(0xFFffdf8e) val night_md_theme_dark_error = Color(0xFFF2B8B5) val night_md_theme_dark_errorContainer = Color(0xFF8C1D18) val night_md_theme_dark_onError = Color(0xFF601410) val night_md_theme_dark_onErrorContainer = Color(0xFFF9DEDC) val night_md_theme_dark_background = Color(0xFF1b1b1d) val night_md_theme_dark_onBackground = Color(0xFFe3e2e6) val night_md_theme_dark_surface = Color(0xFF1b1b1d) val night_md_theme_dark_onSurface = Color(0xFFe3e2e6) val night_md_theme_dark_surfaceVariant = Color(0xFF46464F) val night_md_theme_dark_onSurfaceVariant = Color(0xFFCAC4D0) val night_md_theme_dark_outline = Color(0x10ffffff) val night_md_theme_dark_inverseOnSurface = Color(0xFF1b1b1d) val night_md_theme_dark_inverseSurface = Color(0xFFe3e2e6) val night_md_theme_dark_inversePrimary = Color(0xFF205daf) val night_md_theme_dark_shadow = Color(0xFF000000)
lgpl-3.0
75f67f560ef5495bc56249b265f1734a
53.833333
64
0.811436
2.695082
false
false
false
false
midhunhk/random-contact
app/src/main/java/com/ae/apps/randomcontact/utils/AppUtils.kt
1
2301
package com.ae.apps.randomcontact.utils import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.database.Cursor import android.net.Uri import android.provider.ContactsContract import android.widget.Toast import com.ae.apps.lib.common.utils.ContactUtils.cleanupPhoneNumber var DEFAULT_CONTACT_GROUP = "0" var CONTACT_ID_SEPARATOR = "," var PACKAGE_NAME_WHATSAPP = "com.whatsapp" private const val DEFAULT_DATE_FORMAT = "MMM dd, yyyy hh:mm a" private const val CONTENT_CONTACTS_DATA = "content://com.android.contacts/data/" /** * Send a WhatsAppMessage to a contact number * _experimental feature_ * * @param context context */ fun sendWhatsAppMessage(context: Context, contactNo: String) { sendWhatsAppMethod3(context, contactNo) } /** * This method opens the conversation screen for the contact * The number should have the Country code prefixed when it was saved, * else whatsapp will not open * * @param context context * @param contactNo contactNo */ private fun sendWhatsAppMethod3(context: Context, contactNo: String) { val id = cleanupPhoneNumber(contactNo) + "@s.whatsapp.net" var cursor: Cursor? = null try { cursor = context.contentResolver.query( ContactsContract.Data.CONTENT_URI, arrayOf(ContactsContract.Contacts.Data._ID), ContactsContract.Data.DATA1 + "=?", arrayOf(id), null ) if (null != cursor && !cursor.moveToFirst()) { Toast.makeText( context, "WhatsApp contact with this number not found. Make sure it has country code.", Toast.LENGTH_LONG ).show() return } val sendIntent = Intent(Intent.ACTION_VIEW, Uri.parse(CONTENT_CONTACTS_DATA + (cursor?.getString(0)))) val packageManager = context.packageManager if (null == sendIntent.resolveActivity(packageManager)) { Toast.makeText(context, "No Activity to handle this Intent", Toast.LENGTH_SHORT).show() } else { context.startActivity(sendIntent) } } catch (ex: ActivityNotFoundException) { Toast.makeText(context, ex.message, Toast.LENGTH_SHORT).show() } finally { cursor?.close() } }
apache-2.0
7b083c982f3463e15814a017ff615de9
33.863636
99
0.683181
4.15343
false
false
false
false
patm1987/lwjgl_test
src/main/kotlin/com/pux0r3/lwjgltest/LookAtPerspectiveCamera.kt
1
4138
package com.pux0r3.lwjgltest import org.joml.Math import org.joml.Matrix4f import org.joml.Quaternionf import org.joml.Vector3f import org.lwjgl.opengl.GL20 import org.lwjgl.system.MemoryStack // TODO: when I make a scenegraph, lookat should act on the node generically class LookAtPerspectiveCamera( fov: Float, aspect: Float, near: Float = .01f, far: Float = 100f, target: Vector3f = Vector3f()) : ICamera { override val transform = Transform() private var perspectiveDirty = true private var _fov: Float = fov set(value) { perspectiveDirty = true field = value } private var _aspect: Float = aspect set(value) { perspectiveDirty = true field = value } private var _near: Float = near set(value) { perspectiveDirty = true field = value } private var _far: Float = far set(value) { perspectiveDirty = true field = value } private var perspectiveMatrix = Matrix4f() private var viewMatrix = Matrix4f() private var _target: Vector3f = target private val upVector = Vector3f(0f, 1f, 0f) private var viewProjectionMatrix = Matrix4f() override fun setResolution(width: Int, height: Int) { _aspect = width.toFloat() / height.toFloat() } /** * Loads the uniform with our ViewProjection matrix * TODO: Shader should load the Uniform and we should just provide a Matrix accordingly */ override fun loadUniform(uniformId: Int) { if (perspectiveDirty) { updatePerspectiveMatrix() } updateViewMatrix() updateViewProjectionMatrix() MemoryStack.stackPush().use { val nativeMatrix = it.mallocFloat(16) viewProjectionMatrix.get(nativeMatrix) GL20.glUniformMatrix4fv(uniformId, false, nativeMatrix) } } private fun updatePerspectiveMatrix() { perspectiveMatrix.setPerspective(_fov, _aspect, _near, _far) perspectiveDirty = false } private fun updateViewMatrix() { /* * For some reason, [Quaternionf.lookAlong] isn't working as I expect. I manually build a quaternion here that * sets its -z vector to look at the target. It also corrects its up vector to face up. * * TODO: actually make this efficient */ // get the vector to the target val position = Vector3f() transform.getPosition(position) val vectorToTarget = Vector3f(_target) vectorToTarget.sub(position) vectorToTarget.normalize() // rotate to point -z along this vector val rotation = Quaternionf() rotation.rotationTo(Vector3f(0f, 0f, -1f), vectorToTarget) // compute the current up as [fromUp]. Compute the target up as [targetUp]. [targetUp] must be perpendicular to forward val forward = Vector3f(0f, 0f, 1f) rotation.transform(forward) val fromUp = Vector3f(0f, 1f, 0f) rotation.transform(fromUp) val targetUp = Vector3f() forward.cross(Vector3f(0f, 1f, 0f), targetUp).cross(forward) // correct the quaternion so up is up val correction = Quaternionf() correction.rotationTo(fromUp, targetUp) rotation.premul(correction) // apply the rotation to the transform transform.setRotation(rotation) // get our view matrix transform.getInverseWorldMatrix(viewMatrix) } private fun updateViewProjectionMatrix() { viewProjectionMatrix.set(perspectiveMatrix).mul(viewMatrix) } /** * Sets the target of this camera * note that this value will be copied in * @param target the new target of the camera */ fun setTarget(target: Vector3f) { _target = target } /** * retrieves the target of this camera * @param outTarget the value that will hold this camera's target */ fun getTarget(outTarget: Vector3f) { outTarget.set(_target) } }
mit
9f04b4fb9a5d88d0a5b94cdaa5f21d00
29.88806
127
0.627356
4.360379
false
false
false
false
Heiner1/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusTime.kt
1
2070
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgInitConnStatusTime( injector: HasAndroidInjector ) : MessageBase(injector) { init { setCommand(0x0301) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 > 7) { val notification = Notification(Notification.WRONG_DRIVER, rh.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to Korean DanaR") danaRKoreanPlugin.setPluginEnabled(PluginType.PUMP, true) danaRKoreanPlugin.setFragmentVisible(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, false) danaRPlugin.setFragmentVisible(PluginType.PUMP, false) danaPump.reset() // mark not initialized pumpSync.connectNewPump() //If profile coming from pump, switch it as well configBuilder.storeSettings("ChangingDanaDriver") rxBus.send(EventRebuildTabs()) commandQueue.readStatus(rh.gs(R.string.pump_driver_change), null) // force new connection failed = false return } else { failed = true } val time = dateTimeSecFromBuff(bytes, 0) val versionCode = intFromBuff(bytes, 6, 1) aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time)) aapsLogger.debug(LTag.PUMPCOMM, "Version code: $versionCode") } }
agpl-3.0
5d9fdb0afa85354c04e465a2db5349c4
44.021739
128
0.705314
4.630872
false
false
false
false
sivaprasadreddy/springboot-tutorials
spring-boot-k8s-demo/src/main/kotlin/com/sivalabs/geeksclub/entities/User.kt
1
964
package com.sivalabs.geeksclub.entities import javax.persistence.* import javax.validation.constraints.Email import javax.validation.constraints.NotBlank @Entity @Table(name = "users") class User { @Id @SequenceGenerator(name = "user_generator", sequenceName = "user_sequence", initialValue = 10) @GeneratedValue(generator = "user_generator") var id: Long? = null @Column(nullable = false, unique = true) @NotBlank(message = "Email must not be blank") @Email(message = "Email address is invalid") var email: String = "" @Column(nullable = false) @NotBlank(message = "Password must not be blank") var password: String = "" @Column(nullable = false) @NotBlank(message = "Name must not be blank") var name: String = "" @Column(nullable = true) var website: String = "" @Column(nullable = true, length = 4000) var bio: String = "" @Column(nullable = false) var role: String = "" }
apache-2.0
677c1b1057a1bc717c7949977006b572
25.805556
98
0.6639
3.918699
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateEqualsAndHashcodeAction.kt
3
15115
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions.generate import com.intellij.codeInsight.CodeInsightSettings import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.insertMembersAfterAndReformat import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull fun ClassDescriptor.findDeclaredEquals(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("equals", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.singleOrNull()?.type == it.builtIns.nullableAnyType && it.typeParameters.isEmpty() } } fun ClassDescriptor.findDeclaredHashCode(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("hashCode", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.isEmpty() && it.typeParameters.isEmpty() } } class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<KotlinGenerateEqualsAndHashcodeAction.Info>() { companion object { private val LOG = Logger.getInstance(KotlinGenerateEqualsAndHashcodeAction::class.java) } class Info( val needEquals: Boolean, val needHashCode: Boolean, val classDescriptor: ClassDescriptor, val variablesForEquals: List<VariableDescriptor>, val variablesForHashCode: List<VariableDescriptor> ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { return targetClass is KtClass && targetClass !is KtEnumEntry && !targetClass.isEnum() && !targetClass.isAnnotation() && !targetClass.isInterface() } override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? { if (klass !is KtClass) throw AssertionError("Not a class: ${klass.getElementTextWithContext()}") val context = klass.analyzeWithContent() val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null val equalsDescriptor = classDescriptor.findDeclaredEquals(false) val hashCodeDescriptor = classDescriptor.findDeclaredHashCode(false) var needEquals = equalsDescriptor == null var needHashCode = hashCodeDescriptor == null if (!needEquals && !needHashCode) { if (!confirmMemberRewrite(klass, equalsDescriptor!!, hashCodeDescriptor!!)) return null runWriteAction { try { equalsDescriptor.source.getPsi()?.delete() hashCodeDescriptor.source.getPsi()?.delete() needEquals = true needHashCode = true } catch (e: IncorrectOperationException) { LOG.error(e) } } } val properties = getPropertiesToUseInGeneratedMember(klass) if (properties.isEmpty() || isUnitTestMode()) { val descriptors = properties.map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor } return Info(needEquals, needHashCode, classDescriptor, descriptors, descriptors) } return with(KotlinGenerateEqualsWizard(project, klass, properties, needEquals, needHashCode)) { if (!klass.hasExpectModifier() && !showAndGet()) return null Info(needEquals, needHashCode, classDescriptor, getPropertiesForEquals().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }, getPropertiesForHashCode().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }) } } private fun generateClassLiteralsNotEqual(paramName: String, targetClass: KtClassOrObject): String { val defaultExpression = "javaClass != $paramName?.javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "other == null || this::class.js != $paramName::class.js" targetClass.platform.isCommon() -> "other == null || this::class != $paramName::class" else -> defaultExpression } } private fun generateClassLiteral(targetClass: KtClassOrObject): String { val defaultExpression = "javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "this::class.js" targetClass.platform.isCommon() -> "this::class" else -> defaultExpression } } private fun isNestedArray(variable: VariableDescriptor) = KotlinBuiltIns.isArrayOrPrimitiveArray(variable.builtIns.getArrayElementType(variable.type)) private fun KtElement.canUseArrayContentFunctions() = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_1 private fun generateArraysEqualsCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, arg1: String, arg2: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepEquals" else "contentEquals" "$arg1.$methodName($arg2)" } else { val methodName = if (isNestedArray(variable)) "deepEquals" else "equals" "java.util.Arrays.$methodName($arg1, $arg2)" } } private fun generateArrayHashCodeCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, argument: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepHashCode" else "contentHashCode" val dot = if (TypeUtils.isNullableType(variable.type)) "?." else "." "$argument$dot$methodName()" } else { val methodName = if (isNestedArray(variable)) "deepHashCode" else "hashCode" "java.util.Arrays.$methodName($argument)" } } private fun generateEquals(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { with(info) { if (!needEquals) return null val superEquals = classDescriptor.getSuperClassOrAny().findDeclaredEquals(true)!! val equalsFun = generateFunctionSkeleton(superEquals, targetClass) val paramName = equalsFun.valueParameters.first().name!!.quoteIfNeeded() var typeForCast = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classDescriptor) val typeParams = classDescriptor.declaredTypeParameters if (typeParams.isNotEmpty()) { typeForCast += typeParams.joinToString(prefix = "<", postfix = ">") { "*" } } val useIsCheck = CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER val isNotInstanceCondition = if (useIsCheck) { "$paramName !is $typeForCast" } else { generateClassLiteralsNotEqual(paramName, targetClass) } val bodyText = buildString { append("if (this === $paramName) return true\n") append("if ($isNotInstanceCondition) return false\n") val builtIns = superEquals.builtIns if (!builtIns.isMemberOfAny(superEquals)) { append("if (!super.equals($paramName)) return false\n") } if (variablesForEquals.isNotEmpty()) { if (!useIsCheck) { append("\n$paramName as $typeForCast\n") } append('\n') variablesForEquals.forEach { val isNullable = TypeUtils.isNullableType(it.type) val isArray = KotlinBuiltIns.isArrayOrPrimitiveArray(it.type) val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val propName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) as PsiNameIdentifierOwner).nameIdentifier!!.text val notEquals = when { isArray -> { "!${generateArraysEqualsCall(it, canUseArrayContentFunctions, propName, "$paramName.$propName")}" } else -> { "$propName != $paramName.$propName" } } val equalsCheck = "if ($notEquals) return false\n" if (isArray && isNullable && canUseArrayContentFunctions) { append("if ($propName != null) {\n") append("if ($paramName.$propName == null) return false\n") append(equalsCheck) append("} else if ($paramName.$propName != null) return false\n") } else { append(equalsCheck) } } append('\n') } append("return true") } equalsFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return equalsFun } } private fun generateHashCode(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { fun VariableDescriptor.genVariableHashCode(parenthesesNeeded: Boolean): String { val ref = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, this) as PsiNameIdentifierOwner).nameIdentifier!!.text val isNullable = TypeUtils.isNullableType(type) val builtIns = builtIns val typeClass = type.constructor.declarationDescriptor var text = when { typeClass == builtIns.byte || typeClass == builtIns.short || typeClass == builtIns.int -> ref KotlinBuiltIns.isArrayOrPrimitiveArray(type) -> { val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val shouldWrapInLet = isNullable && !canUseArrayContentFunctions val hashCodeArg = if (shouldWrapInLet) "it" else ref val hashCodeCall = generateArrayHashCodeCall(this, canUseArrayContentFunctions, hashCodeArg) if (shouldWrapInLet) "$ref?.let { $hashCodeCall }" else hashCodeCall } else -> if (isNullable) "$ref?.hashCode()" else "$ref.hashCode()" } if (isNullable) { text += " ?: 0" if (parenthesesNeeded) { text = "($text)" } } return text } with(info) { if (!needHashCode) return null val superHashCode = classDescriptor.getSuperClassOrAny().findDeclaredHashCode(true)!! val hashCodeFun = generateFunctionSkeleton(superHashCode, targetClass) val builtins = superHashCode.builtIns val propertyIterator = variablesForHashCode.iterator() val initialValue = when { !builtins.isMemberOfAny(superHashCode) -> "super.hashCode()" propertyIterator.hasNext() -> propertyIterator.next().genVariableHashCode(false) else -> generateClassLiteral(targetClass) + ".hashCode()" } val bodyText = if (propertyIterator.hasNext()) { val validator = CollectingNameValidator(variablesForEquals.map { it.name.asString().quoteIfNeeded() }) val resultVarName = Fe10KotlinNameSuggester.suggestNameByName("result", validator) StringBuilder().apply { append("var $resultVarName = $initialValue\n") propertyIterator.forEach { append("$resultVarName = 31 * $resultVarName + ${it.genVariableHashCode(true)}\n") } append("return $resultVarName") }.toString() } else "return $initialValue" hashCodeFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return hashCodeFun } } override fun generateMembers(project: Project, editor: Editor?, info: Info): List<KtDeclaration> { val targetClass = info.classDescriptor.source.getPsi() as KtClass val prototypes = ArrayList<KtDeclaration>(2) .apply { addIfNotNull(generateEquals(project, info, targetClass)) addIfNotNull(generateHashCode(project, info, targetClass)) } val anchor = with(targetClass.declarations) { lastIsInstanceOrNull<KtNamedFunction>() ?: lastOrNull() } return insertMembersAfterAndReformat(editor, targetClass, prototypes, anchor) } }
apache-2.0
456ebabfb6ea488c4af3314316ee98bc
45.940994
158
0.644195
5.561074
false
false
false
false
Rin-Da/UCSY-News
app/src/main/java/io/github/rin_da/ucsynews/presentation/post/view/PostView.kt
1
1372
package io.github.rin_da.ucsynews.presentation.post.view import android.content.Context import android.view.View import android.widget.EditText import io.github.rin_da.ucsynews.presentation.abstract.model.Post import io.github.rin_da.ucsynews.presentation.post.activity.PostActivity import io.github.rin_da.ucsynews.presentation.post.presenter.PostPresenter import org.jetbrains.anko.* /** * Created by user on 12/16/16. */ class PostView(var presenter: PostPresenter) : AnkoComponent<PostActivity>, PostBaseView() { override fun success() { context.toast("Success") } override fun failed() { context.toast("Failed") } lateinit var mEdit: EditText lateinit var context: Context override fun createView(ui: AnkoContext<PostActivity>): View { context = ui.ctx presenter.view = this with(ui) { relativeLayout { mEdit = editText { }.lparams(width = matchParent, height = wrapContent) button { onClick { owner.post(Post(title = mEdit.text.toString(), description = mEdit.text.toString())) } }.lparams(width = wrapContent, height = wrapContent) { alignParentBottom() } } } return ui.view } }
mit
a9c5e6a2513d0f21559a25dc7a4a7007
27.604167
108
0.614431
4.543046
false
false
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/local/feed/service/FeedLoadService.kt
1
18776
/* * Copyright 2019 Mauricio Colli <[email protected]> * FeedLoadService.kt is part of NewPipe * * License: GPL-3.0+ * 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 org.schabi.newpipe.local.feed.service import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.ServiceCompat import androidx.preference.PreferenceManager import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Notification import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.functions.Consumer import io.reactivex.rxjava3.functions.Function import io.reactivex.rxjava3.processors.PublishProcessor import io.reactivex.rxjava3.schedulers.Schedulers import org.reactivestreams.Subscriber import org.reactivestreams.Subscription import org.schabi.newpipe.MainActivity.DEBUG import org.schabi.newpipe.R import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.extractor.ListInfo import org.schabi.newpipe.extractor.exceptions.ReCaptchaException import org.schabi.newpipe.extractor.stream.StreamInfoItem import org.schabi.newpipe.local.feed.FeedDatabaseManager import org.schabi.newpipe.local.feed.service.FeedEventManager.Event.ErrorResultEvent import org.schabi.newpipe.local.feed.service.FeedEventManager.Event.ProgressEvent import org.schabi.newpipe.local.feed.service.FeedEventManager.Event.SuccessResultEvent import org.schabi.newpipe.local.feed.service.FeedEventManager.postEvent import org.schabi.newpipe.local.subscription.SubscriptionManager import org.schabi.newpipe.util.ExceptionUtils import org.schabi.newpipe.util.ExtractorHelper import java.io.IOException import java.time.OffsetDateTime import java.time.ZoneOffset import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger class FeedLoadService : Service() { companion object { private val TAG = FeedLoadService::class.java.simpleName private const val NOTIFICATION_ID = 7293450 private const val ACTION_CANCEL = "org.schabi.newpipe.local.feed.service.FeedLoadService.CANCEL" /** * How often the notification will be updated. */ private const val NOTIFICATION_SAMPLING_PERIOD = 1500 /** * How many extractions will be running in parallel. */ private const val PARALLEL_EXTRACTIONS = 6 /** * Number of items to buffer to mass-insert in the database. */ private const val BUFFER_COUNT_BEFORE_INSERT = 20 const val EXTRA_GROUP_ID: String = "FeedLoadService.EXTRA_GROUP_ID" } private var loadingSubscription: Subscription? = null private lateinit var subscriptionManager: SubscriptionManager private lateinit var feedDatabaseManager: FeedDatabaseManager private lateinit var feedResultsHolder: ResultsHolder private var disposables = CompositeDisposable() private var notificationUpdater = PublishProcessor.create<String>() // ///////////////////////////////////////////////////////////////////////// // Lifecycle // ///////////////////////////////////////////////////////////////////////// override fun onCreate() { super.onCreate() subscriptionManager = SubscriptionManager(this) feedDatabaseManager = FeedDatabaseManager(this) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (DEBUG) { Log.d( TAG, "onStartCommand() called with: intent = [" + intent + "]," + " flags = [" + flags + "], startId = [" + startId + "]" ) } if (intent == null || loadingSubscription != null) { return START_NOT_STICKY } setupNotification() setupBroadcastReceiver() val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) val groupId = intent.getLongExtra(EXTRA_GROUP_ID, FeedGroupEntity.GROUP_ALL_ID) val useFeedExtractor = defaultSharedPreferences .getBoolean(getString(R.string.feed_use_dedicated_fetch_method_key), false) val thresholdOutdatedSecondsString = defaultSharedPreferences .getString(getString(R.string.feed_update_threshold_key), getString(R.string.feed_update_threshold_default_value)) val thresholdOutdatedSeconds = thresholdOutdatedSecondsString!!.toInt() startLoading(groupId, useFeedExtractor, thresholdOutdatedSeconds) return START_NOT_STICKY } private fun disposeAll() { unregisterReceiver(broadcastReceiver) loadingSubscription?.cancel() loadingSubscription = null disposables.dispose() } private fun stopService() { disposeAll() ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) notificationManager.cancel(NOTIFICATION_ID) stopSelf() } override fun onBind(intent: Intent): IBinder? { return null } // ///////////////////////////////////////////////////////////////////////// // Loading & Handling // ///////////////////////////////////////////////////////////////////////// private class RequestException(val subscriptionId: Long, message: String, cause: Throwable) : Exception(message, cause) { companion object { fun wrapList(subscriptionId: Long, info: ListInfo<StreamInfoItem>): List<Throwable> { val toReturn = ArrayList<Throwable>(info.errors.size) info.errors.mapTo(toReturn) { RequestException(subscriptionId, info.serviceId.toString() + ":" + info.url, it) } return toReturn } } } private fun startLoading(groupId: Long = FeedGroupEntity.GROUP_ALL_ID, useFeedExtractor: Boolean, thresholdOutdatedSeconds: Int) { feedResultsHolder = ResultsHolder() val outdatedThreshold = OffsetDateTime.now(ZoneOffset.UTC).minusSeconds(thresholdOutdatedSeconds.toLong()) val subscriptions = when (groupId) { FeedGroupEntity.GROUP_ALL_ID -> feedDatabaseManager.outdatedSubscriptions(outdatedThreshold) else -> feedDatabaseManager.outdatedSubscriptionsForGroup(groupId, outdatedThreshold) } subscriptions .take(1) .doOnNext { currentProgress.set(0) maxProgress.set(it.size) } .filter { it.isNotEmpty() } .observeOn(AndroidSchedulers.mainThread()) .doOnNext { startForeground(NOTIFICATION_ID, notificationBuilder.build()) updateNotificationProgress(null) broadcastProgress() } .observeOn(Schedulers.io()) .flatMap { Flowable.fromIterable(it) } .takeWhile { !cancelSignal.get() } .parallel(PARALLEL_EXTRACTIONS, PARALLEL_EXTRACTIONS * 2) .runOn(Schedulers.io(), PARALLEL_EXTRACTIONS * 2) .filter { !cancelSignal.get() } .map { subscriptionEntity -> try { val listInfo = if (useFeedExtractor) { ExtractorHelper .getFeedInfoFallbackToChannelInfo(subscriptionEntity.serviceId, subscriptionEntity.url) .blockingGet() } else { ExtractorHelper .getChannelInfo(subscriptionEntity.serviceId, subscriptionEntity.url, true) .blockingGet() } as ListInfo<StreamInfoItem> return@map Notification.createOnNext(Pair(subscriptionEntity.uid, listInfo)) } catch (e: Throwable) { val request = "${subscriptionEntity.serviceId}:${subscriptionEntity.url}" val wrapper = RequestException(subscriptionEntity.uid, request, e) return@map Notification.createOnError<Pair<Long, ListInfo<StreamInfoItem>>>(wrapper) } } .sequential() .observeOn(AndroidSchedulers.mainThread()) .doOnNext(errorHandlingConsumer) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(notificationsConsumer) .observeOn(Schedulers.io()) .buffer(BUFFER_COUNT_BEFORE_INSERT) .doOnNext(databaseConsumer) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resultSubscriber) } private fun broadcastProgress() { postEvent(ProgressEvent(currentProgress.get(), maxProgress.get())) } private val resultSubscriber get() = object : Subscriber<List<Notification<Pair<Long, ListInfo<StreamInfoItem>>>>> { override fun onSubscribe(s: Subscription) { loadingSubscription = s s.request(java.lang.Long.MAX_VALUE) } override fun onNext(notification: List<Notification<Pair<Long, ListInfo<StreamInfoItem>>>>) { if (DEBUG) Log.v(TAG, "onNext() → $notification") } override fun onError(error: Throwable) { handleError(error) } override fun onComplete() { if (maxProgress.get() == 0) { postEvent(FeedEventManager.Event.IdleEvent) stopService() return } currentProgress.set(-1) maxProgress.set(-1) notificationUpdater.onNext(getString(R.string.feed_processing_message)) postEvent(ProgressEvent(R.string.feed_processing_message)) disposables.add( Single .fromCallable { feedResultsHolder.ready() postEvent(ProgressEvent(R.string.feed_processing_message)) feedDatabaseManager.removeOrphansOrOlderStreams() postEvent(SuccessResultEvent(feedResultsHolder.itemsErrors)) true } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { _, throwable -> if (throwable != null) { Log.e(TAG, "Error while storing result", throwable) handleError(throwable) return@subscribe } stopService() } ) } } private val databaseConsumer: Consumer<List<Notification<Pair<Long, ListInfo<StreamInfoItem>>>>> get() = Consumer { feedDatabaseManager.database().runInTransaction { for (notification in it) { if (notification.isOnNext) { val subscriptionId = notification.value!!.first val info = notification.value!!.second feedDatabaseManager.upsertAll(subscriptionId, info.relatedItems) subscriptionManager.updateFromInfo(subscriptionId, info) if (info.errors.isNotEmpty()) { feedResultsHolder.addErrors(RequestException.wrapList(subscriptionId, info)) feedDatabaseManager.markAsOutdated(subscriptionId) } } else if (notification.isOnError) { val error = notification.error!! feedResultsHolder.addError(error) if (error is RequestException) { feedDatabaseManager.markAsOutdated(error.subscriptionId) } } } } } private val errorHandlingConsumer: Consumer<Notification<Pair<Long, ListInfo<StreamInfoItem>>>> get() = Consumer { if (it.isOnError) { var error = it.error!! if (error is RequestException) error = error.cause!! val cause = error.cause when { error is ReCaptchaException -> throw error cause is ReCaptchaException -> throw cause error is IOException -> throw error cause is IOException -> throw cause ExceptionUtils.isNetworkRelated(error) -> throw IOException(error) } } } private val notificationsConsumer: Consumer<Notification<Pair<Long, ListInfo<StreamInfoItem>>>> get() = Consumer { onItemCompleted(it.value?.second?.name) } private fun onItemCompleted(updateDescription: String?) { currentProgress.incrementAndGet() notificationUpdater.onNext(updateDescription ?: "") broadcastProgress() } // ///////////////////////////////////////////////////////////////////////// // Notification // ///////////////////////////////////////////////////////////////////////// private lateinit var notificationManager: NotificationManagerCompat private lateinit var notificationBuilder: NotificationCompat.Builder private var currentProgress = AtomicInteger(-1) private var maxProgress = AtomicInteger(-1) private fun createNotification(): NotificationCompat.Builder { val cancelActionIntent = PendingIntent.getBroadcast( this, NOTIFICATION_ID, Intent(ACTION_CANCEL), 0 ) return NotificationCompat.Builder(this, getString(R.string.notification_channel_id)) .setOngoing(true) .setProgress(-1, -1, true) .setSmallIcon(R.drawable.ic_newpipe_triangle_white) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .addAction(0, getString(R.string.cancel), cancelActionIntent) .setContentTitle(getString(R.string.feed_notification_loading)) } private fun setupNotification() { notificationManager = NotificationManagerCompat.from(this) notificationBuilder = createNotification() val throttleAfterFirstEmission = Function { flow: Flowable<String> -> flow.take(1).concatWith(flow.skip(1).throttleLatest(NOTIFICATION_SAMPLING_PERIOD.toLong(), TimeUnit.MILLISECONDS)) } disposables.add( notificationUpdater .publish(throttleAfterFirstEmission) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::updateNotificationProgress) ) } private fun updateNotificationProgress(updateDescription: String?) { notificationBuilder.setProgress(maxProgress.get(), currentProgress.get(), maxProgress.get() == -1) if (maxProgress.get() == -1) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) notificationBuilder.setContentInfo(null) if (!updateDescription.isNullOrEmpty()) notificationBuilder.setContentText(updateDescription) notificationBuilder.setContentText(updateDescription) } else { val progressText = this.currentProgress.toString() + "/" + maxProgress if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (!updateDescription.isNullOrEmpty()) notificationBuilder.setContentText("$updateDescription ($progressText)") } else { notificationBuilder.setContentInfo(progressText) if (!updateDescription.isNullOrEmpty()) notificationBuilder.setContentText(updateDescription) } } notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()) } // ///////////////////////////////////////////////////////////////////////// // Notification Actions // ///////////////////////////////////////////////////////////////////////// private lateinit var broadcastReceiver: BroadcastReceiver private val cancelSignal = AtomicBoolean() private fun setupBroadcastReceiver() { broadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == ACTION_CANCEL) { cancelSignal.set(true) } } } registerReceiver(broadcastReceiver, IntentFilter(ACTION_CANCEL)) } // ///////////////////////////////////////////////////////////////////////// // Error handling // ///////////////////////////////////////////////////////////////////////// private fun handleError(error: Throwable) { postEvent(ErrorResultEvent(error)) stopService() } // ///////////////////////////////////////////////////////////////////////// // Results Holder // ///////////////////////////////////////////////////////////////////////// class ResultsHolder { /** * List of errors that may have happen during loading. */ internal lateinit var itemsErrors: List<Throwable> private val itemsErrorsHolder: MutableList<Throwable> = ArrayList() fun addError(error: Throwable) { itemsErrorsHolder.add(error) } fun addErrors(errors: List<Throwable>) { itemsErrorsHolder.addAll(errors) } fun ready() { itemsErrors = itemsErrorsHolder.toList() } } }
gpl-3.0
3296540e68eccf0c387547e6caa6b5d9
38.607595
134
0.599446
5.554438
false
false
false
false
akakim/akakim.github.io
Android/KotlinRepository/QSalesPrototypeKotilnVersion/main/java/tripath/com/samplekapp/widget/MovieView.kt
1
13275
package tripath.com.samplekapp.widget import android.content.Context import android.graphics.Color import android.media.MediaPlayer import android.os.Handler import android.os.Message import android.support.annotation.RawRes import android.transition.TransitionManager import android.util.AttributeSet import android.util.Log import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import android.widget.ImageButton import android.widget.RelativeLayout import tripath.com.samplekapp.R import java.lang.ref.WeakReference /** * let 절이 쓰이게 된다면 어떤 변수다 라는걸 표시안하고 그그냥 변수명만 쓰면 자기 * 자신을 가리키는거같다. */ class MovieView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context,attrs,defStyleAttr){ companion object { private val TAG = "MovieView" private val FAST_FORWARD_REWIND_INTERVAL = 5000 // ms // the amount of time until we fade out the control private val TIMEOUT_CONTROLS = 3000L // ms } // 자신의 상태의 변화를 알 수있는 콜백 // monitors all event relate to movieView abstract class MovieListener{ // call when the video is stated or resumed open fun onMoviewStarted(){} // called when the video is paused or finished open fun onMoviewStopped(){} // called when this view should be minimized open fun onMovieMinimized(){} } // shows the video playback private val surfaceView : SurfaceView // Controls private val toggleBtn : ImageButton private val shade : View private val fastForward : ImageButton private val fastRewind : ImageButton private val minimize : ImageButton // the plays the video. this will be null when no video is set internal var mediaPlayer: MediaPlayer? = null /** The resource ID for the video to play. */ @RawRes private var videoResourceId: Int = 0 /** Whether we adjust our view bounds or we fill the remaining area with black bars */ private var adjustViewBounds: Boolean = false /** Handles timeout for media controls. */ private var timeoutHandler: TimeoutHandler? = null /** The listener for all the events we publish. */ internal var movieListener: MovieListener? = null private var savedCurrentPosition: Int = 0 init { setBackgroundColor( Color.BLACK ) // inflate the content View.inflate(context, R.layout.view_movie, this) surfaceView = findViewById <SurfaceView> (R.id.surface) shade = findViewById <View> (R.id.shade) toggleBtn = findViewById <ImageButton> (R.id.toggle) fastForward = findViewById <ImageButton> (R.id.fast_forward) fastRewind = findViewById <ImageButton> (R.id.fast_rewind) minimize = findViewById <ImageButton> (R.id.minimize) // attributes... val a = context.obtainStyledAttributes(attrs,R.styleable.MovieView, defStyleAttr,R.style.Widget_PictureInPicture_MovieView ) setVideoResourceId( a.getResourceId(R.styleable.MovieView_android_src, 0)) setAdjustViewBounds( a.getBoolean( R.styleable.MovieView_android_adjustViewBounds,false)) a.recycle() val listener = View.OnClickListener { view -> when (view.id){ R.id.surface -> toggleControls() R.id.toggle -> toggle() R.id.fast_forward -> fastForwardFun() R.id.fast_rewind -> fastRewind() R.id.minimize -> movieListener?.onMovieMinimized() } // TODO : 뭘까 이부분은 . // Start or reset the timeout to hide controls mediaPlayer?.let { player -> if (timeoutHandler == null) { timeoutHandler = TimeoutHandler(this@MovieView) } timeoutHandler?.let { handler -> handler.removeMessages(TimeoutHandler.MESSAGE_HIDE_CONTROLS) if (player.isPlaying) { handler.sendEmptyMessageDelayed(TimeoutHandler.MESSAGE_HIDE_CONTROLS, TIMEOUT_CONTROLS) } } } } surfaceView.setOnClickListener( listener ) shade.setOnClickListener( listener ) toggleBtn.setOnClickListener( listener ) fastForward.setOnClickListener( listener ) fastRewind.setOnClickListener( listener ) minimize.setOnClickListener( listener ) // prepare surfaceView.holder.addCallback( object : SurfaceHolder.Callback { override fun surfaceChanged(p0: SurfaceHolder?, p1: Int, p2: Int, p3: Int) { } override fun surfaceDestroyed(p0: SurfaceHolder?) { mediaPlayer?.let{ savedCurrentPosition = it.currentPosition closeVideo() } } override fun surfaceCreated(holder: SurfaceHolder) { openVideo(holder.surface) } }) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { mediaPlayer?.let { player-> val videoWidth = player.videoWidth val videoHeight = player.videoHeight if (videoWidth != 0 && videoHeight != 0) { val aspectRatio = videoHeight.toFloat() / videoWidth val width = View.MeasureSpec.getSize(widthMeasureSpec) val widthMode = View.MeasureSpec.getMode(widthMeasureSpec) val height = View.MeasureSpec.getSize(heightMeasureSpec) val heightMode = View.MeasureSpec.getMode(heightMeasureSpec) if( adjustViewBounds ){ /** * 가로 사이즈는 정해져있는데 높이는 정해지지 않는경우 * 가로의비율에 맞춰서 높이를 설정한다. */ if( widthMode == View.MeasureSpec.EXACTLY && heightMode != View.MeasureSpec.EXACTLY){ super.onMeasure( widthMeasureSpec , View.MeasureSpec.makeMeasureSpec( (width * aspectRatio).toInt(),View.MeasureSpec.EXACTLY )) } /** * 높이가 정확한경우 가로를 높이의 비율에 맞춘다. */ else if (widthMode != View.MeasureSpec.EXACTLY && heightMode == View.MeasureSpec.EXACTLY) { super.onMeasure(View.MeasureSpec.makeMeasureSpec((height / aspectRatio).toInt(), View.MeasureSpec.EXACTLY), heightMeasureSpec) } else { super.onMeasure( widthMeasureSpec , View.MeasureSpec.makeMeasureSpec( (width * aspectRatio).toInt(),View.MeasureSpec.EXACTLY )) } }else { val viewRatio = height.toFloat() / width if (aspectRatio > viewRatio) { val padding = ((width - height / aspectRatio) / 2).toInt() setPadding(padding, 0, padding, 0) } else { val padding = ((height - width * aspectRatio) / 2).toInt() setPadding(0, padding, 0, padding) } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } return } } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onDetachedFromWindow() { timeoutHandler?.removeMessages ( TimeoutHandler.MESSAGE_HIDE_CONTROLS ) timeoutHandler = null super.onDetachedFromWindow() } val isPlaying : Boolean get() = mediaPlayer?.isPlaying?:false /** * Sets the listener to monitor movie events. * @param movieListener The listener to be set. */ fun setMovieListener(movieListener: MovieListener?) { this.movieListener = movieListener } fun setVideoResourceId(@RawRes id: Int){ if( id == videoResourceId ){ return } videoResourceId = id val surface = surfaceView.holder.surface if( surface != null && surface.isValid ){ closeVideo() openVideo(surface) } } fun setAdjustViewBounds( adjustViewBound : Boolean ){ if( adjustViewBounds == adjustViewBound ){ return } adjustViewBounds = adjustViewBound if( adjustViewBound ){ background = null }else { setBackgroundColor( Color.BLACK ) } requestLayout() } /** * player를 메모리에서 해체한다. */ internal fun closeVideo(){ mediaPlayer?.release() mediaPlayer = null } internal fun openVideo(surface : Surface){ if( videoResourceId == 0){ return } mediaPlayer = MediaPlayer() mediaPlayer?.let { player -> player.setSurface( surface ) try{ resources.openRawResource( videoResourceId ).use { fd -> // player.setDataSource( fd ) player.setOnPreparedListener { mediaPlayer -> //adjust aspect ratio of this view requestLayout() if( savedCurrentPosition > 0 ){ mediaPlayer.seekTo( savedCurrentPosition ) savedCurrentPosition = 0 }else { play() } } } }catch ( e : Exception){ Log.e(TAG,"Failed to open Video",e) } } } /** * 정지하느냐 재생하느냐 */ internal fun toggle(){ mediaPlayer?.let{ if( it.isPlaying ) pause() else play() } } /** * 제어 버튼들을 보여주거나 안보여주거나 */ internal fun toggleControls(){ if( shade.visibility == View.VISIBLE ){ hideControls() }else { showControls() } } /** * 동영상 시작 */ fun play(){ if( mediaPlayer == null){ return } mediaPlayer!!.start() } /** * 되감기 */ fun fastRewind(){ mediaPlayer?.let { it.seekTo(it.currentPosition - FAST_FORWARD_REWIND_INTERVAL) } } /** * 뒤로가기 */ fun fastForwardFun(){ mediaPlayer?.let { it.seekTo( it.currentPosition - FAST_FORWARD_REWIND_INTERVAL) } } /** * 동영상 정지 */ fun pause(){ if( mediaPlayer == null ){ adjustToggleState() return } mediaPlayer!!.pause() keepScreenOn = false movieListener?.onMoviewStopped() } /** * 컨트롤버튼 숨김 */ fun hideControls(){ TransitionManager.beginDelayedTransition(this) // TODO: visibility 조정. shade.visibility = View.INVISIBLE toggleBtn.visibility = View.INVISIBLE fastForward.visibility = View.INVISIBLE fastRewind.visibility = View.INVISIBLE minimize.visibility = View.INVISIBLE } /** * 컨트롤 버튼 보여줌 */ fun showControls(){ TransitionManager.beginDelayedTransition(this) // TODO: visibility 조정. shade.visibility = View.VISIBLE toggleBtn.visibility = View.VISIBLE fastForward.visibility = View.VISIBLE fastRewind.visibility = View.VISIBLE minimize.visibility = View.VISIBLE } /** * 재생중이냐 일시정지중이냐에 따른 이미지 버튼 교체 */ internal fun adjustToggleState(){ mediaPlayer?.let{ if( it.isPlaying ){ toggleBtn.contentDescription = resources.getString( R.string.pause ) toggleBtn.setImageResource( R.drawable.ic_pause_64dp) } else { toggleBtn.contentDescription = resources.getString( R.string.play ) toggleBtn.setImageResource( R.drawable.ic_play_arrow_64dp ) } } } // 타임아웃 정책에 대한 클래스 . private class TimeoutHandler(view: MovieView): Handler(){ private val mMovieViewRef : WeakReference<MovieView> = WeakReference(view) override fun handleMessage(msg: Message){ when (msg.what){ MESSAGE_HIDE_CONTROLS ->{ mMovieViewRef.get()?.hideControls() } else ->super.handleMessage(msg) } } companion object { internal val MESSAGE_HIDE_CONTROLS = 1 } } }
gpl-3.0
bd93bd78ee5b2117eb0dbb7c2f0e1a90
28.878788
151
0.559803
4.829314
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt
4
1986
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import org.jetbrains.kotlin.types.typeUtil.isUnit fun KtExpression.shouldHaveNotNullType(): Boolean { val type = when (val parent = parent) { is KtBinaryExpression -> parent.left?.let { it.getType(it.analyze()) } is KtProperty -> parent.typeReference?.let { it.analyze()[BindingContext.TYPE, it] } is KtReturnExpression -> parent.getTargetFunctionDescriptor(analyze())?.returnType is KtValueArgument -> { val call = parent.getStrictParentOfType<KtCallExpression>()?.resolveToCall() (call?.getArgumentMapping(parent) as? ArgumentMatch)?.valueParameter?.type } is KtBlockExpression -> { if (parent.statements.lastOrNull() != this) return false val functionLiteral = parent.parent as? KtFunctionLiteral ?: return false if (functionLiteral.parent !is KtLambdaExpression) return false functionLiteral.analyze()[BindingContext.FUNCTION, functionLiteral]?.returnType } else -> null } ?: return false return !type.isMarkedNullable && !type.isUnit() && !type.isTypeParameter() }
apache-2.0
3799b5f73abc1112f3c65cd59c0924b7
52.675676
158
0.752769
4.820388
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/data/Playlist.kt
1
909
package com.kelsos.mbrc.data import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonPropertyOrder import com.kelsos.mbrc.data.db.RemoteDatabase import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder("name", "url") @Table(database = RemoteDatabase::class, name = "playlists") data class Playlist( @Column(name = "name") @JsonProperty var name: String = "", @Column(name = "url") @JsonProperty var url: String = "", @JsonIgnore @Column(name="date_added") var dateAdded: Long = 0, @Column(name = "id") @PrimaryKey(autoincrement = true) @JsonIgnore var id: Long = 0 ) : Data
gpl-3.0
eb8eed960dbf363d5c9fb5365d02417e
32.666667
60
0.771177
3.819328
false
false
false
false
mikehearn/httpseed
src/main/kotlin/crawler.kt
2
19453
/* * Copyright by the original author or 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.bitcoinj.httpseed import com.google.common.io.BaseEncoding import com.google.common.primitives.UnsignedBytes import net.jcip.annotations.GuardedBy import org.bitcoinj.core.AddressMessage import org.bitcoinj.core.BlockChain import org.bitcoinj.core.Coin import org.bitcoinj.core.Message import org.bitcoinj.core.NetworkParameters import org.bitcoinj.core.Peer import org.bitcoinj.core.PeerAddress import org.bitcoinj.core.PeerGroup import org.bitcoinj.core.Sha256Hash import org.bitcoinj.core.TransactionOutPoint import org.bitcoinj.core.TransactionOutput import org.bitcoinj.core.Utils import org.bitcoinj.core.VersionMessage import org.bitcoinj.core.listeners.DownloadProgressTracker import org.bitcoinj.core.listeners.PreMessageReceivedEventListener import org.bitcoinj.net.NioClientManager import org.bitcoinj.net.discovery.DnsDiscovery import org.bitcoinj.params.MainNetParams import org.bitcoinj.params.TestNet3Params import org.bitcoinj.script.ScriptPattern import org.bitcoinj.store.MemoryBlockStore import org.bitcoinj.utils.Threading import org.mapdb.DBMaker import org.mapdb.DataInput2 import org.mapdb.DataOutput2 import org.mapdb.Serializer import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.Serializable import java.net.Inet4Address import java.net.InetAddress import java.net.InetSocketAddress import java.nio.file.Path import java.time.Duration import java.time.Instant import java.util.Arrays import java.util.Collections import java.util.Date import java.util.LinkedList import java.util.Locale import java.util.concurrent.ConcurrentMap import java.util.concurrent.DelayQueue import java.util.concurrent.Delayed import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import kotlin.concurrent.thread enum class PeerStatus { UNTESTED, UNREACHABLE, BEHIND, // Not caught up with the block chain OK } data class PeerData(val status: PeerStatus, val serviceBits: Long, val lastCrawlTime: Instant, val lastSuccessTime: Instant? = null, val supportsGetUTXO: Boolean = false) : Serializable { fun isTimeToRecrawl(recrawlMinutes: Long): Boolean { val ago = Instant.now().minusSeconds(recrawlMinutes * 60) return this.lastCrawlTime.isBefore(ago) } // We recrawl nodes that are currently up to check they're still alive, or nodes which *were* up within the last day // but have disappeared to see if they come back, or nodes that were behind when we last checked them. fun shouldRecrawl() = when (status) { PeerStatus.OK, PeerStatus.BEHIND, PeerStatus.UNTESTED -> true PeerStatus.UNREACHABLE -> lastSuccessTime != null && lastSuccessTime.isAfter(Instant.now() - Duration.ofDays(1)) } } private class PeerDataSerializer : Serializer<PeerData> { override fun serialize(out: DataOutput2, value: PeerData) { out.writeUTF(value.status.name) out.writeLong(value.serviceBits) out.writeLong(value.lastCrawlTime.toEpochMilli()) out.writeLong(value.lastSuccessTime?.toEpochMilli() ?: 0L) out.writeBoolean(value.supportsGetUTXO) } override fun deserialize(input: DataInput2, available: Int): PeerData { val status = PeerStatus.valueOf(input.readUTF()) val serviceBits = input.readLong() val lastCrawlTime = Instant.ofEpochMilli(input.readLong()) val lastSuccessTimeLong = input.readLong(); val lastSuccessTime = if (lastSuccessTimeLong == 0L) null else Instant.ofEpochMilli(lastSuccessTimeLong) val supportsGetUTXO = input.readBoolean() return PeerData(status, serviceBits, lastCrawlTime, lastSuccessTime, supportsGetUTXO) } } // Crawler engine class Crawler(private val workingDir: Path, public val params: NetworkParameters, private val hostname: String) { private val log: Logger = LoggerFactory.getLogger("cartographer.engine") private val blockStore = MemoryBlockStore(params) private val blockChain = BlockChain(params, blockStore) private val peerGroup = PeerGroup(params, blockChain) private val db = DBMaker.fileDB(workingDir.resolve("httpseed-db").toFile()).make() public val addrMap: ConcurrentMap<InetSocketAddress, PeerData> = db.hashMap("addrToStatus").valueSerializer(PeerDataSerializer()).createOrOpen() as ConcurrentMap<InetSocketAddress, PeerData> @GuardedBy("this") private val okPeers: LinkedList<InetSocketAddress> = LinkedList() private val connecting: MutableSet<InetSocketAddress> = Collections.synchronizedSet(HashSet()) private val ccm = NioClientManager() private val verMsg: VersionMessage = VersionMessage(params, -1) // Rate limiting private var openConnections = 0 private val maxConnections = 200 data class LightweightAddress(public val addr: ByteArray, public val port: Short) { fun toInetSocketAddress() = InetSocketAddress(InetAddress.getByAddress(addr), port.toInt()) } fun InetSocketAddress.toLightweight() = LightweightAddress(this.address.address, this.port.toShort()) private val addressQueue = HashSet<LightweightAddress>() private val recrawlMinutes = 30L // Recrawl queue inner class PendingRecrawl(val addr: InetSocketAddress) : Delayed { private fun nowSeconds() = (System.currentTimeMillis() / 1000).toInt() private val creationTime = nowSeconds() override fun compareTo(other: Delayed?): Int = creationTime.compareTo((other as PendingRecrawl).creationTime) override fun getDelay(unit: TimeUnit): Long = unit.convert(creationTime + (recrawlMinutes * 60) - nowSeconds(), TimeUnit.SECONDS) fun delayAsString() = Duration.ofSeconds(getDelay(TimeUnit.SECONDS)).toString().substring(2).replace("M", " minutes ").replace("S", " seconds") override fun toString() = "${addr.toString().substring(1)} in ${delayAsString()}" } private val recrawlQueue = DelayQueue<PendingRecrawl>() public fun snapshotRecrawlQueue(): Iterator<PendingRecrawl> = recrawlQueue.iterator() // Snapshots internally public fun start() { loadFromDB() val VERSION = "1.2" val PRODUCT_NAME = "HTTPSeed" verMsg.appendToSubVer(PRODUCT_NAME, VERSION, hostname) // We use the low level networking API to crawl, because PeerGroup does things like backoff/retry/etc which we don't want. log.info("Starting crawl network manager") ccm.startAsync().awaitRunning() // We use a regular PeerGroup setup to learn about the state of the network but not to crawl it. log.info("Starting peer group ...") peerGroup.setFastCatchupTimeSecs(Instant.now().epochSecond) peerGroup.setUserAgent(PRODUCT_NAME, VERSION, hostname) peerGroup.setMaxConnections(12) peerGroup.addPeerDiscovery(DnsDiscovery(params)) peerGroup.start() log.info("Waiting for peers to connect ...") peerGroup.waitForPeers(8).get(30, TimeUnit.SECONDS); log.info("Waiting for block chain headers to sync ...") val listener = object : DownloadProgressTracker() { override fun progress(pct: Double, blocksSoFar: Int, date: Date?) { log.info(String.format(Locale.US, "Chain download %d%% done with %d blocks to go, block date %s", pct.toInt(), blocksSoFar, Utils.dateTimeFormat(date))) } } peerGroup.startBlockChainDownload(listener) listener.await() log.info("Chain synced, querying initial addresses") val peer = peerGroup.waitForPeers(1).get()[0] // When we receive an addr broadcast from our long-term network connections, queue up the addresses for crawling. peerGroup.addPreMessageReceivedEventListener(Threading.SAME_THREAD, object : PreMessageReceivedEventListener { override fun onPreMessageReceived(peer: Peer, m: Message): Message { if (m is AddressMessage) { Threading.USER_THREAD.execute { val sockaddrs = m.addresses.map { it.socketAddress } val fresh = sockaddrs.filterNot { addrMap.containsKey(it) or addressQueue.contains(it.toLightweight()) } if (fresh.isNotEmpty()) { log.info("Got ${fresh.size} new address(es) from $peer" + if (fresh.size < 10) ": " + fresh.joinToString(",") else "") queueAddrs(fresh) crawl() } } } return m } }) if (okPeers.isEmpty()) { // First run: request some addresses. Response will be handled by the event listener above. peer.addr } else { // Pick some peers that were considered OK on the last run and recrawl them immediately to kick things off again. log.info("Kicking off crawl with some peers from previous run") Threading.USER_THREAD.execute() { okPeers.take(20).forEach { attemptConnect(it) } } } thread(name = "Recrawl thread") { while (true) { queueAndCrawl(recrawlQueue.take().addr) } } } fun stop() { log.info("Stopping ...") peerGroup.stop() db.close() } fun crawl() { while (openConnections < maxConnections) { val lightAddr: LightweightAddress? = addressQueue.firstOrNull() if (lightAddr == null) break addressQueue.remove(lightAddr) // Some addr messages have bogus port values in them; ignore. if (lightAddr.port == 0.toShort()) continue val addr = lightAddr.toInetSocketAddress() if (connecting.contains(addr)) continue val data = addrMap[addr] var doConnect = if (data == null) { // Not seen this address before and not already probing it addrMap[addr] = PeerData(PeerStatus.UNTESTED, 0, Instant.now()) db.commit() true } else { data.shouldRecrawl() && data.isTimeToRecrawl(recrawlMinutes) } if (doConnect) attemptConnect(addr) } } private fun markAs(addr: InetSocketAddress, status: PeerStatus): PeerStatus { val cur = addrMap[addr]!! addrMap[addr] = cur.copy(status = status, lastCrawlTime = Instant.now()) db.commit() synchronized(this) { okPeers.remove(addr) } return cur.status } private fun markAsOK(addr: InetSocketAddress, peer: Peer) { val peerData: PeerData? = addrMap[addr] val oldStatus = peerData?.status if (oldStatus == PeerStatus.UNREACHABLE && peerData.lastSuccessTime != null) log.info("Peer $addr came back from the dead") var newData = PeerData( status = PeerStatus.OK, lastCrawlTime = Instant.now(), serviceBits = peer.peerVersionMessage.localServices, lastSuccessTime = Instant.now() ) addrMap[addr] = newData db.commit() // We might have recrawled an OK peer if forced via JMX. if (oldStatus != PeerStatus.OK) { synchronized(this) { okPeers.add(addr) } } } fun attemptConnect(addr: InetSocketAddress) { connecting.add(addr) val peer = Peer(params, verMsg, null, PeerAddress(params, addr)) peer.versionHandshakeFuture later { p -> onConnect(addr, p) } // Possibly pause a moment to stay within our connects/sec budget. openConnections++ ccm.openConnection(addr, peer) later { sockaddr, error -> if (error != null) { connecting.remove(sockaddr!! as InetSocketAddress) if (markAs(addr, PeerStatus.UNREACHABLE) == PeerStatus.OK) { // Was previously OK, now gone. log.info("Peer $addr has disappeared: will keep retrying for 24 hours") scheduleRecrawl(addr) } onDisconnected() } } } private fun queueAddrs(addr: AddressMessage) { queueAddrs(addr.addresses.filter { isPeerAddressRoutable(it) }.map { it.toSocketAddress() }) } private fun queueAddrs(sockaddrs: List<InetSocketAddress>) { addressQueue.addAll(sockaddrs.map { // If we found a peer on the same machine as the cartographer, look up our own hostname to find the public IP // instead of publishing localhost. if (it.address.isAnyLocalAddress || it.address.isLoopbackAddress) { val rs = InetSocketAddress(hostname, it.port) log.info("Replacing $it with $rs") rs.toLightweight() } else { it.toLightweight() } }) } private fun isPeerAddressRoutable(peerAddress: PeerAddress): Boolean { val address = peerAddress.addr if (address is Inet4Address) { val a0 = UnsignedBytes.toInt(address.address[0]) if (a0 >= 240) // Reserved for future use return false } return true } private fun onConnect(sockaddr: InetSocketAddress, peer: Peer) { connecting.remove(sockaddr) val heightDiff = blockChain.bestChainHeight - peer.bestHeight if (heightDiff > 6) { log.warn("Peer $peer is behind our block chain by $heightDiff blocks") markAs(sockaddr, PeerStatus.BEHIND) } else { markAsOK(sockaddr, peer) } // Check up on it again in future to make sure it's still OK/has become OK. scheduleRecrawl(sockaddr) peer.addr later { addr -> queueAddrs(addr) if (peer.peerVersionMessage.isGetUTXOsSupported) { // Check if it really is, to catch peers that are using the service bit for something else. testGetUTXOSupport(peer, sockaddr) } peer.close() onDisconnected() } } private fun testGetUTXOSupport(peer: Peer, sockaddr: InetSocketAddress) { try { var txhash: Sha256Hash = Sha256Hash.ZERO_HASH var outcheck: (TransactionOutput) -> Boolean = { false } var height = 0L if (params == TestNet3Params.get()) { txhash = Sha256Hash.wrap("1c899ae8efd6bd460e517195dc34d2beeca9c5e76ff98af644cf6a28807f86cf") outcheck = { it.value == Coin.parseCoin("0.00001") && ScriptPattern.isP2PKH(it.scriptPubKey) && it.scriptPubKey.getToAddress(params).toString() == "mydzGfTrtHx8KnCRu43HfKwYyKjjSo6gUB" } height = 314941 } else if (params == MainNetParams.get()) { // For now just assume Satoshi never spends the first block ever mined. There are much // more sophisticated and randomized tests possible, but currently we only check for mistakes and // not deliberately malicious peers that try to cheat this check. txhash = Sha256Hash.wrap("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098") val pubkey = "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee" outcheck = { it.value == Coin.FIFTY_COINS && ScriptPattern.isP2PK(it.scriptPubKey) && // KT-6587 means we cannot use == as you would expect here. Arrays.equals(it.scriptPubKey.chunks[0].data, BaseEncoding.base16().decode(pubkey.toUpperCase())) } height = 1 } val answer = peer.getUTXOs(listOf(TransactionOutPoint(params, 0, txhash))).get(10, TimeUnit.SECONDS) val rightHeight = answer.heights[0] == height val rightSpentness = answer.hitMap.size == 1 && answer.hitMap[0] == 1.toByte() val rightOutput = if (answer.outputs.size == 1) outcheck(answer.outputs[0]) else false if (!rightHeight || !rightSpentness || !rightOutput) { log.warn("Found peer ${sockaddr} which has the GETUTXO service bit set but didn't answer the test query correctly") log.warn("Got $answer") } else { log.info("Peer $sockaddr is flagged as supporting GETUTXO and passed the test query") addrMap[sockaddr] = addrMap[sockaddr]!!.copy(supportsGetUTXO = true) db.commit() } } catch (e: TimeoutException) { log.warn("Found peer $sockaddr which has the GETUTXO service bit set but didn't answer quickly enough") } catch (e: Exception) { log.warn("Crash whilst trying to process getutxo answer from $sockaddr", e) } } private fun onDisconnected() { openConnections-- crawl() } @Synchronized public fun getSomePeers(size: Int, serviceMask: Long): List<Pair<InetSocketAddress, PeerData>> { // Take some items from the head of the list and add them back to the tail, i.e. we loop around. val addrs: List<InetSocketAddress> = if (serviceMask == -1L) { size.gatherTimes { okPeers.poll() }.filterNotNull() } else { val matches = okPeers.filter { addrMap[it]!!.serviceBits and serviceMask == serviceMask }.take(size) okPeers.removeAll(matches) matches } okPeers.addAll(addrs) return addrs.map { it to addrMap[it]!! } } @Synchronized private fun loadFromDB() { // Shuffle the peers because otherwise MapDB can give them back with very close IP ordering. val tmp: MutableList<InetSocketAddress> = arrayListOf() for ((addr, data) in addrMap) { if (data.status == PeerStatus.OK) tmp.add(addr) if (data.shouldRecrawl()) scheduleRecrawl(addr) } Collections.shuffle(tmp) okPeers.addAll(tmp) log.info("We have ${addrMap.size} IP addresses in our database of which ${okPeers.size} are considered OK") } private fun scheduleRecrawl(addr: InetSocketAddress) { recrawlQueue.add(PendingRecrawl(addr)) } private fun queueAndCrawl(addr: InetSocketAddress) { // Running on the wrong thread here, so get back onto the right one. // TODO: bcj user thread should probably be a proper scheduled executor Threading.USER_THREAD.execute() { addressQueue.add(addr.toLightweight()) crawl() } } }
apache-2.0
fd49088d4c0de0f11542195b0c083636
42.421875
201
0.649206
4.249235
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidSnippets/src/main/kotlin/tags/SnippetsTag.kt
2
1434
package com.eden.orchid.snippets.tags import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateTag import com.eden.orchid.api.options.annotations.BooleanDefault import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.snippets.models.Snippet import com.eden.orchid.snippets.models.SnippetsModel import com.eden.orchid.utilities.resolve class SnippetsTag : TemplateTag("snippets", Type.Simple, true), SnippetsModel.SnippetsQuery { @Option @Description("the snippet tags") override lateinit var snippetTags: List<String> @Option @Description("The ID to add to tabs. Defaults to the tags used to query snippets.") override var id: String = "" get() { return field.takeIf { it.isNotBlank() } ?: snippetTags.sorted().joinToString("_") } @Option @Description("render the raw snippet content without compiling it first") @BooleanDefault(false) var raw: Boolean = false lateinit var snippets: List<Snippet> override fun parameters() = arrayOf(::snippetTags.name, ::id.name, ::raw.name) override fun onRender(context: OrchidContext, page: OrchidPage?) { super.onRender(context, page) val model = context.resolve<SnippetsModel>() snippets = model.getSnippets(this) } }
mit
46309365f1febd1dc513d1a62554111d
33.97561
93
0.730126
4.108883
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/console/PydevConsoleRunnerUtil.kt
1
8412
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("PydevConsoleRunnerUtil") package com.jetbrains.python.console import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.value.* import com.intellij.lang.ASTNode import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.Pair import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.encoding.EncodingProjectManager import com.intellij.psi.PsiElement import com.jetbrains.python.console.PyConsoleOptions.PyConsoleSettings import com.jetbrains.python.console.completion.PydevConsoleElement import com.jetbrains.python.console.pydev.ConsoleCommunication import com.jetbrains.python.parsing.console.PythonConsoleData import com.jetbrains.python.remote.PyRemotePathMapper import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase import com.jetbrains.python.remote.PythonRemoteInterpreterManager import com.jetbrains.python.run.PythonCommandLineState import com.jetbrains.python.run.target.getPathMapper import com.jetbrains.python.run.toStringLiteral import com.jetbrains.python.sdk.PythonEnvUtil import com.jetbrains.python.sdk.PythonSdkUtil import com.jetbrains.python.target.PyTargetAwareAdditionalData import java.util.function.Function fun getPathMapper(project: Project, sdk: Sdk?, consoleSettings: PyConsoleSettings): PyRemotePathMapper? { if (sdk == null) return null return when (val sdkAdditionalData = sdk.sdkAdditionalData) { is PyTargetAwareAdditionalData -> getPathMapper(project, consoleSettings, sdkAdditionalData) is PyRemoteSdkAdditionalDataBase -> getPathMapper(project, consoleSettings, sdkAdditionalData) else -> null } } fun getPathMapper(project: Project, consoleSettings: PyConsoleSettings, remoteSdkAdditionalData: PyRemoteSdkAdditionalDataBase): PyRemotePathMapper { val remotePathMapper = PythonRemoteInterpreterManager.appendBasicMappings(project, null, remoteSdkAdditionalData) val mappingSettings = consoleSettings.mappingSettings if (mappingSettings != null) { remotePathMapper.addAll(mappingSettings.pathMappings, PyRemotePathMapper.PyPathMappingType.USER_DEFINED) } return remotePathMapper } fun findPythonSdkAndModule(project: Project, contextModule: Module?): Pair<Sdk?, Module?> { var sdk: Sdk? = null var module: Module? = null val settings = PyConsoleOptions.getInstance(project).pythonConsoleSettings val sdkHome = settings.sdkHome if (sdkHome != null) { sdk = PythonSdkUtil.findSdkByPath(sdkHome) if (settings.moduleName != null) { module = ModuleManager.getInstance(project).findModuleByName(settings.moduleName) } else { module = contextModule if (module == null && ModuleManager.getInstance(project).modules.isNotEmpty()) { module = ModuleManager.getInstance(project).modules[0] } } } if (sdk == null && settings.isUseModuleSdk) { if (contextModule != null) { module = contextModule } else if (settings.moduleName != null) { module = ModuleManager.getInstance(project).findModuleByName(settings.moduleName) } if (module != null) { if (PythonSdkUtil.findPythonSdk(module) != null) { sdk = PythonSdkUtil.findPythonSdk(module) } } } else if (contextModule != null) { if (module == null) { module = contextModule } if (sdk == null) { sdk = PythonSdkUtil.findPythonSdk(module) } } if (sdk == null) { for (m in ModuleManager.getInstance(project).modules) { if (PythonSdkUtil.findPythonSdk(m) != null) { sdk = PythonSdkUtil.findPythonSdk(m) module = m break } } } if (sdk == null) { if (PythonSdkUtil.getAllSdks().size > 0) { sdk = PythonSdkUtil.getAllSdks()[0] //take any python sdk } } return Pair.create(sdk, module) } fun constructPyPathAndWorkingDirCommand(pythonPath: MutableCollection<String>, workingDir: String?, command: String): String { if (workingDir != null) { pythonPath.add(workingDir) } val path = pythonPath.joinToString(separator = ", ", transform = String::toStringLiteral) return command.replace(PydevConsoleRunnerImpl.WORKING_DIR_AND_PYTHON_PATHS, path) } fun constructPyPathAndWorkingDirCommand(pythonPath: MutableCollection<Function<TargetEnvironment, String>>, workingDirFunction: TargetEnvironmentFunction<String>?, command: String): TargetEnvironmentFunction<String> { if (workingDirFunction != null) { pythonPath.add(workingDirFunction) } val path = pythonPath.toLinkedSetFunction().andThenJoinToString(separator = ", ", transform = String::toStringLiteral) return ReplaceSubstringFunction(command, PydevConsoleRunnerImpl.WORKING_DIR_AND_PYTHON_PATHS, path) } private class ReplaceSubstringFunction(private val s: String, private val oldValue: String, private val newValue: TargetEnvironmentFunction<String>) : TraceableTargetEnvironmentFunction<String>() { override fun applyInner(t: TargetEnvironment): String = s.replace(oldValue, newValue.apply(t)) override fun toString(): String = "ReplaceSubstringFunction(s='$s', oldValue='$oldValue', newValue=$newValue)" } fun addDefaultEnvironments(sdk: Sdk, envs: Map<String, String>, project: Project): Map<String, String> { setCorrectStdOutEncoding(envs, project) PythonEnvUtil.initPythonPath(envs, true, PythonCommandLineState.getAddedPaths(sdk)) return envs } /** * Add required ENV var to Python task to set its stdout charset to current project charset to allow it print correctly. * * @param envs map of envs to add variable * @param project current project */ private fun setCorrectStdOutEncoding(envs: Map<String, String>, project: Project) { val defaultCharset = EncodingProjectManager.getInstance(project).defaultCharset val encoding = defaultCharset.name() PythonEnvUtil.setPythonIOEncoding(PythonEnvUtil.setPythonUnbuffered(envs), encoding) } /** * Set command line charset as current project charset. * Add required ENV var to Python task to set its stdout charset to current project charset to allow it print correctly. * * @param commandLine command line * @param project current project */ fun setCorrectStdOutEncoding(commandLine: GeneralCommandLine, project: Project) { val defaultCharset = EncodingProjectManager.getInstance(project).defaultCharset commandLine.charset = defaultCharset PythonEnvUtil.setPythonIOEncoding(commandLine.environment, defaultCharset.name()) } fun isInPydevConsole(element: PsiElement): Boolean { return element is PydevConsoleElement || getConsoleCommunication(element) != null || hasConsoleKey(element) } private fun hasConsoleKey(element: PsiElement): Boolean { val psiFile = element.containingFile ?: return false if (psiFile.virtualFile == null) return false val inConsole = element.containingFile.virtualFile.getUserData(PythonConsoleView.CONSOLE_KEY) return inConsole != null && inConsole } fun isConsoleView(file: VirtualFile): Boolean { return file.getUserData(PythonConsoleView.CONSOLE_KEY) == true } fun getPythonConsoleData(element: ASTNode?): PythonConsoleData? { if (element == null || element.psi == null || element.psi.containingFile == null) { return null } val file = PydevConsoleRunnerImpl.getConsoleFile(element.psi.containingFile) ?: return null return file.getUserData(PyConsoleUtil.PYTHON_CONSOLE_DATA) } private fun getConsoleCommunication(element: PsiElement): ConsoleCommunication? { val containingFile = element.containingFile return containingFile?.getCopyableUserData(PydevConsoleRunner.CONSOLE_COMMUNICATION_KEY) } fun getConsoleSdk(element: PsiElement): Sdk? { val containingFile = element.containingFile return containingFile?.getCopyableUserData(PydevConsoleRunner.CONSOLE_SDK) }
apache-2.0
69b7fd468fb1485aa0c61c6e36094493
40.44335
120
0.742035
4.647514
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/AfterConversionPass.kt
1
1281
// 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.j2k import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.KtFile class AfterConversionPass(val project: Project, private val postProcessor: PostProcessor) { @JvmOverloads fun run( kotlinFile: KtFile, converterContext: ConverterContext?, range: TextRange?, onPhaseChanged: ((Int, String) -> Unit)? = null ) { postProcessor.doAdditionalProcessing( when { range != null -> JKPieceOfCodePostProcessingTarget(kotlinFile, range.toRangeMarker(kotlinFile)) else -> JKMultipleFilesPostProcessingTarget(listOf(kotlinFile)) }, converterContext, onPhaseChanged ) } } fun TextRange.toRangeMarker(file: KtFile): RangeMarker = runReadAction { file.viewProvider.document!!.createRangeMarker(startOffset, endOffset) }.apply { isGreedyToLeft = true isGreedyToRight = true }
apache-2.0
481151cab0f8f8f2c0637508ac5a16f4
36.705882
158
0.704137
4.852273
false
false
false
false
marukami/RxKotlin-Android-Samples
app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/fragments/ConcurrencyWithSchedulersDemoFragment.kt
1
5297
package au.com.tilbrook.android.rxkotlin.fragments import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.* import android.view.View.INVISIBLE import android.widget.ArrayAdapter import android.widget.LinearLayout.HORIZONTAL import android.widget.ListView import android.widget.ProgressBar import au.com.tilbrook.android.rxkotlin.R import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.ctx import rx.Observable import rx.Observer import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import timber.log.Timber import java.util.* class ConcurrencyWithSchedulersDemoFragment : BaseFragment() { private lateinit var _progress: ProgressBar private lateinit var _logsList: ListView private lateinit var _adapter: LogAdapter private lateinit var _logs: MutableList<String> private lateinit var _subscription: CompositeSubscription override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) _setupLogger() _subscription = CompositeSubscription() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return with(ctx) { verticalLayout { textView(R.string.msg_demo_concurrency_schedulers) { lparams(width = matchParent) padding = dip(10) }.gravity = Gravity.CENTER linearLayout { orientation = HORIZONTAL button { text = "Start long operation" textSize = 16f lparams { leftMargin = dip(16) } onClick { startLongOperation() } } _progress = progressBar { visibility = INVISIBLE lparams { leftMargin = dip(20) } } } _logsList = listView { lparams(width = matchParent, height = matchParent) } } } } override fun onPause() { super.onPause() _subscription.clear() } fun startLongOperation() { _progress.visibility = View.VISIBLE _log("Button Clicked") _subscription.add(_getObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(LongOperationObserver()) ) } private fun _getObservable(): Observable<Boolean> { return Observable.just(true).map { aBoolean -> _log("Within Observable") _doSomeLongOperation_thatBlocksCurrentThread() aBoolean } } /** * Observer that handles the result through the 3 important actions: * 1. onCompleted * 2. onError * 3. onNext */ private inner class LongOperationObserver() : Observer<Boolean> { override fun onNext(bool: Boolean?) { _log("onNext with return value \"%b\"".format(bool)) } override fun onError(e: Throwable) { Timber.e(e, "Error in RxJava Demo concurrency") _log("Boo! Error %s".format(e.message)) _progress.visibility = INVISIBLE } override fun onCompleted() { _log("On complete") _progress.visibility = INVISIBLE } } // ----------------------------------------------------------------------------------- // Method that help wiring up the example (irrelevant to RxJava) private fun _doSomeLongOperation_thatBlocksCurrentThread() { _log("performing long operation") try { Thread.sleep(3000) } catch (e: InterruptedException) { Timber.d("Operation was interrupted") } } private fun _log(logMsg: String) { if (_isCurrentlyOnMainThread()) { _logs.add(0, logMsg + " (main thread) ") _adapter.clear() _adapter.addAll(_logs) } else { _logs.add(0, logMsg + " (NOT main thread) ") // You can only do below stuff on main thread. Handler(Looper.getMainLooper()).post(object : Runnable { override fun run() { _adapter.clear() _adapter.addAll(_logs) } }) } } private fun _setupLogger() { _logs = ArrayList<String>() _adapter = LogAdapter(activity, ArrayList<String>()) _logsList.adapter = _adapter } private fun _isCurrentlyOnMainThread(): Boolean { return Looper.myLooper() == Looper.getMainLooper() } private inner class LogAdapter(context: Context, logs: List<String>) : ArrayAdapter<String>(context, R.layout.item_log, R.id.item_log, logs) }
apache-2.0
f38cc908b0c6b13ce67e654adfac302a
30.164706
90
0.550689
5.312939
false
false
false
false
codebutler/farebot
farebot-app/src/main/java/com/codebutler/farebot/app/feature/card/CardScreen.kt
1
6769
/* * CardScreen.kt * * This file is part of FareBot. * Learn more at: https://codebutler.github.io/farebot/ * * Copyright (C) 2017 Eric Butler <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.farebot.app.feature.card import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.view.Menu import com.codebutler.farebot.R import com.codebutler.farebot.app.core.activity.ActivityOperations import com.codebutler.farebot.app.core.analytics.AnalyticsEventName import com.codebutler.farebot.app.core.analytics.logAnalyticsEvent import com.codebutler.farebot.app.core.inject.ScreenScope import com.codebutler.farebot.app.core.transit.TransitFactoryRegistry import com.codebutler.farebot.app.core.ui.ActionBarOptions import com.codebutler.farebot.app.core.ui.FareBotScreen import com.codebutler.farebot.app.feature.card.advanced.CardAdvancedScreen import com.codebutler.farebot.app.feature.card.map.TripMapScreen import com.codebutler.farebot.app.feature.main.MainActivity import com.codebutler.farebot.card.Card import com.codebutler.farebot.card.RawCard import com.codebutler.farebot.transit.TransitInfo import com.uber.autodispose.kotlin.autoDisposable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject class CardScreen(private val rawCard: RawCard<*>) : FareBotScreen<CardScreen.Component, CardScreenView>() { data class Content( val card: Card, val transitInfo: TransitInfo?, val viewModels: List<TransactionViewModel> ) private var content: Content? = null @Inject lateinit var activityOperations: ActivityOperations @Inject lateinit var transitFactoryRegistry: TransitFactoryRegistry override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions( backgroundColorRes = R.color.accent, textColorRes = R.color.white, shadow = false ) override fun onCreateView(context: Context): CardScreenView = CardScreenView(context) override fun onShow(context: Context) { super.onShow(context) logAnalyticsEvent(AnalyticsEventName.VIEW_CARD, rawCard.cardType().toString()) activityOperations.menuItemClick .autoDisposable(this) .subscribe({ menuItem -> when (menuItem.itemId) { R.id.card_advanced -> { content?.let { navigator.goTo(CardAdvancedScreen(it.card, it.transitInfo)) } } } }) loadContent() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .autoDisposable(this) .subscribe({ content -> this.content = content if (content.transitInfo != null) { (activity as AppCompatActivity).supportActionBar?.apply { title = content.transitInfo.getCardName(view.resources) subtitle = content.transitInfo.serialNumber } view.setTransitInfo(content.transitInfo, content.viewModels) } else { (activity as AppCompatActivity).supportActionBar?.apply { title = context.getString(R.string.unknown_card) } view.setError(context.getString(R.string.unknown_card_desc)) } activity.invalidateOptionsMenu() val type = content.transitInfo?.getCardName(activity.resources) ?: "Unknown" logAnalyticsEvent(AnalyticsEventName.VIEW_TRANSIT, type) }) view.observeItemClicks() .autoDisposable(this) .subscribe { viewModel -> when (viewModel) { is TransactionViewModel.TripViewModel -> { val trip = viewModel.trip if (trip.startStation?.hasLocation() == true || trip.endStation?.hasLocation() == true) { navigator.goTo(TripMapScreen(trip)) } } } } } override fun onUpdateMenu(menu: Menu?) { menu?.clear() activity.menuInflater.inflate(R.menu.screen_card, menu) menu?.findItem(R.id.card_advanced)?.isVisible = content != null } private fun loadContent(): Single<Content> = Single.create<Content> { e -> try { val card = rawCard.parse() val transitInfo = transitFactoryRegistry.parseTransitInfo(card) val viewModels = createViewModels(transitInfo) e.onSuccess(Content(card, transitInfo, viewModels)) } catch (ex: Exception) { e.onError(ex) } } private fun createViewModels(transitInfo: TransitInfo?): List<TransactionViewModel> { val subscriptions = transitInfo?.subscriptions?.map { TransactionViewModel.SubscriptionViewModel(activity, it) } ?: listOf() val trips = transitInfo?.trips?.map { TransactionViewModel.TripViewModel(activity, it) } ?: listOf() val refills = transitInfo?.refills?.map { TransactionViewModel.RefillViewModel(activity, it) } ?: listOf() return subscriptions + (trips + refills).sortedByDescending { it.date } } override fun createComponent(parentComponent: MainActivity.MainActivityComponent): Component = DaggerCardScreen_Component.builder() .mainActivityComponent(parentComponent) .build() override fun inject(component: Component) { component.inject(this) } @ScreenScope @dagger.Component(dependencies = arrayOf(MainActivity.MainActivityComponent::class)) interface Component { fun inject(screen: CardScreen) } }
gpl-3.0
ec022ab2bf1349356ea54a49b4d3c518
40.27439
117
0.639533
4.944485
false
false
false
false
actions-on-google/actions-shortcut-convert
src/main/kotlin/com/google/assistant/actions/model/shortcuts/ShortcutsModel.kt
1
6341
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.assistant.actions.model.shortcuts import com.sun.xml.bind.marshaller.NamespacePrefixMapper import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement private const val ANDROID_NAMESPACE_URI = "http://schemas.android.com/apk/res/android" private const val APP_NAMESPACE = "app" @XmlRootElement(name = "shortcuts") data class ShortcutsRoot( @set:XmlElement(name = "capability") var capabilities: List<Capability> = mutableListOf(), @set:XmlElement(name = "shortcut") var shortcuts: List<Shortcut> = mutableListOf(), ) // Children of ShortcutsRoot data class Capability( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var name: String? = null, @set:XmlAttribute(namespace = APP_NAMESPACE) var queryPatterns: String? = null, @set:XmlElement(name = "intent") var intents: List<CapabilityIntent> = mutableListOf(), @set:XmlElement(name = "slice") var slices: List<Slice> = mutableListOf(), @set:XmlElement(name = "shortcut-fulfillment") var shortcutFulfillments: List<ShortcutFulfillment> = mutableListOf(), ) data class Shortcut( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var shortcutId: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var enabled: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var icon: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var shortcutShortLabel: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var shortcutLongLabel: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var disabledMessage: String? = null, @set:XmlElement(name = "intent") var intents: List<ShortcutIntent> = mutableListOf(), @set:XmlElement(name = "capability-binding") var capabilityBindings: List<CapabilityBinding> = mutableListOf(), @set:XmlElement(name = "extra") var extras: List<Extra> = mutableListOf(), ) // // Children of Capability // data class CapabilityIntent( @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var action: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var targetClass: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var targetPackage: String? = null, @set:XmlElement(name = "url-template") var urlTemplate: UrlTemplate? = null, @set:XmlElement var parameter: List<Parameter> = mutableListOf(), @set:XmlElement(name="extra") var extras: List<Extra> = mutableListOf(), ) data class Slice( @set:XmlElement(name = "url-template") var urlTemplate: UrlTemplate? = null, @set:XmlElement var parameter: List<Parameter> = mutableListOf(), ) data class ShortcutFulfillment( @set:XmlElement var parameter: Parameter? = null, ) // // Children of Shortcut // data class ShortcutIntent( @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var action: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var targetPackage: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var targetClass: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var data: String? = null, @set:XmlElement(name = "url-template") var urlTemplate: UrlTemplate? = null, ) // // Children of CapabilityIntent // data class UrlTemplate( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var value: String? = null ) data class Parameter( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var name: String? = null, @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var key: String? = null, @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var mimeType: String? = null, @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var required: String? = null, @set:XmlAttribute // TOOD(tanub): update this namespace with "app:" var shortcutMatchRequired: String? = null, @set:XmlElement var data: Data? = null, ) data class Extra( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var key: String? = null, @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var value: String? = null, ) // // Children of ShortcutIntent // data class CapabilityBinding( @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var key: String? = null, @set:XmlElement(name = "parameter-binding") var parameterBinding: List<ParameterBinding> = mutableListOf(), ) // // Children of CapabilityBinding // data class ParameterBinding( @set:XmlAttribute(required = false, namespace = ANDROID_NAMESPACE_URI) var key: String? = null, @set:XmlAttribute(required = true, namespace = ANDROID_NAMESPACE_URI) var value: String? = null, ) // // Children of Parameter // data class Data( @set:XmlAttribute(namespace = ANDROID_NAMESPACE_URI) var pathPattern: String? = null, ) class AndroidNamespaceMapper : NamespacePrefixMapper() { override fun getPreferredPrefix( namespaceUri: String?, suggestion: String?, requirePrefix: Boolean ): String? { if (ANDROID_NAMESPACE_URI == namespaceUri) { return "android" } else if (APP_NAMESPACE == namespaceUri) { return namespaceUri } return suggestion } override fun getPreDeclaredNamespaceUris(): Array<String> { return arrayOf(ANDROID_NAMESPACE_URI) } }
apache-2.0
eeb2f2c9ca906e72a9d3c60e858f39a2
25.09465
86
0.698943
4.005685
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/core/src/templates/kotlin/core/linux/LinuxTypes.kt
3
5717
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package core.linux import org.lwjgl.generator.* val __u8 = typedef(uint8_t, "__u8") val __u16 = typedef(uint16_t, "__u16") val __u32 = typedef(uint32_t, "__u32") val __u64 = typedef(uint64_t, "__u64") val __s32 = typedef(int32_t, "__s32") val __s64 = typedef(int64_t, "__s64") val ssize_t = IntegerType("ssize_t", PrimitiveMapping.POINTER) val mode_t = typedef(unsigned_int, "mode_t") val off_t = typedef(int64_t, "off_t") val pid_t = typedef(int, "pid_t") val socklen_t = typedef(uint32_t, "socklen_t") val cpu_set_t = "cpu_set_t".opaque val sigset_t = "sigset_t".opaque val flock = struct(Module.CORE_LINUX, "Flock", nativeName = "flock64") { short("l_type", "type of lock").links("#F_RDLCK #F_WRLCK #F_UNLCK") short("l_whence", "where {@code l_start} is relative to (like {@code lseek})") off_t("l_start", "offset where the lock begins") off_t("l_len", "size of the locked area; zero means until EOF") pid_t("l_pid", "process holding the lock") } val f_owner_ex = struct(Module.CORE_LINUX, "FOwnerEx", nativeName = "f_owner_ex") { int("type", "") pid_t("pid", "") } // fcntl.h val open_how = struct(Module.CORE_LINUX, "OpenHow", nativeName = "struct open_how") { documentation = """ Arguments for how {@code openat2(2)} should open the target path. If only {@code flags} and {@code @}mode are non-zero, then {@code openat2(2)} operates very similarly to {@code openat(2)}. However, unlike {@code openat(2)}, unknown or invalid bits in {@code flags} result in {@code -EINVAL} rather than being silently ignored. {@code mode} must be zero unless one of #O_CREAT, #O_TMPFILE are set. """ __u64("flags", "") __u64("mode", "") __u64("resolve", "") } // fs.h val __kernel_rwf_t = typedef(int, "__kernel_rwf_t") // sys/epoll.h val epoll_data_t = union(Module.CORE_LINUX, "EpollData", nativeName = "epoll_data_t") { opaque_p("ptr", "") int("fd", "") uint32_t("u32", "") uint64_t("u64", "") } val epoll_event = struct(Module.CORE_LINUX, "EpollEvent", nativeName = "struct epoll_event") { uint32_t("events", "epoll events") epoll_data_t("data", "user data variable") } // sys/uio.h val iovec = struct(Module.CORE_LINUX, "IOVec", nativeName = "struct iovec") { Check("iov_len")..nullable..void.p("iov_base", "starting address") size_t("iov_len", "number of bytes to transfer") } // sys/socket.h val msghdr = struct(Module.CORE_LINUX, "Msghdr", nativeName = "struct msghdr") { void.p("msg_name", "address to send to/receive from") AutoSize("msg_name")..socklen_t("msg_namelen", "length of {@code address} data") iovec.p("msg_iov", "vector of data to send/receive into") AutoSize("msg_iov")..size_t("msg_iovlen", "number of elements in the vector") void.p("msg_control", "ancillary data (eg BSD filedesc passing)") AutoSize("msg_control")..size_t("msg_controllen", "ancillary data buffer length") int("msg_flags", "flags on received message") } val sockaddr = struct(Module.CORE_LINUX, "Sockaddr", nativeName = "struct sockaddr") { documentation = "Structure describing a generic socket address." typedef(unsigned_short, "sa_family_t")("sa_family", "address family and length") char("sa_data", "address data")[14] } val cmsghdr = struct(Module.CORE_LINUX, "CMsghdr", nativeName = "struct cmsghdr") { socklen_t("cmsg_len", "data byte count, including header") int("cmsg_level", "originating protocol") int("cmsg_type", "protocol-specific type") char("cmsg_data", "")[0] } // sys/stat.h val stat = "struct stat".opaque // TODO: val statx_timestamp = struct(Module.CORE_LINUX, "StatxTimestamp", nativeName = "struct statx_timestamp") { documentation = "Timestamp structure for the timestamps in {@code struct statx}." __s64("tv_sec", "the number of seconds before (negative) or after (positive) {@code 00:00:00 1st January 1970 UTC}") __u32("tv_nsec", "a number of nanoseconds (0..999,999,999) after the {@code tv_sec} time") __s32("__reserved", "in case we need a yet finer resolution").private() } val statx = struct(Module.CORE_LINUX, "Statx", nativeName = "struct statx") { __u32("stx_mask", "what results were written [uncond]") __u32("stx_blksize", "preferred general I/O size [uncond]") __u64("stx_attributes", "flags conveying information about the file [uncond]") __u32("stx_nlink", "number of hard links") __u32("stx_uid", "user ID of owner") __u32("stx_gid", "group ID of owner") __u16("stx_mode", "file mode") __u16("__spare0", "")[1].private() __u64("stx_ino", "{@code inode} number") __u64("stx_size", "file size") __u64("stx_blocks", "number of 512-byte blocks allocated") __u64("stx_attributes_mask", "mask to show what's supported in {@code stx_attributes}") statx_timestamp("stx_atime", "last access time") statx_timestamp("stx_btime", "file creation time") statx_timestamp("stx_ctime", "last attribute change time") statx_timestamp("stx_mtime", "last data modification time ") __u32("stx_rdev_major", "device ID of special file [if bdev/cdev]") __u32("stx_rdev_minor", "") __u32("stx_dev_major", "ID of device containing file [uncond]") __u32("stx_dev_minor", "") __u64("stx_mnt_id", "") __u64("__spare2", "").private() __u64("__spare3", "spare space for future expansion")[12].private() } // time_types.h val __kernel_timespec = struct(Module.CORE_LINUX, "KernelTimespec", nativeName = "struct __kernel_timespec") { int64_t("tv_sec", "seconds") long_long("tv_nsec", "nanoseconds") }
bsd-3-clause
9f2ed86264190f098fc5d24c7d5b4423
35.890323
158
0.639846
3.008947
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/math/sets/MultipleOfSet.kt
1
2650
package net.pureal.traits.math.sets import net.pureal.traits.math.* import net.pureal.traits.* public trait MultipleOfSet : RealSet, net.pureal.traits.math.Set { public companion object : Constructor4<net.pureal.traits.math.Set, Number, Number, Number, Number>, Constructor3<net.pureal.traits.math.Set, Number, Number, Number>, Constructor2<net.pureal.traits.math.Set, Number, RealSet> { override fun invoke(factor: Number, offset: Number, lEnd: Number, hEnd: Number): net.pureal.traits.math.Set { val factor = factor.asCalculatable().abs() // to make 0 <= offset < factor val off = offset divideAndRemainder factor if (factor is Infinity) return EmptySet var le = lEnd.asCalculatable() + off[0] var he = hEnd.asCalculatable() + off[0] if (le > he) { val tmp = le le = he he = tmp } le = le.ceil() * factor + off[1] he = he.floor() * factor + off[1] return object : MultipleOfSet { override val factor = factor override val offset = off[1] override val lowEnd = le override val highEnd = he } } override fun invoke(factor: Number, lEnd: Number, hEnd: Number): net.pureal.traits.math.Set = invoke(factor, 0, lEnd, hEnd) override fun invoke(factor: Number, s: RealSet): net.pureal.traits.math.Set = invoke(factor, s.lowEnd, s.highEnd) } override fun toString(): String = "multipleOfSet(${factor}, ${lowEnd / factor}, ${highEnd / factor})" override fun contains(other: Number): Boolean { try { val o = (other.asCalculatable() - offset) % factor return super<RealSet>.contains(other) && o equals 0 } catch(e: UnsupportedOperationException) { return false } } override fun contains(other: net.pureal.traits.math.Set): Boolean { if (other is MultipleOfSet) return lowEnd <= other.lowEnd && highEnd >= other.lowEnd && other.factor % factor equals 0 && (other.offset - offset) % factor equals 0 return super<net.pureal.traits.math.Set>.contains(other) } val factor: Calculatable val offset: Calculatable override val lowClosed: Boolean get() = true override val highClosed: Boolean get() = true override fun equals(other: Any?) = other is MultipleOfSet && factor == other.factor && lowEnd == other.lowEnd && highEnd == other.highEnd } val multipleOfSet = MultipleOfSet
bsd-3-clause
666e0928a0c7ee6a33784dc0c31cdb45
40.421875
141
0.600755
4.089506
false
false
false
false
google/android-fhir
engine/src/main/java/com/google/android/fhir/FhirEngineProvider.kt
1
5452
/* * 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 import android.content.Context import com.google.android.fhir.DatabaseErrorStrategy.UNSPECIFIED import com.google.android.fhir.sync.Authenticator import com.google.android.fhir.sync.DataSource import com.google.android.fhir.sync.remote.HttpLogger /** The provider for [FhirEngine] instance. */ object FhirEngineProvider { private var fhirEngineConfiguration: FhirEngineConfiguration? = null private var fhirServices: FhirServices? = null /** * Initializes the [FhirEngine] singleton with a custom Configuration. * * This method throws [IllegalStateException] if it is called multiple times */ @Synchronized fun init(fhirEngineConfiguration: FhirEngineConfiguration) { check(this.fhirEngineConfiguration == null) { "FhirEngineProvider: FhirEngineConfiguration has already been initialized." } this.fhirEngineConfiguration = fhirEngineConfiguration } /** * Returns the cached [FhirEngine] instance. Creates a new instance from the supplied [Context] if * it doesn't exist. * * If this method is called without calling [init], the default [FhirEngineConfiguration] is used. */ @Synchronized fun getInstance(context: Context): FhirEngine { return getOrCreateFhirService(context).fhirEngine } @Synchronized @JvmStatic // needed for mockito internal fun getDataSource(context: Context): DataSource? { return getOrCreateFhirService(context).remoteDataSource } @Synchronized private fun getOrCreateFhirService(context: Context): FhirServices { if (fhirServices == null) { fhirEngineConfiguration = fhirEngineConfiguration ?: FhirEngineConfiguration() val configuration = checkNotNull(fhirEngineConfiguration) fhirServices = FhirServices.builder(context.applicationContext) .apply { if (configuration.enableEncryptionIfSupported) enableEncryptionIfSupported() setDatabaseErrorStrategy(configuration.databaseErrorStrategy) configuration.serverConfiguration?.let { setServerConfiguration(it) } if (configuration.testMode) { inMemory() } } .build() } return checkNotNull(fhirServices) } @Synchronized fun cleanup() { check(fhirEngineConfiguration?.testMode == true) { "FhirEngineProvider: FhirEngineProvider needs to be in the test mode to perform cleanup." } forceCleanup() } internal fun forceCleanup() { fhirServices?.database?.close() fhirServices = null fhirEngineConfiguration = null } } /** * A configuration which describes the database setup and error recovery. * * Database encryption is only available on API 23 or above. If enableEncryptionIfSupported is true, * FHIR SDK will only enable database encryption on API 23 or above. * * WARNING: Your app may try to decrypt an unencrypted database from a device which was previously * on API 22 but later upgraded to API 23. When this happens, an [IllegalStateException] is thrown. */ data class FhirEngineConfiguration( val enableEncryptionIfSupported: Boolean = false, val databaseErrorStrategy: DatabaseErrorStrategy = UNSPECIFIED, val serverConfiguration: ServerConfiguration? = null, val testMode: Boolean = false ) enum class DatabaseErrorStrategy { /** * If unspecified, all database errors will be propagated to the call site. The caller shall * handle the database error on a case-by-case basis. */ UNSPECIFIED, /** * If a database error occurs at open, automatically recreate the database. * * This strategy is NOT respected when opening a previously unencrypted database with an encrypted * configuration or vice versa. An [IllegalStateException] is thrown instead. */ RECREATE_AT_OPEN } /** A configuration to provide necessary params for network connection. */ data class ServerConfiguration( /** Url of the remote FHIR server. */ val baseUrl: String, /** A configuration to provide the network connection parameters. */ val networkConfiguration: NetworkConfiguration = NetworkConfiguration(), /** * An [Authenticator] for supplying any auth token that may be necessary to communicate with the * server */ val authenticator: Authenticator? = null, /** Logs the communication between the engine and the remote server. */ val httpLogger: HttpLogger = HttpLogger.NONE ) /** A configuration to provide the network connection parameters. */ data class NetworkConfiguration( /** Connection timeout (in seconds). The default is 10 seconds. */ val connectionTimeOut: Long = 10, /** Read timeout (in seconds) for network connection. The default is 10 seconds. */ val readTimeOut: Long = 10, /** Write timeout (in seconds) for network connection. The default is 10 seconds. */ val writeTimeOut: Long = 10 )
apache-2.0
8a816f0e3abdfdcac8f7078a97a8ff37
35.346667
100
0.736427
4.732639
false
true
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/relationship/internal/RelationshipManager.kt
1
4074
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.relationship.internal import dagger.Reusable import javax.inject.Inject import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper import org.hisp.dhis.android.core.relationship.Relationship import org.hisp.dhis.android.core.relationship.RelationshipConstraintType import org.hisp.dhis.android.core.relationship.RelationshipItem @Reusable internal class RelationshipManager @Inject constructor( private var relationshipStore: RelationshipStore, private val relationshipItemStore: RelationshipItemStore, private val relationshipVersionManager: RelationshipDHISVersionManager ) { fun getByItem( searchItem: RelationshipItem, includeDeleted: Boolean, onlyAccessible: Boolean ): List<Relationship> { val relationships = relationshipItemStore.getByItem(searchItem) .mapNotNull { item -> val relationship = relationshipStore.selectByUid(item.relationship()!!.uid()) if (relationship != null && (includeDeleted || !CollectionsHelper.isDeleted(relationship))) { val relatedType = when (item.relationshipItemType()!!) { RelationshipConstraintType.FROM -> RelationshipConstraintType.TO RelationshipConstraintType.TO -> RelationshipConstraintType.FROM } val relatedItem = relationshipItemStore .getForRelationshipUidAndConstraintType(relationship.uid()!!, relatedType) relatedItem?.let { when (item.relationshipItemType()!!) { RelationshipConstraintType.FROM -> relationship.toBuilder() .from(item) .to(relatedItem) .build() RelationshipConstraintType.TO -> relationship.toBuilder() .from(relatedItem) .to(item) .build() } } } else { null } } return if (onlyAccessible) { relationshipVersionManager.getOwnedRelationships(relationships, searchItem.elementUid()) } else { relationships } } }
bsd-3-clause
a0d0043d653c0aa6025acc20c03f8145
45.827586
109
0.645557
5.557981
false
false
false
false
komu/scratch
src/main/kotlin/markdown/TabSeparatedValuesToMarkdownTable.kt
1
1073
package markdown private const val tableData = """ """ fun main() { toMarkDownTable(tableData.lines(), "\t") } fun toMarkDownTable(lines: List<String>, separator: String) { val rows = lines.map { it.trim() }.filter { it.isNotEmpty() }.map { it.split(separator) } val columns = rows.first() val data = rows.drop(1) val transposedData = columns.indices.map { index -> data.map { it[index] } } println(columns.toMarkdownTableRow()) println(columns.indices.map { guessColumnType(transposedData[it]).markdownHeader }.toMarkdownTableRow()) for (row in data) println(row.toMarkdownTableRow()) } enum class ColumnType(val markdownHeader: String) { DEFAULT("----"), NUMERIC("---:") } private fun guessColumnType(values: List<String>) = if (values.all { it.isBlank() || it.isNumeric() } ) ColumnType.NUMERIC else ColumnType.DEFAULT private fun String.isNumeric() = matches(Regex("""\d+(\.\d+)?""")) private fun List<String>.toMarkdownTableRow() = joinToString(" | ", prefix = "| ", postfix = " |")
mit
845d7bd18873578189873f9c56a1c75b
28
108
0.649581
3.725694
false
false
false
false
martijn-heil/wac-core
src/main/kotlin/tk/martijn_heil/wac_core/WacCore.kt
1
6480
/* * wac-core * Copyright (C) 2016 Martijn Heil * * 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 tk.martijn_heil.wac_core import com.comphenix.protocol.ProtocolLibrary import com.comphenix.protocol.ProtocolManager import org.bukkit.Bukkit import org.bukkit.plugin.Plugin import org.bukkit.plugin.java.JavaPlugin import tk.martijn_heil.wac_core.classes.PlayerClassModule import tk.martijn_heil.wac_core.craft.SailingModule import tk.martijn_heil.wac_core.gameplay.GamePlayControlModule import tk.martijn_heil.wac_core.general.GeneralModule import tk.martijn_heil.wac_core.kingdom.KingdomModule import tk.martijn_heil.wac_core.namehiding.NameHidingModule import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException import java.util.* import java.util.logging.Logger class WacCore : JavaPlugin() { val debug = false override fun onEnable() { try { Companion.plugin = this Companion.logger = logger logger.fine("Saving default config..") saveDefaultConfig() logger.info("Migrating database if needed..") dbUrl = config.getString("db.url") dbUsername = config.getString("db.username") dbPassword = config.getString("db.password") // Storing the password in a char array doesn't improve much.. // it's stored in plaintext in the "config" object anyway.. :/ // This is a hack, we use a custom classloader to replace Flyway's VersionPrinter class with // Our custom version of that class, which is located in the resources folder. // The main reason for this is that with Bukkit, Flyway was having classpath issues determining it's version. // Due to that the whole plugin crashed on startup. val hackyLoader = HackyClassLoader(this.classLoader) val cls = hackyLoader.loadClass("tk.martijn_heil.wac_core.HackyClass") val migrationResult = cls!!.getMethod("doStuff", String::class.java, String::class.java, String::class.java, ClassLoader::class.java).invoke(null, dbUrl, dbUsername, dbPassword, this.classLoader) as Boolean if(!migrationResult) { this.isEnabled = false return } try { WacCore.dbconn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword) } catch (ex: SQLException) { WacCore.logger.severe(ex.message) WacCore.logger.severe("Disabling plugin due to database error..") this.isEnabled = false return } messages = ResourceBundle.getBundle("messages.messages") logger.info("Ensuring database presence of all players currently online..") for (player in Bukkit.getServer().onlinePlayers) { ensurePresenceInDatabase(player) } logger.info("Setting up ProtocolLib things..") protocolManager = ProtocolLibrary.getProtocolManager() if (!debug) KingdomModule.init(this, PrefixedLogger("WacCoreKingdomModuleLogger", "KingdomModule", logger)) GeneralModule.init(this, PrefixedLogger("WacCoreGeneralModuleLogger", "GeneralModule", logger)) GamePlayControlModule.init(this, PrefixedLogger("WacCoreGamePlayControlModuleLogger", "GamePlayControlModule", logger)) CustomResourcePackModule.init(this, PrefixedLogger("WacCoreCustomResourcePackModule", "CustomResourcePackModule", logger)) //CommandModule.init(this, PrefixedLogger("WacCoreCommandModuleLogger", "CommandModule", logger)) //GameModeSwitchingModule.init(this, PrefixedLogger("GameModeSwitchingModuleLogger", "GameModeSwitchingModule", logger)) SailingModule.init(this, PrefixedLogger("WacCoreSailingModuleLogger", "SailingModule", logger)) SprintRestrictionModule.init(this, PrefixedLogger("WacCoreSprintRestrictionModuleLogger", "SprintRestrictionModule", logger)) HealthModule.init(this, PrefixedLogger("WacCoreHealthModuleLogger", "HealthModule", logger)) NameHidingModule.init(this, PrefixedLogger("WacCoreNameHidingModuleLogger", "NameHidingModule", logger), protocolManager) CrackshotHook.init(this, PrefixedLogger("WacCoreCrackShootHookLogger", "CrackShotHook", logger), protocolManager) PlayerClassModule.init(this) //TemporaryModule.init(this) if(!debug) HackyModule.init(PrefixedLogger("HackyModuleLogger", "HackyModule", logger)) } catch (t: Throwable) { t.printStackTrace() throw t } } override fun onDisable() { SailingModule.close() HackyModule.close() PlayerClassModule.close() } companion object { private lateinit var dbUrl: String private lateinit var dbUsername: String private lateinit var dbPassword: String var dbconn: Connection? = null get() { if(field!!.isClosed) field = DriverManager.getConnection(dbUrl, dbUsername, dbPassword) return field } lateinit var messages: ResourceBundle lateinit var logger: Logger lateinit var plugin: Plugin lateinit var protocolManager: ProtocolManager } enum class Permission(val str: String) { BYPASS__ITEM_LIMIT("wac-core.bypass.item-limit"), BYPASS__GAMEMODE_SWITCH_PENALTY("wac-core.bypass.gamemode-switch-penalty"), BYPASS__OCEAN_BUILD_LIMITS("wac-core.bypass.ocean-build-limits"); override fun toString() = str } }
gpl-3.0
31113a21d6a1ab9862cea4d8b2ff89c2
43.957447
218
0.662963
4.585987
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/model/kapt/KaptModelBuilderService.kt
4
6370
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling.model.kapt import org.gradle.api.Named import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task import org.jetbrains.kotlin.idea.gradleTooling.* import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext import org.jetbrains.plugins.gradle.tooling.ModelBuilderService import java.io.File import java.io.Serializable import java.lang.reflect.Modifier interface KaptSourceSetModel : Serializable { val sourceSetName: String val isTest: Boolean val generatedSourcesDir: String val generatedClassesDir: String val generatedKotlinSourcesDir: String val generatedSourcesDirFile get() = generatedSourcesDir.takeIf { it.isNotEmpty() }?.let(::File) val generatedClassesDirFile get() = generatedClassesDir.takeIf { it.isNotEmpty() }?.let(::File) val generatedKotlinSourcesDirFile get() = generatedKotlinSourcesDir.takeIf { it.isNotEmpty() }?.let(::File) } class KaptSourceSetModelImpl( override val sourceSetName: String, override val isTest: Boolean, override val generatedSourcesDir: String, override val generatedClassesDir: String, override val generatedKotlinSourcesDir: String ) : KaptSourceSetModel interface KaptGradleModel : Serializable { val isEnabled: Boolean val buildDirectory: File val sourceSets: List<KaptSourceSetModel> } class KaptGradleModelImpl( override val isEnabled: Boolean, override val buildDirectory: File, override val sourceSets: List<KaptSourceSetModel> ) : KaptGradleModel class KaptModelBuilderService : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex { override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder { return ErrorMessageBuilder.create(project, e, "Gradle import errors") .withDescription("Unable to build kotlin-kapt plugin configuration") } override fun canBuild(modelName: String?): Boolean = modelName == KaptGradleModel::class.java.name override fun buildAll(modelName: String?, project: Project): KaptGradleModelImpl? { return buildAll(project, null) } override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KaptGradleModelImpl? { return buildAll(project, builderContext) } private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KaptGradleModelImpl? { val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter) if (androidVariantRequest.shouldSkipBuildAllCall()) return null val kaptPlugin: Plugin<*>? = project.plugins.findPlugin("kotlin-kapt") val kaptIsEnabled = kaptPlugin != null val sourceSets = mutableListOf<KaptSourceSetModel>() if (kaptIsEnabled) { // When running in Android Studio, Android Studio would request specific source sets only to avoid syncing // currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants // accidentally named starting with upper case. val targets = project.getTargets() fun handleCompileTask(moduleName: String, compileTask: Task) { if (compileTask.javaClass.name !in kotlinCompileJvmTaskClasses) { return } val sourceSetName = compileTask.getSourceSetName() val isTest = sourceSetName.toLowerCase().endsWith("test") val kaptGeneratedSourcesDir = getKaptDirectory("getKaptGeneratedSourcesDir", project, sourceSetName) val kaptGeneratedClassesDir = getKaptDirectory("getKaptGeneratedClassesDir", project, sourceSetName) val kaptGeneratedKotlinSourcesDir = getKaptDirectory("getKaptGeneratedKotlinSourcesDir", project, sourceSetName) sourceSets += KaptSourceSetModelImpl( moduleName, isTest, kaptGeneratedSourcesDir, kaptGeneratedClassesDir, kaptGeneratedKotlinSourcesDir ) } if (!targets.isNullOrEmpty()) { for (target in targets) { if (!isWithJavaEnabled(target)) { continue } val compilations = target.compilations ?: continue for (compilation in compilations) { val compileTask = compilation.getCompileKotlinTaskName(project) ?: continue val moduleName = target.name + compilation.name.capitalize() handleCompileTask(moduleName, compileTask) } } } else { val compileTasks = project.getTarget()?.compilations?.map { compilation -> compilation.getCompileKotlinTaskName(project) } ?: project.getAllTasks(false)[project] compileTasks?.forEach{ compileTask -> val sourceSetName = compileTask.getSourceSetName() if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach handleCompileTask(sourceSetName, compileTask) } } } return KaptGradleModelImpl(kaptIsEnabled, project.buildDir, sourceSets) } private fun isWithJavaEnabled(target: Named): Boolean { val getWithJavaEnabledMethod = target.javaClass.methods .firstOrNull { it.name == "getWithJavaEnabled" && it.parameterCount == 0 } ?: return false return getWithJavaEnabledMethod.invoke(target) == true } private fun getKaptDirectory(funName: String, project: Project, sourceSetName: String): String { val kotlinKaptPlugin = project.plugins.findPlugin("kotlin-kapt") ?: return "" val targetMethod = kotlinKaptPlugin::class.java.methods.firstOrNull { Modifier.isStatic(it.modifiers) && it.name == funName && it.parameterCount == 2 } ?: return "" return (targetMethod(null, project, sourceSetName) as? File)?.absolutePath ?: "" } }
apache-2.0
974fe2cc73c6c6b74ed28aaa6d6841cd
44.184397
158
0.690581
5.389171
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actpost/ActPostAttachment.kt
1
11467
package jp.juggler.subwaytooter.actpost import android.app.Dialog import android.net.Uri import android.view.View import androidx.appcompat.app.AlertDialog import jp.juggler.subwaytooter.ActPost import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.Styler import jp.juggler.subwaytooter.api.ApiTask import jp.juggler.subwaytooter.api.TootApiResult import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.api.runApiTask import jp.juggler.subwaytooter.dialog.ActionsDialog import jp.juggler.subwaytooter.dialog.DlgFocusPoint import jp.juggler.subwaytooter.dialog.DlgTextInput import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.util.AttachmentRequest import jp.juggler.subwaytooter.util.PostAttachment import jp.juggler.subwaytooter.view.MyNetworkImageView import jp.juggler.util.* private val log = LogCategory("ActPostAttachment") // AppStateに保存する fun ActPost.saveAttachmentList() { if (!isMultiWindowPost) appState.attachmentList = this.attachmentList } fun ActPost.decodeAttachments(sv: String) { attachmentList.clear() try { sv.decodeJsonArray().objectList().forEach { try { attachmentList.add(PostAttachment(TootAttachment.decodeJson(it))) } catch (ex: Throwable) { log.trace(ex) } } } catch (ex: Throwable) { log.trace(ex) } } fun ActPost.showMediaAttachment() { if (isFinishing) return views.llAttachment.vg(attachmentList.isNotEmpty()) ivMedia.forEachIndexed { i, v -> showMediaAttachmentOne(v, i) } } fun ActPost.showMedisAttachmentProgress() { val mergedProgress = attachmentList .mapNotNull { it.progress.notEmpty() } .joinToString("\n") views.tvAttachmentProgress .vg(mergedProgress.isNotEmpty()) ?.text = mergedProgress } fun ActPost.showMediaAttachmentOne(iv: MyNetworkImageView, idx: Int) { if (idx >= attachmentList.size) { iv.visibility = View.GONE } else { iv.visibility = View.VISIBLE val pa = attachmentList[idx] val a = pa.attachment when { a == null || pa.status != PostAttachment.Status.Ok -> { iv.setDefaultImage(Styler.defaultColorIcon(this, R.drawable.ic_upload)) iv.setErrorImage(Styler.defaultColorIcon(this, R.drawable.ic_clip)) iv.setImageUrl(Styler.calcIconRound(iv.layoutParams.width), null) } else -> { val defaultIconId = when (a.type) { TootAttachmentType.Image -> R.drawable.ic_image TootAttachmentType.Video, TootAttachmentType.GIFV, -> R.drawable.ic_videocam TootAttachmentType.Audio -> R.drawable.ic_music_note else -> R.drawable.ic_clip } iv.setDefaultImage(Styler.defaultColorIcon(this, defaultIconId)) iv.setErrorImage(Styler.defaultColorIcon(this, defaultIconId)) iv.setImageUrl(Styler.calcIconRound(iv.layoutParams.width), a.preview_url) } } } } fun ActPost.openAttachment() { when { attachmentList.size >= 4 -> showToast(false, R.string.attachment_too_many) account == null -> showToast(false, R.string.account_select_please) else -> attachmentPicker.openPicker() } } fun ActPost.addAttachment( uri: Uri, mimeTypeArg: String? = null, // onUploadEnd: () -> Unit = {}, ) { val account = this.account val mimeType = attachmentUploader.getMimeType(uri, mimeTypeArg) val isReply = states.inReplyToId != null val instance = account?.let { TootInstance.getCached(it) } when { attachmentList.size >= 4 -> showToast(false, R.string.attachment_too_many) account == null -> showToast(false, R.string.account_select_please) mimeType?.isEmpty() != false -> showToast(false, R.string.mime_type_missing) !attachmentUploader.isAcceptableMimeType( instance, mimeType, isReply ) -> Unit // エラーメッセージ出力済み else -> { saveAttachmentList() val pa = PostAttachment(this) attachmentList.add(pa) showMediaAttachment() attachmentUploader.addRequest( AttachmentRequest( account, pa, uri, mimeType, isReply = isReply, // onUploadEnd = onUploadEnd ) ) } } } fun ActPost.onPostAttachmentCompleteImpl(pa: PostAttachment) { // この添付メディアはリストにない if (!attachmentList.contains(pa)) { log.w("onPostAttachmentComplete: not in attachment list.") return } when (pa.status) { PostAttachment.Status.Error -> { log.w("onPostAttachmentComplete: upload failed.") attachmentList.remove(pa) showMediaAttachment() } PostAttachment.Status.Progress -> { // アップロード中…? log.w("onPostAttachmentComplete: ?? status=${pa.status}") } PostAttachment.Status.Ok -> { when (val a = pa.attachment) { null -> log.e("onPostAttachmentComplete: upload complete, but missing attachment entity.") else -> { // アップロード完了 log.i("onPostAttachmentComplete: upload complete.") // 投稿欄の末尾に追記する if (PrefB.bpAppendAttachmentUrlToContent(pref)) { val selStart = views.etContent.selectionStart val selEnd = views.etContent.selectionEnd val e = views.etContent.editableText val len = e.length val lastChar = if (len <= 0) ' ' else e[len - 1] if (!CharacterGroup.isWhitespace(lastChar.code)) { e.append(" ").append(a.text_url) } else { e.append(a.text_url) } views.etContent.setSelection(selStart, selEnd) } } } showMediaAttachment() } } } // 添付した画像をタップ fun ActPost.performAttachmentClick(idx: Int) { val pa = try { attachmentList[idx] } catch (ex: Throwable) { showToast(false, ex.withCaption("can't get attachment item[$idx].")) return } val a = ActionsDialog() .addAction(getString(R.string.set_description)) { editAttachmentDescription(pa) } if (pa.attachment?.canFocus == true) { a.addAction(getString(R.string.set_focus_point)) { openFocusPoint(pa) } } if (account?.isMastodon == true) { when (pa.attachment?.type) { TootAttachmentType.Audio, TootAttachmentType.GIFV, TootAttachmentType.Video, -> a.addAction(getString(R.string.custom_thumbnail)) { attachmentPicker.openCustomThumbnail(pa) } else -> Unit } } a.addAction(getString(R.string.delete)) { deleteAttachment(pa) } a.show(this, title = getString(R.string.media_attachment)) } fun ActPost.deleteAttachment(pa: PostAttachment) { AlertDialog.Builder(this) .setTitle(R.string.confirm_delete_attachment) .setPositiveButton(R.string.ok) { _, _ -> try { pa.isCancelled = true pa.status = PostAttachment.Status.Error pa.job.cancel() attachmentList.remove(pa) } catch (ignored: Throwable) { } showMediaAttachment() } .setNegativeButton(R.string.cancel, null) .show() } fun ActPost.openFocusPoint(pa: PostAttachment) { val attachment = pa.attachment ?: return DlgFocusPoint(this, attachment) .setCallback { x, y -> sendFocusPoint(pa, attachment, x, y) } .show() } fun ActPost.sendFocusPoint(pa: PostAttachment, attachment: TootAttachment, x: Float, y: Float) { val account = this.account ?: return launchMain { var resultAttachment: TootAttachment? = null runApiTask(account, progressStyle = ApiTask.PROGRESS_NONE) { client -> try { client.request( "/api/v1/media/${attachment.id}", jsonObject { put("focus", "%.2f,%.2f".format(x, y)) }.toPutRequestBuilder() )?.also { result -> resultAttachment = parseItem(::TootAttachment, ServiceType.MASTODON, result.jsonObject) } } catch (ex: Throwable) { TootApiResult(ex.withCaption("set focus point failed.")) } }?.let { result -> when (val newAttachment = resultAttachment) { null -> showToast(true, result.error) else -> pa.attachment = newAttachment } } } } fun ActPost.editAttachmentDescription(pa: PostAttachment) { val a = pa.attachment if (a == null) { showToast(true, R.string.attachment_description_cant_edit_while_uploading) return } DlgTextInput.show( this, getString(R.string.attachment_description), a.description, callback = object : DlgTextInput.Callback { override fun onEmptyError() { showToast(true, R.string.description_empty) } override fun onOK(dialog: Dialog, text: String) { val attachmentId = pa.attachment?.id ?: return val account = [email protected] ?: return launchMain { val (result, newAttachment) = attachmentUploader.setAttachmentDescription( account, attachmentId, text ) when (newAttachment) { null -> result?.error?.let { showToast(true, it) } else -> { pa.attachment = newAttachment showMediaAttachment() dialog.dismissSafe() } } } } }) } fun ActPost.onPickCustomThumbnailImpl(pa: PostAttachment, src: GetContentResultEntry) { when (val account = this.account) { null -> showToast(false, R.string.account_select_please) else -> launchMain { val result = attachmentUploader.uploadCustomThumbnail(account, src, pa) result?.error?.let { showToast(true, it) } showMediaAttachment() } } }
apache-2.0
8ff76996104e48592105be419fffcc65
33.177019
106
0.552573
4.569181
false
false
false
false
lisuperhong/ModularityApp
CommonBusiness/src/main/java/com/company/commonbusiness/base/fragment/BaseFragment.kt
1
3999
package com.company.commonbusiness.base.fragment import android.content.Context import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.company.commonbusiness.base.activity.BaseActivity /** * @author 李昭鸿 * @desc: Fragment基类 * @date Created on 2017/7/21 15:35 */ abstract class BaseFragment : Fragment() { protected val TAG = BaseFragment::class.java.simpleName /** * 当前Fragment是否可见 */ private var isFragmentVisible: Boolean = false /** * true表示rootView已加载完成 */ private var isPrepared: Boolean = false /** * 是否第一次加载 */ private var isFirstLoad = true /** * 忽略isFirstLoad的值,强制刷新数据,但仍要isFragmentVisible & isPrepared * 一般用于PagerAdapter需要刷新各个子Fragment的场景 * 不要new新的PagerAdapter,而采取reset数据的方式 * 所以要求Fragment重新走initData方法 * 故使用 [BaseFragment.setForceLoad]来让Fragment下次执行initData */ private var forceLoad = false protected var context: BaseActivity? = null // 缓存Fragment的view private var rootView: View? = null @get:LayoutRes protected abstract val layoutId: Int override fun onAttach(context: Context?) { super.onAttach(context) if (context is BaseActivity) { this.context = this.activity as BaseActivity? } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { if (rootView == null) { rootView = inflater.inflate(layoutId, null) } return rootView } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) isPrepared = true isFirstLoad = true initPresenter() initView() lazyLoad() } /** * 如果是与ViewPager一起使用,调用的是setUserVisibleHint * * @param isVisibleToUser Fragment是否显示 */ override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (userVisibleHint) { onVisible() } else { onInvisible() } } /** * 如果是通过FragmentTransaction的show和hide的方法来控制显示,调用的是onHiddenChanged. * 若是初始就show的Fragment 为了触发该事件 需要先hide再show * * @param hidden hidden True if the fragment is now hidden, false if it is not * visible. */ override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden) { onVisible() } else { onInvisible() } } override fun onDestroy() { super.onDestroy() isPrepared = false } /** * 忽略isFirstLoad的值,强制刷新数据,但仍要isFragmentVisible & isPrepared */ fun setForceLoad() { forceLoad = true } private fun onVisible() { isFragmentVisible = true lazyLoad() } private fun onInvisible() { isFragmentVisible = false } private fun lazyLoad() { if (isPrepared && isFragmentVisible) { if (isFirstLoad || forceLoad) { isFirstLoad = false forceLoad = false initData() } } } open fun initPresenter() { } protected abstract fun initView() /** * 若把初始化内容放到initData实现 * 就是采用Lazy方式加载的Fragment * 若不需要Lazy加载则initData方法内留空,初始化内容放到initView即可 */ protected abstract fun initData() }
apache-2.0
60d66ded28a41e85d81aa3ba4d46a85a
22.54902
82
0.625312
4.356711
false
false
false
false
google/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinDefinitionsSearcher.kt
3
7591
// 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.search.ideaExtensions import com.intellij.openapi.application.ReadAction import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.search.searches.DefinitionsScopedSearch import com.intellij.util.Processor import com.intellij.util.QueryExecutor import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.toFakeLightClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.actualsForExpected import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.forEachOverridingMethod import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachImplementation import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contains import java.util.concurrent.Callable class KotlinDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters> { override fun execute(queryParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>): Boolean { val processor = skipDelegatedMethodsConsumer(consumer) val element = queryParameters.element val scope = queryParameters.scope return when (element) { is KtClass -> { val isExpectEnum = runReadAction { element.isEnum() && element.isExpectDeclaration() } if (isExpectEnum) { processActualDeclarations(element, processor) } else { processClassImplementations(element, processor) && processActualDeclarations(element, processor) } } is KtObjectDeclaration -> { processActualDeclarations(element, processor) } is KtLightClass -> { val useScope = runReadAction { element.useScope } if (useScope is LocalSearchScope) processLightClassLocalImplementations(element, useScope, processor) else true } is KtNamedFunction, is KtSecondaryConstructor -> { processFunctionImplementations(element as KtFunction, scope, processor) && processActualDeclarations(element, processor) } is KtProperty -> { processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor) } is KtParameter -> { if (isFieldParameter(element)) { processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor) } else { true } } else -> true } } companion object { private fun skipDelegatedMethodsConsumer(baseConsumer: Processor<in PsiElement>): Processor<PsiElement> = Processor { element -> if (isDelegated(element)) { return@Processor true } baseConsumer.process(element) } private fun isDelegated(element: PsiElement): Boolean = element is KtLightMethod && element.isDelegated private fun isFieldParameter(parameter: KtParameter): Boolean = runReadAction { KtPsiUtil.getClassIfParameterIsProperty(parameter) != null } private fun processClassImplementations(klass: KtClass, consumer: Processor<PsiElement>): Boolean { val psiClass = runReadAction { klass.toLightClass() ?: klass.toFakeLightClass() } val searchScope = runReadAction { psiClass.useScope } if (searchScope is LocalSearchScope) { return processLightClassLocalImplementations(psiClass, searchScope, consumer) } return runReadAction { ContainerUtil.process(ClassInheritorsSearch.search(psiClass, true), consumer) } } private fun processLightClassLocalImplementations( psiClass: KtLightClass, searchScope: LocalSearchScope, consumer: Processor<PsiElement> ): Boolean { // workaround for IDEA optimization that uses Java PSI traversal to locate inheritors in local search scope val virtualFiles = runReadAction { searchScope.scope.mapTo(HashSet()) { it.containingFile.virtualFile } } val globalScope = GlobalSearchScope.filesScope(psiClass.project, virtualFiles) return ContainerUtil.process(ClassInheritorsSearch.search(psiClass, globalScope, true)) { candidate -> val candidateOrigin = candidate.unwrapped ?: candidate val inScope = runReadAction { candidateOrigin in searchScope } if (inScope) { consumer.process(candidate) } else { true } } } private fun processFunctionImplementations( function: KtFunction, scope: SearchScope, consumer: Processor<PsiElement>, ): Boolean = ReadAction.nonBlocking(Callable { function.toPossiblyFakeLightMethods().firstOrNull()?.forEachImplementation(scope, consumer::process) ?: true }).executeSynchronously() private fun processPropertyImplementations( declaration: KtNamedDeclaration, scope: SearchScope, consumer: Processor<PsiElement> ): Boolean = runReadAction { processPropertyImplementationsMethods(declaration.toPossiblyFakeLightMethods(), scope, consumer) } private fun processActualDeclarations(declaration: KtDeclaration, consumer: Processor<PsiElement>): Boolean = runReadAction { if (!declaration.isExpectDeclaration()) true else declaration.actualsForExpected().all(consumer::process) } fun processPropertyImplementationsMethods( accessors: Iterable<PsiMethod>, scope: SearchScope, consumer: Processor<PsiElement> ): Boolean = accessors.all { method -> method.forEachOverridingMethod(scope) { implementation -> if (isDelegated(implementation)) return@forEachOverridingMethod true val elementToProcess = runReadAction { when (val mirrorElement = (implementation as? KtLightMethod)?.kotlinOrigin) { is KtProperty, is KtParameter -> mirrorElement is KtPropertyAccessor -> if (mirrorElement.parent is KtProperty) mirrorElement.parent else implementation else -> implementation } } consumer.process(elementToProcess) } } } }
apache-2.0
53a32e5db6bf754aee06c01a28579de2
43.652941
136
0.666842
5.953725
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/ProductProperties.kt
1
12315
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.PersistentMap import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentMapOf import org.jetbrains.annotations.ApiStatus import org.jetbrains.intellij.build.impl.productInfo.CustomProperty import org.jetbrains.jps.model.module.JpsModule import java.nio.file.Path import java.util.* import java.util.function.BiPredicate /** * Describes distribution of an IntelliJ-based IDE. Override this class and build distribution of your product. */ abstract class ProductProperties() { /** * The base name for script files (*.bat, *.sh, *.exe), usually a shortened product name in lower case * (e.g. 'idea' for IntelliJ IDEA, 'datagrip' for DataGrip). */ abstract val baseFileName: String /** * Deprecated: specify product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file instead (see its schema for details); * if you need to get the product code in the build scripts, use [ApplicationInfoProperties.productCode] instead; * if you need to override product code value from *ApplicationInfo.xml - [ProductProperties.customProductCode] can be used. */ @Deprecated("see the doc") var productCode: String? = null /** * This value overrides specified product code in 'number' attribute in 'build' tag in *ApplicationInfo.xml file. */ open val customProductCode: String? get() = null /** * Value of 'idea.platform.prefix' property. It's also used as a prefix for 'ApplicationInfo.xml' product descriptor. */ var platformPrefix: String? = null /** * Name of the module containing ${platformPrefix}ApplicationInfo.xml product descriptor in 'idea' package. */ lateinit var applicationInfoModule: String /** * Enables fast activation of a running IDE instance from the launcher * (at the moment, it is only implemented in the native Windows one). */ var fastInstanceActivation = true /** * An entry point into application's Java code, usually [com.intellij.idea.Main]. */ var mainClassName = "com.intellij.idea.Main" /** * Paths to directories containing images specified by 'logo/@url' and 'icon/@ico' attributes in ApplicationInfo.xml file. * <br> * todo(nik) get rid of this and make sure that these resources are located in [applicationInfoModule] instead */ var brandingResourcePaths: List<Path> = emptyList() /** * Name of the command which runs IDE in 'offline inspections' mode * (returned by [com.intellij.openapi.application.ApplicationStarter.getCommandName]). * This property will be also used to name sh/bat scripts which execute this command. */ var inspectCommandName = "inspect" /** * `true` if tools.jar from JDK must be added to the IDE classpath. */ var toolsJarRequired = false var isAntRequired = false /** * Whether to use splash for application start-up. */ var useSplash = false /** * Class-loader that product application should use by default. * <p/> * `com.intellij.util.lang.PathClassLoader` is used by default as * it unifies class-loading logic of an application and allows to avoid double-loading of bootstrap classes. */ var classLoader: String? = "com.intellij.util.lang.PathClassLoader" /** * Additional arguments which will be added to JVM command line in IDE launchers for all operating systems. */ var additionalIdeJvmArguments: MutableList<String> = mutableListOf() /** * The specified options will be used instead of/in addition to the default JVM memory options for all operating systems. */ var customJvmMemoryOptions: PersistentMap<String, String> = persistentMapOf() /** * An identifier which will be used to form names for directories where configuration and caches will be stored, usually a product name * without spaces with an added version ('IntelliJIdea2016.1' for IntelliJ IDEA 2016.1). */ open fun getSystemSelector(appInfo: ApplicationInfoProperties, buildNumber: String): String { return "${appInfo.productName}${appInfo.majorVersion}.${appInfo.minorVersionMainPart}" } /** * If `true`, Alt+Button1 shortcut will be removed from 'Quick Evaluate Expression' action and assigned to 'Add/Remove Caret' action * (instead of Alt+Shift+Button1) in the default keymap. */ var reassignAltClickToMultipleCarets = false /** * Now file containing information about third-party libraries is bundled and shown inside the IDE. * If `true`, HTML & JSON files of third-party libraries will be placed alongside built artifacts. */ var generateLibraryLicensesTable = true /** * List of licenses information about all libraries which can be used in the product modules. */ var allLibraryLicenses: List<LibraryLicense> = CommunityLibraryLicenses.LICENSES_LIST /** * If `true`, the product's main JAR file will be scrambled using [ProprietaryBuildTools.scrambleTool]. */ var scrambleMainJar = false @ApiStatus.Experimental var useProductJar = true /** * If `false`, names of private fields won't be scrambled (to avoid problems with serialization). * This field is ignored if [scrambleMainJar] is `false`. */ var scramblePrivateFields = true /** * Path to an alternative scramble script which will should be used for a product. */ var alternativeScrambleStubPath: Path? = null /** * Describes which modules should be included in the product's platform and which plugins should be bundled with the product. */ val productLayout = ProductModulesLayout() /** * If `true`, a cross-platform ZIP archive containing binaries for all OSes will be built. * The archive will be generated in [BuildPaths.artifactDir] directory and have ".portable" suffix by default * (override [getCrossPlatformZipFileName] to change the file name). * Cross-platform distribution is required for [plugins development](https://github.com/JetBrains/gradle-intellij-plugin). */ var buildCrossPlatformDistribution = false /** * Specifies name of cross-platform ZIP archive if `[buildCrossPlatformDistribution]` is set to `true`. */ open fun getCrossPlatformZipFileName(applicationInfo: ApplicationInfoProperties, buildNumber: String): String = getBaseArtifactName(applicationInfo, buildNumber) + ".portable.zip" /** * A config map for [org.jetbrains.intellij.build.impl.ClassFileChecker], * when .class file version verification is needed. */ var versionCheckerConfig: PersistentMap<String, String> = persistentMapOf() /** * Strings which are forbidden as a part of resulting class file path */ var forbiddenClassFileSubPaths: List<String> = emptyList() /** * Paths to properties files the content of which should be appended to idea.properties file. */ var additionalIDEPropertiesFilePaths: List<Path> = emptyList() /** * Paths to directories the content of which should be added to 'license' directory of IDE distribution. */ var additionalDirectoriesWithLicenses: List<Path> = emptyList() /** * Base file name (without an extension) for product archives and installers (*.exe, *.tar.gz, *.dmg). */ abstract fun getBaseArtifactName(appInfo: ApplicationInfoProperties, buildNumber: String): String /** * @return an instance of the class containing properties specific for Windows distribution, * or `null` if the product doesn't have Windows distribution. */ abstract fun createWindowsCustomizer(projectHome: String): WindowsDistributionCustomizer? /** * @return an instance of the class containing properties specific for Linux distribution, * or `null` if the product doesn't have Linux distribution. */ abstract fun createLinuxCustomizer(projectHome: String): LinuxDistributionCustomizer? /** * @return an instance of the class containing properties specific for macOS distribution, * or `null` if the product doesn't have macOS distribution. */ abstract fun createMacCustomizer(projectHome: String): MacDistributionCustomizer? /** * If `true`, a .zip archive containing sources of modules included in the product will be produced. * See also [includeIntoSourcesArchiveFilter]. */ var buildSourcesArchive = false /** * Determines sources of which modules should be included in the source archive when [buildSourcesArchive] is `true`. */ var includeIntoSourcesArchiveFilter: BiPredicate<JpsModule, BuildContext> = BiPredicate { _, _ -> true } /** * Specifies how Maven artifacts for IDE modules should be generated; by default, no artifacts are generated. */ val mavenArtifacts = MavenArtifactsProperties() /** * Specified additional modules (not included into the product layout) which need to be compiled when product is built. * todo(nik) get rid of this */ var additionalModulesToCompile: PersistentList<String> = persistentListOf() /** * Specified modules which tests need to be compiled when product is built. * todo(nik) get rid of this */ var modulesToCompileTests: List<String> = emptyList() var runtimeDistribution: JetBrainsRuntimeDistribution = JetBrainsRuntimeDistribution.JCEF /** * A prefix for names of environment variables used by Windows and Linux distributions * to allow users to customize location of the product runtime (`<PRODUCT>_JDK` variable), * *.vmoptions file (`<PRODUCT>_VM_OPTIONS`), `idea.properties` file (`<PRODUCT>_PROPERTIES`). */ open fun getEnvironmentVariableBaseName(appInfo: ApplicationInfoProperties) = appInfo.upperCaseProductName /** * Override this method to copy additional files to distributions of all operating systems. */ open suspend fun copyAdditionalFiles(context: BuildContext, targetDirectory: String) { } /** * Override this method if the product has several editions to ensure that their artifacts won't be mixed up. * @return the name of a subdirectory under `projectHome/out` where build artifacts will be placed, * must be unique among all products built from the same sources. */ open fun getOutputDirectoryName(appInfo: ApplicationInfoProperties) = appInfo.productName.lowercase(Locale.ROOT) /** * Paths to externally built plugins to be included in the IDE. * They will be copied into the build, as well as included in the IDE classpath when launching it to build search index, .jar order, etc. */ open fun getAdditionalPluginPaths(context: BuildContext): List<Path> = emptyList() /** * @return custom properties for [org.jetbrains.intellij.build.impl.productInfo.ProductInfoData]. */ open fun generateCustomPropertiesForProductInfo(): List<CustomProperty> = emptyList() /** * If `true`, a distribution contains libraries and launcher script for running IDE in Remote Development mode. */ @ApiStatus.Internal open fun addRemoteDevelopmentLibraries(): Boolean = productLayout.bundledPluginModules.contains("intellij.remoteDevServer") /** * Build steps which are always skipped for this product. * Can be extended via [org.jetbrains.intellij.build.BuildOptions.buildStepsToSkip], but not overridden. */ var incompatibleBuildSteps: List<String> = emptyList() /** * Names of JARs inside IDE_HOME/lib directory which need to be added to the Xbootclasspath to start the IDE */ var xBootClassPathJarNames: List<String> = emptyList() /** * Allows customizing `PRODUCT_CODE-builtinModules.json` file, which contains information about product modules, * bundled plugins, and file extensions. The file is used to populate marketplace settings of the product. * <p> * It's particularly useful when you want to limit modules used to calculate compatible plugins on the marketplace. */ open fun customizeBuiltinModules(context: BuildContext, builtinModulesFile: Path) {} /** * When set to true, invokes keymap and inspections description generators during build. * These generators produce artifacts utilized by documentation * authoring tools and builds. */ var buildDocAuthoringAssets: Boolean = false }
apache-2.0
c8d9b14344bed74bf697ed41f17abba1
39.509868
141
0.741048
4.677174
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2019/IntCode.kt
1
3717
package com.nibado.projects.advent.y2019 import com.nibado.projects.advent.toBlockingQueue import com.nibado.projects.advent.y2019.IntCode.Opcode.* import java.util.concurrent.BlockingQueue class IntCode( val memory: Memory, val input: BlockingQueue<Long>, val output: BlockingQueue<Long> ) { var terminated = false var ip = 0 var rb = 0 constructor(memory: List<Long>, input: BlockingQueue<Long>, output: BlockingQueue<Long>) : this(Memory(memory.mapIndexed { index, l -> index.toLong() to l }.toMap().toMutableMap()), input, output) constructor(memory: List<Long>, input: List<Long> = emptyList(), output: List<Long> = emptyList()) : this( Memory(memory.mapIndexed { index, l -> index.toLong() to l }.toMap().toMutableMap()), input.toBlockingQueue(), output.toBlockingQueue() ) fun run() { while (!terminated) { step() } } fun step() { if(terminated) { return } val op = Opcode.from(memory.get(ip)) val instruction = Instruction( op, (1 until op.len).map { memory.get(ip + it) }, (memory.get(ip) / 100).toString().padStart(op.len - 1, '0').map { it - '0' }.reversed() ) val result = instruction.apply(ip, rb, memory, input, output) if (result == null) { terminated = true } else { ip = result.first rb = result.second } } data class Memory(val memory: MutableMap<Long, Long>) { fun get(pos: Number) = memory.computeIfAbsent(pos.toLong()) { 0 } fun set(pos: Number, value: Number) { memory[pos.toLong()] = value.toLong() } } data class Instruction(val op: Opcode, val params: List<Long>, val modes: List<Int>) { fun apply( ip: Int, rb: Int, memory: Memory, input: BlockingQueue<Long>, output: BlockingQueue<Long> ): Pair<Int, Int>? { var base = rb fun get(param: Int) = when (modes[param]) { 0 -> memory.get(params[param].toInt()) 1 -> params[param] 2 -> memory.get(params[param].toInt() + base) else -> throw IllegalArgumentException("Invalid param $param") } fun set(param: Int, value: Long) { when (modes[param]) { 0 -> memory.set(params[param].toInt(), value) 2 -> memory.set(params[param].toInt() + base, value) } } when (op) { ADD -> set(2, get(0) + get(1)) MUL -> set(2, get(0) * get(1)) SAV -> set(0, input.take()) OUT -> output.put(get(0)) JIT -> if (get(0) != 0L) return get(1).toInt() to rb JIF -> if (get(0) == 0L) return get(1).toInt() to rb LT -> set(2, if (get(0) < get(1)) 1 else 0) EQ -> set(2, if (get(0) == get(1)) 1 else 0) REL -> base += get(0).toInt() TERM -> return null } return ip + op.len to base } } enum class Opcode(val op: Int, val len: Int) { ADD(1, 4), MUL(2, 4), SAV(3, 2), OUT(4, 2), JIT(5, 3), JIF(6, 3), LT(7, 4), EQ(8, 4), REL(9, 2), TERM(99, 1); companion object { fun from(opcode: Long) = from(opcode.toInt()) fun from(opcode: Int): Opcode = values().find { it.op == opcode % 100 } ?: throw IllegalArgumentException() } } }
mit
15e1aeb5740eff17b4e262e1815b2299
31.321739
119
0.49583
3.900315
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/adaptive/ui/dialogs/AdaptiveLevelDialogFragment.kt
2
2897
package org.stepic.droid.adaptive.ui.dialogs import android.app.Dialog import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.github.jinatonic.confetti.CommonConfetti import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.Completable import io.reactivex.Scheduler import kotlinx.android.synthetic.main.dialog_adaptive_level.view.* import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.di.qualifiers.MainScheduler import org.stepic.droid.util.resolveColorAttribute import org.stepic.droid.util.resolveFloatAttribute import org.stepik.android.view.base.ui.extension.ColorExtensions import ru.nobird.android.view.base.ui.extension.argument import java.util.concurrent.TimeUnit import javax.inject.Inject class AdaptiveLevelDialogFragment : DialogFragment() { companion object { fun newInstance(level: Long): DialogFragment = AdaptiveLevelDialogFragment().apply { this.level = level } } @Inject @field:MainScheduler lateinit var mainScheduler: Scheduler private lateinit var expLevelDialogConfetti: ViewGroup private var level by argument<Long>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App.component().inject(this) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val alertDialogBuilder = MaterialAlertDialogBuilder(requireContext()) val root = View.inflate(context, R.layout.dialog_adaptive_level, null) root.adaptiveLevelDialogTitle.text = level.toString() root.continueButton.setOnClickListener { dismiss() } expLevelDialogConfetti = root.adaptiveLevelDialogConfetti alertDialogBuilder.setView(root) return alertDialogBuilder.create() } override fun onResume() { super.onResume() val context = expLevelDialogConfetti.context // with theme overlay val alpha = context.resolveFloatAttribute(R.attr.alphaEmphasisMedium) val colorOnSurface = context.resolveColorAttribute(R.attr.colorOnSurface) val colorSecondary = context.resolveColorAttribute(R.attr.colorSecondary) val colors = intArrayOf( colorOnSurface, ColorExtensions.colorWithAlpha(colorOnSurface, alpha), colorSecondary ) Completable .timer(0, TimeUnit.MICROSECONDS) // js like work around .observeOn(mainScheduler) .subscribe { CommonConfetti .rainingConfetti(expLevelDialogConfetti, colors) .infinite() .setVelocityY(100f, 30f) .setVelocityX(0f, 60f) .setEmissionRate(15f) } } }
apache-2.0
1e09b4bda11da17515248af4f3de26ba
34.341463
81
0.706248
4.804312
false
false
false
false
pattyjogal/MusicScratchpad
app/src/main/java/com/viviose/musicscratchpad/Composition.kt
2
8714
package com.viviose.musicscratchpad import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.media.MediaPlayer import android.net.Uri import android.os.Bundle import android.os.CountDownTimer import android.os.Environment import android.os.Looper import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.util.Log import android.view.View import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.widget.Toast import java.io.File import java.io.IOException import java.util.ArrayList import java.util.concurrent.CountDownLatch class Composition : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { private fun nameToNum(note: Note): Int { var noteNum = -1 if (note.name == Note.NoteName.c) { noteNum = 12 * note.octave } else if (note.name == Note.NoteName.cs) { noteNum = 12 * note.octave + 1 } else if (note.name == Note.NoteName.d) { noteNum = 12 * note.octave + 2 } else if (note.name == Note.NoteName.ds) { noteNum = 12 * note.octave + 3 } else if (note.name == Note.NoteName.e) { noteNum = 12 * note.octave + 4 } else if (note.name == Note.NoteName.f) { noteNum = 12 * note.octave + 5 } else if (note.name == Note.NoteName.fs) { noteNum = 12 * note.octave + 6 } else if (note.name == Note.NoteName.g) { noteNum = 12 * note.octave + 7 } else if (note.name == Note.NoteName.gs) { noteNum = 12 * note.octave + 8 } else if (note.name == Note.NoteName.a) { noteNum = 12 * note.octave + 9 } else if (note.name == Note.NoteName.`as`) { noteNum = 12 * note.octave + 10 } else if (note.name == Note.NoteName.b) { noteNum = 12 * note.octave + 11 } return noteNum } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_composition) //PERMISSIONS: val hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED if (!hasPermission) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_STORAGE) } val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) //MIDI Composition val tempoTrack = MidiTrack() val noteTrack = MidiTrack() //TODO: Make the timesignatures dynamic val ts = TimeSignature() ts.setTimeSignature(4, 4, TimeSignature.DEFAULT_METER, TimeSignature.DEFAULT_DIVISION) //TODO: Make BPM Dynamic val tempo = Tempo() tempo.bpm = 60f tempoTrack.insertEvent(ts) tempoTrack.insertEvent(tempo) var lastR = 0.0 var tick: Long = 0 var tempTick: Long = 0 for (chord in MusicStore.sheet) { var chordMargin: Long = 0 for (note in chord) { tempTick = (tick + 480 * lastR).toLong() noteTrack.insertNote(0, nameToNum(note), 100, tempTick + chordMargin, 120 * note.rhythm.toLong()) print("Kill me") chordMargin += 1 lastR = note.rhythm } //TODO: This won't work for polyrhythmic chords lmao tick = tempTick } val tracks = ArrayList<MidiTrack>() tracks.add(tempoTrack) noteTrack.insertEvent(ProgramChange(0, 0, 1)) tracks.add(noteTrack) val midi = MidiFile(MidiFile.DEFAULT_RESOLUTION, tracks) val sdCard = Environment.getExternalStorageDirectory() val o = File(sdCard, "music.mid") try { midi.writeToFile(o) Toast.makeText(this, "File WRITTEN!, find it here: " + "/sdcard/Music/music.mid", Toast.LENGTH_SHORT).show() } catch (e: IOException) { System.err.println(e) Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show() } System.gc() val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { val mp = MediaPlayer() try { mp.setDataSource(o.path) } catch (e: IOException) { System.err.println("Couldn't init media player") } mp.setOnPreparedListener { mp -> mp.start() Log.i("MP", "Playing MIDI") } try { mp.prepare() } catch (e: Exception) { Log.e("MP", "Error with media player prepare") } } val drawer = findViewById(R.id.drawer_layout) as DrawerLayout val toggle = ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.setDrawerListener(toggle) toggle.syncState() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { val sendBackToMain = Intent(this, MainActivity::class.java) startActivity(sendBackToMain) super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.composition, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true } return super.onOptionsItemSelected(item) } @SuppressWarnings("StatementWithEmptyBody") override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. val id = item.itemId if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_keys) { val sendToKeys = Intent(this, KeyChanger::class.java) startActivity(sendToKeys) } else if (id == R.id.nav_clefs) { val sendToClefs = Intent(this, ClefChanger::class.java) startActivity(sendToClefs) } else if (id == R.id.nav_view_composition) { val sendToComp = Intent(this, Composition::class.java) startActivity(sendToComp) } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } else if (id == R.id.singletap) { } val drawer = findViewById(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_WRITE_STORAGE -> { if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //reload my activity with permission granted or use the features what required the permission } else { Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show() } } } } companion object { private val REQUEST_WRITE_STORAGE = 112 } }
gpl-3.0
0653e398a5ea18d5b0ff8c2bffcf343a
34.422764
199
0.61625
4.376695
false
false
false
false
theunknownxy/mcdocs
src/main/kotlin/de/theunknownxy/mcdocs/gui/document/Document.kt
1
2333
package de.theunknownxy.mcdocs.gui.document import de.theunknownxy.mcdocs.docs.Content import de.theunknownxy.mcdocs.docs.DocumentationBackend import de.theunknownxy.mcdocs.docs.DocumentationNodeRef import de.theunknownxy.mcdocs.gui.base.Point import de.theunknownxy.mcdocs.gui.base.Rectangle import de.theunknownxy.mcdocs.gui.document.builder.ContentBuilder import de.theunknownxy.mcdocs.gui.document.segments.Segment import de.theunknownxy.mcdocs.gui.event.MouseButton import java.util.ArrayList class Document(val backend: DocumentationBackend, val content: Content) { private data class Link(val rect: Rectangle, val ref: DocumentationNodeRef) private val links: MutableList<Link> = ArrayList() private val segments: MutableList<Segment> = ArrayList() public var width: Float = 0f set(v: Float) { if ($width != v) { $width = v rebuild() } } public val height: Float get() { return segments.lastOrNull()?.rect()?.y2() ?: 0f } /** * Add a segment to the end of the document */ internal fun addSegment(segment: Segment) { segment.y = segments.lastOrNull()?.rect()?.y2() ?: 0f segments.add(segment) } /** * Add a link rectangle to the document. The rectangle is offseted to the last segment position */ internal fun addLink(rect: Rectangle, ref: DocumentationNodeRef) { rect.y += segments.lastOrNull()?.rect()?.y2() ?: 0f links.add(Link(rect, ref)) } /** * Rebuild the segments from the content */ public fun rebuild() { links.clear() segments.clear() ContentBuilder(this, content).build() } /** * Draw the document at x=0|y=0 to the screen */ public fun draw() { for (segment in segments) { segment.draw() } } /** * Return an action to run when clicked at pos * @param[pos] The position of the mouse click in Document local coordinates */ public fun onMouseClick(pos: Point, button: MouseButton): Action? { for ((rect, ref) in links) { if (rect.contains(pos) && button == MouseButton.LEFT) { return NavigateAction(ref) } } return null } }
mit
7a6ef761e7f6f55b3eb8051861213828
28.544304
99
0.624089
4.312384
false
false
false
false
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/rts/route/trip/RTSTripStopsFragment.kt
1
13834
@file:JvmName("RTSTripStopsFragment") // ANALYTICS package org.mtransit.android.ui.rts.route.trip import android.content.Context import android.content.res.ColorStateList import android.location.Location import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import org.mtransit.android.R import org.mtransit.android.commons.CollectionUtils import org.mtransit.android.commons.LocationUtils import org.mtransit.android.commons.data.RouteTripStop import org.mtransit.android.data.POIArrayAdapter import org.mtransit.android.data.POIManager import org.mtransit.android.databinding.FragmentRtsTripStopsBinding import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.datasource.POIRepository import org.mtransit.android.provider.FavoriteManager import org.mtransit.android.provider.permission.LocationPermissionProvider import org.mtransit.android.provider.sensor.MTSensorManager import org.mtransit.android.task.ServiceUpdateLoader import org.mtransit.android.task.StatusLoader import org.mtransit.android.ui.fragment.MTFragmentX import org.mtransit.android.ui.rts.route.RTSRouteViewModel import org.mtransit.android.ui.view.MapViewController import org.mtransit.android.ui.view.common.IActivity import org.mtransit.android.ui.view.common.isAttached import org.mtransit.android.ui.view.common.isVisible import javax.inject.Inject @AndroidEntryPoint class RTSTripStopsFragment : MTFragmentX(R.layout.fragment_rts_trip_stops), IActivity { companion object { private val LOG_TAG = RTSTripStopsFragment::class.java.simpleName @JvmStatic fun newInstance( agencyAuthority: String, routeId: Long, tripId: Long, optSelectedStopId: Int? = null, ): RTSTripStopsFragment { return RTSTripStopsFragment().apply { arguments = bundleOf( RTSTripStopsViewModel.EXTRA_AGENCY_AUTHORITY to agencyAuthority, RTSTripStopsViewModel.EXTRA_ROUTE_ID to routeId, RTSTripStopsViewModel.EXTRA_TRIP_ID to tripId, RTSTripStopsViewModel.EXTRA_SELECTED_STOP_ID to (optSelectedStopId ?: RTSTripStopsViewModel.EXTRA_SELECTED_STOP_ID_DEFAULT), ) } } } private var theLogTag: String = LOG_TAG override fun getLogTag(): String = this.theLogTag private val viewModel by viewModels<RTSTripStopsViewModel>() private val parentViewModel by viewModels<RTSRouteViewModel>({ requireParentFragment() }) private val attachedParentViewModel get() = if (isAttached()) parentViewModel else null private var binding: FragmentRtsTripStopsBinding? = null @Inject lateinit var sensorManager: MTSensorManager @Inject lateinit var dataSourcesRepository: DataSourcesRepository @Inject lateinit var poiRepository: POIRepository @Inject lateinit var favoriteManager: FavoriteManager @Inject lateinit var statusLoader: StatusLoader @Inject lateinit var serviceUpdateLoader: ServiceUpdateLoader @Inject lateinit var locationPermissionProvider: LocationPermissionProvider private val mapMarkerProvider = object : MapViewController.MapMarkerProvider { override fun getPOMarkers(): Collection<MapViewController.POIMarker>? = null override fun getPOIs(): Collection<POIManager>? { if (!adapter.isInitialized) { return null } val pois = mutableSetOf<POIManager>() for (i in 0 until adapter.poisCount) { adapter.getItem(i)?.let { pois.add(it) } } return pois } override fun getClosestPOI() = adapter.closestPOI override fun getPOI(uuid: String?) = adapter.getItem(uuid) } private val mapViewController: MapViewController by lazy { MapViewController( logTag, mapMarkerProvider, null, // DO NOTHING (map click, camera change) true, true, true, false, false, false, 0, 56, false, true, false, true, false, this.dataSourcesRepository ).apply { setLocationPermissionGranted(locationPermissionProvider.allRequiredPermissionsGranted(requireContext())) } } private val adapter: POIArrayAdapter by lazy { POIArrayAdapter( this, this.sensorManager, this.dataSourcesRepository, this.poiRepository, this.favoriteManager, this.statusLoader, this.serviceUpdateLoader ).apply { logTag = logTag setShowExtra(false) setLocation(attachedParentViewModel?.deviceLocation?.value) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.mapViewController.onCreate(savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.mapViewController.onViewCreated(view, savedInstanceState) binding = FragmentRtsTripStopsBinding.bind(view).apply { listLayout.list.let { listView -> listView.isVisible = adapter.isInitialized adapter.setListView(listView) } fabListMap?.setOnClickListener { if (context?.resources?.getBoolean(R.bool.two_pane) == true) { // large screen return@setOnClickListener } viewModel.saveShowingListInsteadOfMap(viewModel.showingListInsteadOfMap.value == false) // switching } } parentViewModel.colorInt.observe(viewLifecycleOwner) { colorInt -> binding?.apply { colorInt?.let { colorInt -> fabListMap?.apply { rippleColor = colorInt backgroundTintList = ColorStateList.valueOf(colorInt) } } } } viewModel.tripId.observe(viewLifecycleOwner) { tripId -> theLogTag = tripId?.let { "${LOG_TAG}-$it" } ?: LOG_TAG adapter.logTag = logTag mapViewController.logTag = logTag } parentViewModel.deviceLocation.observe(viewLifecycleOwner) { deviceLocation -> mapViewController.onDeviceLocationChanged(deviceLocation) adapter.setLocation(deviceLocation) } viewModel.showingListInsteadOfMap.observe(viewLifecycleOwner) { showingListInsteadOfMap -> showingListInsteadOfMap?.let { listInsteadOfMap -> binding?.fabListMap?.apply { @Suppress("LiftReturnOrAssignment") if (listInsteadOfMap) { // LIST setImageResource(R.drawable.switch_action_map_dark_16dp) contentDescription = getString(R.string.menu_action_map) } else { // MAP setImageResource(R.drawable.switch_action_view_headline_dark_16dp) contentDescription = getString(R.string.menu_action_list) } } if (context?.resources?.getBoolean(R.bool.two_pane) == true // LARGE SCREEN || !listInsteadOfMap // MAP ) { mapViewController.onResume() } else { // LIST mapViewController.onPause() } } switchView(showingListInsteadOfMap) } viewModel.selectedTripStopId.observe(viewLifecycleOwner) { // DO NOTHING } viewModel.closestPOIShown.observe(viewLifecycleOwner) { // DO NOTHING } viewModel.poiList.observe(viewLifecycleOwner) { poiList -> var currentSelectedItemIndexUuid: Pair<Int?, String?>? = null val selectedStopId = viewModel.selectedTripStopId.value val closestPOIShow = viewModel.closestPOIShown.value if (selectedStopId != null || closestPOIShow != true) { if (selectedStopId != null) { currentSelectedItemIndexUuid = findStopIndexUuid(selectedStopId, poiList) } if (currentSelectedItemIndexUuid == null) { if (closestPOIShow == false) { currentSelectedItemIndexUuid = findClosestPOIIndexUuid(poiList) } } viewModel.setSelectedOrClosestStopShown() } adapter.setPois(poiList) adapter.updateDistanceNowAsync(parentViewModel.deviceLocation.value) mapViewController.notifyMarkerChanged(mapMarkerProvider) if (context?.resources?.getBoolean(R.bool.two_pane) == true // LARGE SCREEN || viewModel.showingListInsteadOfMap.value == true // LIST ) { val selectedPosition = currentSelectedItemIndexUuid?.first ?: -1 if (selectedPosition > 0) { binding?.listLayout?.list?.setSelection(selectedPosition - 1) // show 1 more stop on top of the list } } switchView() } } private fun findStopIndexUuid(stopId: Int, pois: List<POIManager>?): Pair<Int?, String?>? { return pois ?.withIndex() ?.firstOrNull { (it.value.poi as? RouteTripStop)?.stop?.id == stopId } ?.let { it.index to it.value.poi.uuid } } private fun findClosestPOIIndexUuid( pois: List<POIManager>?, deviceLocation: Location? = parentViewModel.deviceLocation.value ): Pair<Int?, String?>? { if (deviceLocation != null && pois?.isNotEmpty() == true) { LocationUtils.updateDistance(pois, deviceLocation.latitude, deviceLocation.longitude) val sortedPOIs = ArrayList(pois) CollectionUtils.sort(sortedPOIs, LocationUtils.POI_DISTANCE_COMPARATOR) val closestPoiUuid = sortedPOIs.getOrNull(0)?.poi?.uuid ?: return null for (idx in pois.indices) { val poim = pois[idx] if (poim.poi.uuid == closestPoiUuid) { return idx to poim.poi.uuid } } } return null } private fun switchView(showingListInsteadOfMap: Boolean? = viewModel.showingListInsteadOfMap.value) { binding?.apply { when { !adapter.isInitialized || showingListInsteadOfMap == null -> { // LOADING emptyLayout.isVisible = false listLayout.isVisible = false mapViewController.hideMap() loadingLayout.isVisible = true } adapter.poisCount == 0 -> { // EMPTY loadingLayout.isVisible = false listLayout.isVisible = false mapViewController.hideMap() emptyLayout.isVisible = true } else -> { loadingLayout.isVisible = false emptyLayout.isVisible = false if (context?.resources?.getBoolean(R.bool.two_pane) == true) { // LARGE SCREEN listLayout.isVisible = true mapViewController.showMap(view) } else if (showingListInsteadOfMap) { // LIST mapViewController.hideMap() listLayout.isVisible = true } else { // MAP listLayout.isVisible = false mapViewController.showMap(view) } } } } } override fun onAttach(context: Context) { super.onAttach(context) mapViewController.apply { setDataSourcesRepository(dataSourcesRepository) onAttach(requireActivity()) setLocationPermissionGranted(locationPermissionProvider.allRequiredPermissionsGranted(context)) } } override fun onSaveInstanceState(outState: Bundle) { mapViewController.onSaveInstanceState(outState) super.onSaveInstanceState(outState) } override fun onDetach() { super.onDetach() this.mapViewController.onDetach() } override fun onResume() { super.onResume() if (context?.resources?.getBoolean(R.bool.two_pane) == true // LARGE SCREEN || viewModel.showingListInsteadOfMap.value == false // MAP ) { mapViewController.onResume() } adapter.onResume(this, parentViewModel.deviceLocation.value) switchView() } override fun onPause() { super.onPause() mapViewController.onPause() adapter.onPause() } override fun onLowMemory() { super.onLowMemory() mapViewController.onLowMemory() } override fun onDestroyView() { super.onDestroyView() mapViewController.onDestroyView() binding = null } override fun onDestroy() { super.onDestroy() mapViewController.onDestroy() } override fun getLifecycleOwner() = this override fun finish() { activity?.finish() } override fun <T : View?> findViewById(id: Int): T? = view?.findViewById<T>(id) }
apache-2.0
272b0e75c348802b04e81103dfe93de3
36.391892
144
0.609079
5.248103
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/JTableExtensions.kt
1
1260
package com.jetbrains.packagesearch.intellij.plugin.ui.util import javax.swing.JTable import javax.swing.table.TableColumn internal fun JTable.autosizeColumnsAt(indices: Iterable<Int>) { val columns = indices.map { columnModel.getColumn(it) } val preferredWidths = getColumnDataWidths(columns) columns.forEachIndexed { index, column -> column.width = preferredWidths[index] } } private fun JTable.getColumnDataWidths(columns: Iterable<TableColumn>): IntArray { val preferredWidth = IntArray(columns.count()) val separatorSize = intercellSpacing.width for ((index, column) in columns.withIndex()) { val maxWidth = column.maxWidth val columnIndex = column.modelIndex for (row in 0 until rowCount) { val width = getCellDataWidth(row, columnIndex) + separatorSize preferredWidth[index] = preferredWidth[index].coerceAtLeast(width) if (preferredWidth[index] >= maxWidth) break } } return preferredWidth } private fun JTable.getCellDataWidth(row: Int, column: Int): Int { val renderer = getCellRenderer(row, column) val cellWidth = prepareRenderer(renderer, row, column).preferredSize.width return cellWidth + intercellSpacing.width }
apache-2.0
a62d9f4f9cf071ff2d04f1a79d5b42ad
34
82
0.716667
4.548736
false
false
false
false
Bastien7/Kotlin-presentation
KotlinApp/src/main/kotlin/kotlinApp/controllers/TopicController.kt
1
1391
package kotlinApp.controllers import kotlinApp.model.Message import kotlinApp.model.Topic import kotlinApp.repositories.TopicRepository import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.UUID @RestController @RequestMapping("/topic") open class TopicController(val topicRepository: TopicRepository) { @GetMapping open fun getTopics(): List<Topic> = topicRepository.findAll() @GetMapping("/{id}") open fun getTopics(@PathVariable("id") id: String): List<Topic> = topicRepository.findAll().filter { it.id == id } @PostMapping open fun createTopic(@RequestBody question: Question) = topicRepository.save(Topic(question = question.content)) @PutMapping open fun updateTopic(@RequestBody topic: Topic) = topicRepository.save(topic) @DeleteMapping open fun deleteTopic(@RequestParam id: String) = topicRepository.delete(id) data class Question(val content: String = "") }
mit
2f51e2452aeb3b0c11f9235b5b3722e8
36.594595
115
0.818116
4.177177
false
false
false
false
JuliusKunze/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeUtils.kt
1
2691
/* * Copyright 2010-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.kotlin.native.interop.gen val kotlinKeywords = setOf( "as", "break", "class", "continue", "do", "dynamic", "else", "false", "for", "fun", "if", "in", "interface", "is", "null", "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "val", "var", "when", "while", // While not technically keywords, those shall be escaped as well. "_", "__", "___" ) /** * The expression written in native language. */ typealias NativeExpression = String /** * The expression written in Kotlin. */ typealias KotlinExpression = String /** * For this identifier constructs the string to be parsed by Kotlin as `SimpleName` * defined [here](https://kotlinlang.org/docs/reference/grammar.html#SimpleName). */ fun String.asSimpleName(): String = if (this in kotlinKeywords) { "`$this`" } else { this } /** * Returns the expression to be parsed by Kotlin as string literal with given contents, * i.e. transforms `foo$bar` to `"foo\$bar"`. */ fun String.quoteAsKotlinLiteral(): KotlinExpression { val sb = StringBuilder() sb.append('"') this.forEach { c -> val escaped = when (c) { in 'a' .. 'z', in 'A' .. 'Z', in '0' .. '9', '_', '@', ':', '{', '}', '=', '[', ']', '^', '#', '*' -> c.toString() '$' -> "\\$" else -> "\\u" + "%04X".format(c.toInt()) // TODO: improve result readability by preserving more characters. } sb.append(escaped) } sb.append('"') return sb.toString() } fun block(header: String, lines: Iterable<String>) = block(header, lines.asSequence()) fun block(header: String, lines: Sequence<String>) = sequenceOf("$header {") + lines.map { " $it" } + sequenceOf("}") val annotationForUnableToImport get() = "@Deprecated(${"Unable to import this declaration".quoteAsKotlinLiteral()}, level = DeprecationLevel.ERROR)" fun String.applyToStrings(vararg arguments: String) = "${this}(${arguments.joinToString { it.quoteAsKotlinLiteral() }})"
apache-2.0
cc5059b3546b8f2689297e761f7427df
33.063291
126
0.624303
3.866379
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/evaluate/maxValueInt.kt
2
891
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME @Retention(AnnotationRetention.RUNTIME) annotation class Ann( val p1: Int, val p2: Int, val p4: Long, val p5: Int ) @Ann( p1 = java.lang.Integer.MAX_VALUE + 1, p2 = 1 + 1, p4 = 1 + 1, p5 = 1.toInt() + 1.toInt() ) class MyClass fun box(): String { val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!! if (annotation.p1 != -2147483648) return "fail 1, expected = ${-2147483648}, actual = ${annotation.p1}" if (annotation.p2 != 2) return "fail 2, expected = ${2}, actual = ${annotation.p2}" if (annotation.p4 != 2.toLong()) return "fail 4, expected = ${2}, actual = ${annotation.p4}" if (annotation.p5 != 2) return "fail 5, expected = ${2}, actual = ${annotation.p5}" return "OK" }
apache-2.0
4411d38f68fceb286ac6d6bac6451e3e
30.821429
107
0.613917
3.228261
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/arrayConvention/simpleAccessWithLambdaInClass.kt
3
528
// FILE: 1.kt // WITH_RUNTIME package test var res = 1 class A { inline operator fun Int.get(z: Int, p: () -> Int) = this + z + p() inline operator fun Int.set(z: Int, p: () -> Int, l: Int) { res = this + z + p() + l } } // FILE: 2.kt import test.* fun box(): String { val z = 1; with(A()) { val p = z[2, { 3 }] if (p != 6) return "fail 1: $p" val captured = 3; z[2, { captured }] = p if (res != 12) return "fail 2: $res" } return "OK" }
apache-2.0
f7b5845de51d84804cebe8da477f4b24
13.27027
70
0.450758
2.808511
false
true
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/commands/DropRatesCommand.kt
1
4020
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.commands import co.aikar.commands.BaseCommand import co.aikar.commands.annotation.CommandAlias import co.aikar.commands.annotation.CommandPermission import co.aikar.commands.annotation.Dependency import co.aikar.commands.annotation.Description import co.aikar.commands.annotation.Subcommand import com.tealcube.minecraft.bukkit.mythicdrops.api.items.strategies.DropStrategyManager import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicDropTracker import com.tealcube.minecraft.bukkit.mythicdrops.sendMythicMessage import org.bukkit.command.CommandSender import java.math.RoundingMode import java.text.DecimalFormat @CommandAlias("mythicdrops|md") class DropRatesCommand : BaseCommand() { companion object { private val decimalFormat = DecimalFormat("###.###%").apply { RoundingMode.CEILING } } @field:Dependency lateinit var dropStrategyManager: DropStrategyManager @field:Dependency lateinit var settingsManager: SettingsManager @Description("Prints a list of the calculated drop rate and the real drop rate being experienced") @Subcommand("rates") @CommandPermission("mythicdrops.command.rates") fun debugCommand(sender: CommandSender) { sender.sendMythicMessage("&6=== MythicDrops Drop Rates ===") sender.sendMythicMessage("Item Type - Rate - Expected") sender.sendMythicMessage("---------------------------") val dropStrategy = dropStrategyManager.getById(settingsManager.configSettings.drops.strategy) ?: return displayRate(sender, "Tiered Items", MythicDropTracker.tieredItemRate(), dropStrategy.tieredItemChance) displayRate(sender, "Custom Items", MythicDropTracker.customItemRate(), dropStrategy.customItemChance) displayRate(sender, "Socket Gems", MythicDropTracker.socketGemRate(), dropStrategy.socketGemChance) displayRate( sender, "Unidentified Items", MythicDropTracker.unidentifiedItemRate(), dropStrategy.unidentifiedItemChance ) displayRate(sender, "Identity Tomes", MythicDropTracker.identityTomeRate(), dropStrategy.identityTomeChance) displayRate( sender, "Socket Extenders", MythicDropTracker.socketExtenderRate(), dropStrategy.socketExtenderChance ) } private fun displayRate(sender: CommandSender, type: String, rate: Double, expected: Double) { sender.sendMythicMessage( "$type - %rate% - %expected%", listOf( "%rate%" to decimalFormat.format(rate), "%expected%" to decimalFormat.format(expected) ) ) } }
mit
12cafab1a585b97116eecca53b5290f1
44.681818
116
0.727861
4.774347
false
false
false
false
craftsmenlabs/gareth-jvm
gareth-execution-ri/src/main/kotlin/org/craftsmenlabs/gareth/execution/services/DefinitionFactory.kt
1
1943
package org.craftsmenlabs.gareth.execution.services import org.springframework.beans.factory.BeanExpressionException import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.stereotype.Service import java.lang.reflect.Constructor @Service open class DefinitionFactory @Autowired constructor(val applicationContext: ApplicationContext) { fun getInstanceForClass(clazz: Class<*>): Any = getDefinitionFromContext(clazz) ?: createDefinitionByReflection(clazz) private fun createDefinitionByReflection(clazz: Class<*>): Any { var constructor: Constructor<*>? = null var declaringClassInstance: Any? = null val memberClass = clazz.isMemberClass val requiredConstructorArguments = if (memberClass) 1 else 0 // if (memberClass) { declaringClassInstance = getInstanceForClass(clazz.declaringClass) } for (declaredConstructor in clazz.declaredConstructors) { if (declaredConstructor.genericParameterTypes.size == requiredConstructorArguments) { constructor = declaredConstructor break } } // If a valid constructor is available if (null != constructor) { val instance: Any constructor.isAccessible = true if (memberClass) { instance = constructor.newInstance(declaringClassInstance) } else { instance = constructor.newInstance() } return instance } throw InstantiationException(String.format("Class %s has no zero argument argument constructor", clazz)) } private fun getDefinitionFromContext(clazz: Class<*>): Any? { try { return applicationContext.getBean(clazz) } catch (e: BeanExpressionException) { return null } } }
gpl-2.0
579fa09da5ffd610b0ac2f092e0968dd
35
122
0.673186
5.519886
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/internal/CompletionQuality.kt
5
17306
// 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. @file:Suppress("DEPRECATION") // declared for import com.intellij.codeInsight.completion.CompletionProgressIndicator package com.intellij.internal import com.google.gson.Gson import com.intellij.codeInsight.completion.CodeCompletionHandlerBase import com.intellij.codeInsight.completion.CompletionProgressIndicator import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.RunContentManager import com.intellij.ide.util.scopeChooser.ScopeChooserCombo import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.fileTypes.NativeFileType import com.intellij.openapi.fileTypes.impl.FileTypeRenderer import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.ui.ScrollingUtil import com.intellij.ui.layout.* import com.intellij.util.ui.UIUtil import java.io.File import java.util.* import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.JLabel import kotlin.collections.HashMap private data class CompletionTime(var cnt: Int, var time: Long) private data class CompletionQualityParameters( val project: Project, val path: String, val editor: Editor, val text: String, val startIndex: Int, val word: String, val stats: CompletionStats, val indicator: ProgressIndicator, val completionTime : CompletionTime = CompletionTime(0, 0)) private const val RANK_EXCESS_LETTERS: Int = -2 private const val RANK_NOT_FOUND: Int = 1000000000 private const val CAN_NOT_COMPLETE_WORD = 1000000000 private val interestingRanks : IntArray = intArrayOf(0, 1, 3) private val interestingCharsToFirsts: IntArray = intArrayOf(1, 3) private const val saveWordsToFile = true private val wordsFileName = "${System.getProperty("user.dir")}/completionQualityAllWords.txt" private val saveResultToFile = "${System.getProperty("user.dir")}/result.json" private const val doProcessingWords = true private const val checkAfterDotOnly = true internal class CompletionQualityStatsAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) as? EditorImpl val project = e.getData(CommonDataKeys.PROJECT) ?: return val dialog = CompletionQualityDialog(project, editor) if (!dialog.showAndGet()) return val fileType = dialog.fileType val stats = CompletionStats(System.currentTimeMillis()) val task = object : Task.Backgroundable(project, "Emulating completion", true) { override fun run(indicator: ProgressIndicator) { val files = (if (dialog.scope is GlobalSearchScope) { lateinit var collectionFiles: Collection<VirtualFile> runReadAction { collectionFiles = FileTypeIndex.getFiles(fileType, dialog.scope as GlobalSearchScope) } collectionFiles } else { (dialog.scope as LocalSearchScope).virtualFiles.asList() }).sortedBy { it.path } // sort files to have same order each run // map to count words frequency // we don't want to complete the same words more than twice val wordsFrequencyMap = HashMap<String, Int>() val fileWithAllWords = File(wordsFileName) fileWithAllWords.writeText("") for (file in files) { if (indicator.isCanceled) { stats.finished = false return } indicator.text = file.path lateinit var document: Document lateinit var completionAttempts: List<Pair<Int, String>> runReadAction { document = FileDocumentManager.getInstance().getDocument(file) ?: throw Exception("Can't get document: ${file.name}") val psiFile = PsiManager.getInstance(project).findFile(file) ?: throw Exception("Can't find file: ${file.name}") completionAttempts = getCompletionAttempts(psiFile, wordsFrequencyMap) } if (saveWordsToFile) { fileWithAllWords.appendText("${file.path}\n") fileWithAllWords.appendText("${completionAttempts.toList().size}\n") for ((offset, word) in completionAttempts) { val start = StringUtil.offsetToLineColumn(document.text, offset + 1) val line = start.line val startCol = start.column val endCol = startCol + word.length fileWithAllWords.appendText("$word ${line + 1} ${startCol + 1} ${line + 1} ${endCol + 1}\n") } } if (!doProcessingWords) { continue } if (completionAttempts.isNotEmpty()) { val application = ApplicationManager.getApplication() lateinit var newEditor: Editor application.invokeAndWait({ val descriptor = OpenFileDescriptor(project, file) newEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true) ?: throw Exception("Can't open text editor for file: ${file.name}") }, ModalityState.NON_MODAL) val text = document.text try { for ((offset, word) in completionAttempts) { if (indicator.isCanceled) { break } val lineAndCol = StringUtil.offsetToLineColumn(text, offset + 1) val line = lineAndCol.line + 1 val col = lineAndCol.column + 1 evalCompletionAt(CompletionQualityParameters(project, "${file.path}:$line:$col", newEditor, text, offset, word, stats, indicator)) } } finally { application.invokeAndWait { runWriteAction { document.setText(text) FileDocumentManager.getInstance().saveDocument(document) } } } stats.totalFiles += 1 } } stats.finished = true val gson = Gson() UIUtil.invokeLaterIfNeeded { createConsoleAndPrint(project, gson.toJson(stats)) } } } ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, BackgroundableProcessIndicator(task)) } private fun createConsoleAndPrint(project: Project, text: String) { val consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project) val console = consoleBuilder.console val descriptor = RunContentDescriptor(console, null, console.component, "Completion Quality Statistics") RunContentManager.getInstance(project).showRunContent(DefaultRunExecutor.getRunExecutorInstance(), descriptor) console.print(text, ConsoleViewContentType.NORMAL_OUTPUT) File(saveResultToFile).writeText(text) } private fun isAfterDot(el: PsiElement) : Boolean { val prev = PsiTreeUtil.prevVisibleLeaf(el) return prev != null && prev.text == "." } // Find offsets to words and words on which we want to try completion private fun getCompletionAttempts(file: PsiFile, wordSet: HashMap<String, Int>): List<Pair<Int, String>> { val maxWordFrequency = 2 val res = ArrayList<Pair<Int, String>>() val text = file.text for (range in StringUtil.getWordIndicesIn(text)) { val startIndex = range.startOffset if (startIndex != -1) { val el = file.findElementAt(startIndex) if (el != null && el !is PsiComment) { if (checkAfterDotOnly && !isAfterDot(el)) { continue } val word = range.substring(text) if (!word.isEmpty() && wordSet.getOrDefault(word, 0) < maxWordFrequency) { res.add(Pair(startIndex - 1, word)) wordSet[word] = wordSet.getOrDefault(word, 0) + 1 } } } } return res } private fun evalCompletionAt(params: CompletionQualityParameters) { with(params) { val maxChars = 10 val cache = arrayOfNulls<Pair<Int, Int>>(maxChars + 1) // (typed letters, rank, total) val ranks = arrayListOf<Triple<Int, Int, Int>>() for (charsTyped in interestingRanks) { val (rank, total) = findCorrectElementRank(charsTyped, params) ranks.add(Triple(charsTyped, rank, total)) cache[charsTyped] = Pair(rank, total) if (indicator.isCanceled) { return } } val charsToFirsts = arrayListOf<Pair<Int, Int>>() for (n in interestingCharsToFirsts) { charsToFirsts.add(Pair(n, calcCharsToFirstN(n, maxChars, cache, params))) } stats.completions.add( getHashMapCompletionInfo(path, startIndex, word, ranks, charsToFirsts, completionTime.cnt, completionTime.time)) } } // Calculate number of letters needed to type to have necessary word in top N private fun calcCharsToFirstN(N: Int, maxChars: Int, cache: Array<Pair<Int, Int>?>, params: CompletionQualityParameters): Int { with (params) { for (charsTyped in 0 .. maxChars) { if (indicator.isCanceled) { return CAN_NOT_COMPLETE_WORD } val (rank, total) = cache[charsTyped] ?: findCorrectElementRank(charsTyped, params) if (cache[charsTyped] == null) { cache[charsTyped] = Pair(rank, total) } if (rank == RANK_EXCESS_LETTERS) { return CAN_NOT_COMPLETE_WORD } if (rank < N) { return charsTyped } } return CAN_NOT_COMPLETE_WORD } } // Find position necessary word in lookup list after 'charsTyped' typed letters // Return pair of this position and total number of words in completion lookup private fun findCorrectElementRank(charsTyped: Int, params: CompletionQualityParameters): Pair<Int, Int> { with (params) { if (charsTyped > word.length) { return Pair(RANK_EXCESS_LETTERS, 0) } if (charsTyped == word.length) { return Pair(0, 1) } // text with prefix of word of charsTyped length in completion site val newText = text.substring(0, startIndex + 1 + charsTyped) + text.substring(startIndex + word.length + 1) var result = RANK_NOT_FOUND var total = 0 ApplicationManager.getApplication().invokeAndWait({ try { fun getLookupItems() : List<LookupElement>? { var lookupItems: List<LookupElement>? = null CommandProcessor.getInstance().executeCommand(project, { WriteAction.run<Exception> { editor.document.setText(newText) FileDocumentManager.getInstance().saveDocument(editor.document) editor.caretModel.moveToOffset(startIndex + 1 + charsTyped) editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) } val handler = object : CodeCompletionHandlerBase(CompletionType.BASIC, false, false, true) { @Suppress("DEPRECATION") override fun completionFinished(indicator: CompletionProgressIndicator, hasModifiers: Boolean) { super.completionFinished(indicator, hasModifiers) lookupItems = indicator.lookup.items } override fun isTestingCompletionQualityMode() = true } handler.invokeCompletion(project, editor, 1) }, null, null, editor.document) val lookup = LookupManager.getActiveLookup(editor) if (lookup != null && lookup is LookupImpl) { ScrollingUtil.moveUp(lookup.list, 0) lookup.refreshUi(false, false) lookupItems = lookup.items lookup.hideLookup(true) } return lookupItems } val timeStart = System.currentTimeMillis() val lookupItems = getLookupItems() if (lookupItems != null) { result = lookupItems.indexOfFirst { it.lookupString == word } if (result == -1) { result = RANK_NOT_FOUND } total = lookupItems.size } completionTime.cnt += 1 completionTime.time += System.currentTimeMillis() - timeStart } catch (e: Throwable) { LOG.error(e) } }, ModalityState.NON_MODAL) return Pair(result, total) } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null e.presentation.text = "Completion Quality Statistics" } } class CompletionQualityDialog(project: Project, editor: Editor?) : DialogWrapper(project) { private var fileTypeCombo: JComboBox<FileType> private var scopeChooserCombo: ScopeChooserCombo var fileType: FileType get() = fileTypeCombo.selectedItem as FileType private set(_) {} var scope: SearchScope? get() = scopeChooserCombo.selectedScope private set(_) {} init { title = "Completion Quality Statistics" fileTypeCombo = createFileTypesCombo() scopeChooserCombo = ScopeChooserCombo(project, false, true, "") Disposer.register(disposable, scopeChooserCombo) if (editor != null) { PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.let { fileTypeCombo.selectedItem = it.fileType } } init() } private fun createFileTypesCombo(): ComboBox<FileType> { val fileTypes = FileTypeManager.getInstance().registeredFileTypes Arrays.sort(fileTypes) { ft1, ft2 -> when { (ft1 == null) -> 1 (ft2 == null) -> -1 else -> ft1.description.compareTo(ft2.description, ignoreCase = true) } } val model = DefaultComboBoxModel<FileType>() for (type in fileTypes) { if (!type.isReadOnly && type !== FileTypes.UNKNOWN && type !is NativeFileType) { model.addElement(type) } } val combo = ComboBox<FileType>(model) combo.renderer = FileTypeRenderer() return combo } override fun createCenterPanel(): JComponent { return panel { row(label = JLabel("File type:")) { fileTypeCombo() } row(label = JLabel("Scope:")) { scopeChooserCombo() } } } } private fun getHashMapCompletionInfo(path: String, offset: Int, word: String, ranks: ArrayList<Triple<Int, Int, Int>>, charsToFirsts: ArrayList<Pair<Int, Int>>, callsCount: Int, totalTime: Long) : HashMap<String, Any> { val id = path.hashCode() val result = hashMapOf<String, Any>() result["id"] = id result["path"] = path result["offset"] = offset result["word"] = word for ((chars, rank, total) in ranks) { result["rank$chars"] = rank result["total$chars"] = total } for ((n, chars) in charsToFirsts) { result["charsToFirst$n"] = chars } result["callsCount"] = callsCount result["totalTime"] = totalTime return result } private data class CompletionStats(val timestamp: Long) { var finished: Boolean = false val completions = arrayListOf<HashMap<String, Any>>() var totalFiles = 0 } private val LOG = Logger.getInstance(CompletionQualityStatsAction::class.java)
apache-2.0
927bd590a61053949c5a79b252a01893
35.512658
146
0.662545
4.648402
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinElementDescriptionProvider.kt
1
10125
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.findUsages import com.intellij.codeInsight.highlighting.HighlightUsagesDescriptionLocation import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringDescriptionLocation import com.intellij.usageView.UsageViewLongNameLocation import com.intellij.usageView.UsageViewShortNameLocation import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.KotlinIndependentBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.util.string.collapseSpaces import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType open class KotlinElementDescriptionProviderBase : ElementDescriptionProvider { private tailrec fun KtNamedDeclaration.parentForFqName(): KtNamedDeclaration? { val parent = getStrictParentOfType<KtNamedDeclaration>() ?: return null if (parent is KtProperty && parent.isLocal) return parent.parentForFqName() return parent } private fun KtNamedDeclaration.name() = nameAsName ?: Name.special("<no name provided>") private fun KtNamedDeclaration.fqName(): FqNameUnsafe { containingClassOrObject?.let { if (it is KtObjectDeclaration && it.isCompanion()) { return it.fqName().child(name()) } return FqNameUnsafe("${it.name()}.${name()}") } val internalSegments = generateSequence(this) { it.parentForFqName() } .filterIsInstance<KtNamedDeclaration>() .map { it.name ?: "<no name provided>" } .toList() .asReversed() val packageSegments = containingKtFile.packageFqName.pathSegments() return FqNameUnsafe((packageSegments + internalSegments).joinToString(".")) } private fun KtTypeReference.renderShort(): String { return accept( object : KtVisitor<String, Unit>() { private val visitor get() = this override fun visitTypeReference(typeReference: KtTypeReference, data: Unit): String { val typeText = typeReference.typeElement?.accept(this, data) ?: "???" return if (typeReference.hasParentheses()) "($typeText)" else typeText } override fun visitDynamicType(type: KtDynamicType, data: Unit) = type.text override fun visitFunctionType(type: KtFunctionType, data: Unit): String { return buildString { type.receiverTypeReference?.let { append(it.accept(visitor, data)).append('.') } type.parameters.joinTo(this, prefix = "(", postfix = ")") { it.accept(visitor, data) } append(" -> ") append(type.returnTypeReference?.accept(visitor, data) ?: "???") } } override fun visitNullableType(nullableType: KtNullableType, data: Unit): String { val innerTypeText = nullableType.innerType?.accept(this, data) ?: return "???" return "$innerTypeText?" } override fun visitSelfType(type: KtSelfType, data: Unit) = type.text override fun visitUserType(type: KtUserType, data: Unit): String { return buildString { append(type.referencedName ?: "???") val arguments = type.typeArguments if (arguments.isNotEmpty()) { arguments.joinTo(this, prefix = "<", postfix = ">") { it.typeReference?.accept(visitor, data) ?: it.text } } } } override fun visitParameter(parameter: KtParameter, data: Unit) = parameter.typeReference?.accept(this, data) ?: "???" }, Unit ) } //TODO: Implement in FIR protected open val PsiElement.isRenameJavaSyntheticPropertyHandler get() = false protected open val PsiElement.isRenameKotlinPropertyProcessor get() = false override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? { val shouldUnwrap = location !is UsageViewShortNameLocation && location !is UsageViewLongNameLocation val targetElement = if (shouldUnwrap) element.unwrapped ?: element else element fun elementKind() = when (targetElement) { is KtClass -> if (targetElement.isInterface()) KotlinIndependentBundle.message("find.usages.interface") else KotlinIndependentBundle.message("find.usages.class") is KtObjectDeclaration -> if (targetElement.isCompanion()) KotlinIndependentBundle.message("find.usages.companion.object") else KotlinIndependentBundle.message("find.usages.object") is KtNamedFunction -> KotlinIndependentBundle.message("find.usages.function") is KtPropertyAccessor -> KotlinIndependentBundle.message( "find.usages.for.property", (if (targetElement.isGetter) KotlinIndependentBundle.message("find.usages.getter") else KotlinIndependentBundle.message("find.usages.setter")) ) + " " is KtFunctionLiteral -> KotlinIndependentBundle.message("find.usages.lambda") is KtPrimaryConstructor, is KtSecondaryConstructor -> KotlinIndependentBundle.message("find.usages.constructor") is KtProperty -> if (targetElement.isLocal) KotlinIndependentBundle.message("find.usages.variable") else KotlinIndependentBundle.message("find.usages.property") is KtTypeParameter -> KotlinIndependentBundle.message("find.usages.type.parameter") is KtParameter -> KotlinIndependentBundle.message("find.usages.parameter") is KtDestructuringDeclarationEntry -> KotlinIndependentBundle.message("find.usages.variable") is KtTypeAlias -> KotlinIndependentBundle.message("find.usages.type.alias") is KtLabeledExpression -> KotlinIndependentBundle.message("find.usages.label") is KtImportAlias -> KotlinIndependentBundle.message("find.usages.import.alias") is KtLightClassForFacade -> KotlinIndependentBundle.message("find.usages.facade.class") else -> { //TODO Implement in FIR when { targetElement.isRenameJavaSyntheticPropertyHandler -> KotlinIndependentBundle.message("find.usages.property") targetElement.isRenameKotlinPropertyProcessor -> KotlinIndependentBundle.message("find.usages.property.accessor") else -> null } } } val namedElement = if (targetElement is KtPropertyAccessor) { targetElement.parent as? KtProperty } else targetElement as? PsiNamedElement @Suppress("FoldInitializerAndIfToElvis") if (namedElement == null) { return if (targetElement is KtElement) "'" + StringUtil.shortenTextWithEllipsis( targetElement.text.collapseSpaces(), 53, 0 ) + "'" else null } if (namedElement.language != KotlinLanguage.INSTANCE) return null return when (location) { is UsageViewTypeLocation -> elementKind() is UsageViewShortNameLocation, is UsageViewLongNameLocation -> namedElement.name is RefactoringDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null val renderFqName = location.includeParent() && namedElement !is KtTypeParameter && namedElement !is KtParameter && namedElement !is KtConstructor<*> @Suppress("HardCodedStringLiteral") val desc = when (namedElement) { is KtFunction -> { val baseText = buildString { append(namedElement.name ?: "") namedElement.valueParameters.joinTo(this, prefix = "(", postfix = ")") { (if (it.isVarArg) "vararg " else "") + (it.typeReference?.renderShort() ?: "") } namedElement.receiverTypeReference?.let { append(" on ").append(it.renderShort()) } } val parentFqName = if (renderFqName) namedElement.fqName().parent() else null if (parentFqName?.isRoot != false) baseText else "${parentFqName.asString()}.$baseText" } else -> (if (renderFqName) namedElement.fqName().asString() else namedElement.name) ?: "" } "$kind ${CommonRefactoringUtil.htmlEmphasize(desc)}" } is HighlightUsagesDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null "$kind ${namedElement.name}" } else -> null } } }
apache-2.0
5a180e33cf10eb7f0772439dbe0cb0f1
49.879397
158
0.618963
5.835735
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionReference.kt
12
4865
// 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. package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions import com.intellij.lang.java.beans.PropertyKind import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrSuperReferenceResolver.resolveSuperExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrThisReferenceResolver.resolveThisExpression import org.jetbrains.plugins.groovy.lang.psi.util.getRValue import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic import org.jetbrains.plugins.groovy.lang.psi.util.isPropertyName import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference import org.jetbrains.plugins.groovy.lang.resolve.processors.AccessorAwareProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.AccessorProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind.* import java.util.* abstract class GrReferenceExpressionReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) { override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> { require(!incomplete) val staticResults = element.staticReference.resolve(incomplete) if (staticResults.isNotEmpty()) { return staticResults } return doResolveNonStatic() } protected open fun doResolveNonStatic(): Collection<GroovyResolveResult> { val expression = element val name = expression.referenceName ?: return emptyList() val kinds = expression.resolveKinds() val processor = buildProcessor(name, expression, kinds) GrReferenceResolveRunner(expression, processor).resolveReferenceExpression() return processor.results } protected abstract fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> } class GrRValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) { override fun doResolveNonStatic(): Collection<GroovyResolveResult> { return element.handleSpecialCases() ?: super.doResolveNonStatic() } override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { return rValueProcessor(name, place, kinds) } } class GrLValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) { override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { val rValue = requireNotNull(element.getRValue()) return lValueProcessor(name, place, kinds, rValue) } } private fun GrReferenceExpression.handleSpecialCases(): Collection<GroovyResolveResult>? { when (referenceNameElement?.node?.elementType) { GroovyElementTypes.KW_THIS -> return resolveThisExpression(this) GroovyElementTypes.KW_SUPER -> return resolveSuperExpression(this) GroovyElementTypes.KW_CLASS -> { if (!isCompileStatic(this) && qualifier?.type == null) { return emptyList() } } } return null } fun GrReferenceExpression.resolveKinds(): Set<GroovyResolveKind> { return resolveKinds(isQualified) } fun resolveKinds(qualified: Boolean): Set<GroovyResolveKind> { return if (qualified) { EnumSet.of(FIELD, PROPERTY, VARIABLE) } else { EnumSet.of(FIELD, PROPERTY, VARIABLE, BINDING) } } fun rValueProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { val accessorProcessors = if (name.isPropertyName()) listOf( AccessorProcessor(name, PropertyKind.GETTER, emptyList(), place), AccessorProcessor(name, PropertyKind.BOOLEAN_GETTER, emptyList(), place) ) else { emptyList() } return AccessorAwareProcessor(name, place, kinds, accessorProcessors) } fun lValueProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>, argument: Argument?): GrResolverProcessor<*> { val accessorProcessors = if (name.isPropertyName()) { listOf(AccessorProcessor(name, PropertyKind.SETTER, argument?.let(::listOf), place)) } else { emptyList() } return AccessorAwareProcessor(name, place, kinds, accessorProcessors) }
apache-2.0
96665377805c5c7818458f2ecd99fd97
42.053097
140
0.788284
4.57667
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSourceEntityImpl.kt
1
9407
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.util.* import java.util.UUID import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildSourceEntityImpl(val dataSource: ChildSourceEntityData) : ChildSourceEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceEntity::class.java, ChildSourceEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val data: String get() = dataSource.data override val parentEntity: SourceEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildSourceEntityData?) : ModifiableWorkspaceEntityBase<ChildSourceEntity>(), ChildSourceEntity.Builder { constructor() : this(ChildSourceEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildSourceEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field ChildSourceEntity#data should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildSourceEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildSourceEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildSourceEntity this.entitySource = dataSource.entitySource this.data = dataSource.data if (parents != null) { this.parentEntity = parents.filterIsInstance<SourceEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var parentEntity: SourceEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as SourceEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as SourceEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): ChildSourceEntityData = result ?: super.getEntityData() as ChildSourceEntityData override fun getEntityClass(): Class<ChildSourceEntity> = ChildSourceEntity::class.java } } class ChildSourceEntityData : WorkspaceEntityData<ChildSourceEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSourceEntity> { val modifiable = ChildSourceEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildSourceEntity { return getCached(snapshot) { val entity = ChildSourceEntityImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildSourceEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildSourceEntity(data, entitySource) { this.parentEntity = parents.filterIsInstance<SourceEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(SourceEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSourceEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSourceEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
de2f9806a3deab650ca694a537e89d1d
35.603113
150
0.699585
5.308691
false
false
false
false
evanchooly/gridfs-fs-provider
core/src/test/kotlin/com/antwerkz/gridfs/GridFSFileSystemProviderTest.kt
1
2788
package com.antwerkz.gridfs import com.mongodb.MongoClient import com.mongodb.client.gridfs.GridFSBuckets import org.testng.Assert import org.testng.Assert.assertEquals import org.testng.Assert.assertNotNull import org.testng.annotations.Test import java.io.ByteArrayOutputStream import java.net.MalformedURLException import java.net.URI import java.nio.ByteBuffer import java.nio.file.Files class GridFSFileSystemProviderTest { companion object { val provider = GridFSFileSystemProvider(MongoClient()) } @Test fun testByteChannelReads() { val url = "gridfs://localhost:27017/gridfs.archives/some/path/to/file" val path = provider.getPath(URI(url)) assertNotNull(path) val mongoClient = MongoClient("localhost") val database = mongoClient.getDatabase("gridfs") database.drop() val gridFSBucket = GridFSBuckets.create(database, "archives") gridFSBucket.uploadFromStream("/some/path/to/file", "hello world".byteInputStream()) assertEquals(String(Files.readAllBytes(path)), "hello world") } @Test fun testByteChannelWrites() { val url = "gridfs://localhost:27017/gridfs.archives/some/path/to/file" val path = provider.getPath(URI(url)) assertNotNull(path) val mongoClient = MongoClient("localhost") val database = mongoClient.getDatabase("gridfs") database.drop() val gridFSBucket = GridFSBuckets.create(database, "archives") val channel = Files.newByteChannel(path) channel.write(ByteBuffer.wrap("hello world".toByteArray())) val bytes = ByteArrayOutputStream() gridFSBucket.downloadToStreamByName("/some/path/to/file", bytes) assertEquals(bytes.toString(), "hello world") } @Test fun testCache() { val path1 = provider.getPath(URI("gridfs://localhost:27017/movies.archives/some/path/to/file")) val path2 = provider.getPath(URI("gridfs://localhost:27017/movies.archives/some/path/to/file")) val path3 = provider.getPath(URI("gridfs://localhost:27017/movies.archives/some/other/path/to/file")) assertEquals(path1.fileSystem, path2.fileSystem) assertEquals(path1.fileSystem, path3.fileSystem) } @Test fun testUrlParsing() { val path = provider.getPath(URI("gridfs://localhost:27017/movies.archives/some/path/to/file")) as GridFSPath Assert.assertEquals(path.fileSystem.bucketName, "archives") } @Test(expectedExceptions = arrayOf(MalformedURLException::class)) fun testBadUrlParsing() { val path = provider.getPath(URI("gridfs://localhost:27017/movies/archives/some/path/to/file")) as GridFSPath Assert.assertEquals(path.fileSystem.bucketName, "archives") } }
apache-2.0
131f4aa239905543d60f78387dc8b30f
34.303797
116
0.703372
4.276074
false
true
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/VideoViewModel.kt
1
3974
package com.kickstarter.viewmodels import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.Project import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.VideoActivity import rx.Observable import rx.subjects.BehaviorSubject import java.util.concurrent.TimeUnit interface VideoViewModel { interface Outputs { /** Emits the url of the video for the player. */ fun preparePlayerWithUrl(): Observable<String> fun preparePlayerWithUrlAndPosition(): Observable<Pair<String, Long>> } interface Inputs { fun onVideoStarted(videoLength: Long, videoPosition: Long) fun onVideoCompleted(videoLength: Long, videoPosition: Long) } class ViewModel(environment: Environment) : ActivityViewModel<VideoActivity>(environment), Inputs, Outputs { private val preparePlayerWithUrl = BehaviorSubject.create<String>() private val preparePlayerWithUrlAndPosition = BehaviorSubject.create<Pair<String, Long>>() private val onVideoStarted = BehaviorSubject.create<Pair<Long, Long>>() private val onVideoCompleted = BehaviorSubject.create<Pair<Long, Long>>() @JvmField val outputs: Outputs = this @JvmField val inputs: Inputs = this override fun preparePlayerWithUrl(): Observable<String> { return preparePlayerWithUrl } override fun preparePlayerWithUrlAndPosition(): Observable<Pair<String, Long>> { return preparePlayerWithUrlAndPosition } override fun onVideoStarted(videoLength: Long, videoPosition: Long) { return onVideoStarted.onNext(Pair(videoLength, videoPosition)) } override fun onVideoCompleted(videoLength: Long, videoPosition: Long) { return onVideoCompleted.onNext(Pair(videoLength, videoPosition)) } init { intent() .map { Pair(it?.getStringExtra(IntentKey.VIDEO_URL_SOURCE), it?.getLongExtra(IntentKey.VIDEO_SEEK_POSITION, 0) ?: 0) } .filter { ObjectUtils.isNotNull(it.first) } .map { Pair(requireNotNull(it.first), it.second) } .distinctUntilChanged() .take(1) .compose(bindToLifecycle()) .subscribe { preparePlayerWithUrlAndPosition.onNext(it) } val project = intent() .map { it.getParcelableExtra(IntentKey.PROJECT) as Project? } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } project.map { it.video() } .filter { ObjectUtils.isNotNull(it) } .map { it?.hls() ?: it?.high() } .distinctUntilChanged() .take(1) .compose(bindToLifecycle()) .subscribe { preparePlayerWithUrl.onNext(it) } Observable.combineLatest(project, onVideoStarted) { p, u -> Pair(p, u) }.distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackVideoStarted( it.first, TimeUnit.MILLISECONDS.toSeconds(it.second.first), TimeUnit.MILLISECONDS.toSeconds(it.second.second) ) } Observable.combineLatest(project, onVideoCompleted) { p, u -> Pair(p, u) }.distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackVideoCompleted( it.first, TimeUnit.MILLISECONDS.toSeconds(it.second.first), TimeUnit.MILLISECONDS.toSeconds(it.second.second) ) } } } }
apache-2.0
6dfac42ea97b99546517e934c75f7715
38.346535
134
0.603422
5.181226
false
false
false
false
mdaniel/intellij-community
platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt
1
12739
// 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. package com.intellij.dvcs.ignore import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.projectView.actions.MarkExcludeRootAction import com.intellij.ide.util.PropertiesComponent import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.runModalTask import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderEnumerator import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FilesProcessorImpl import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.util.Alarm import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity import java.util.* private val LOG = logger<IgnoredToExcludedSynchronizer>() private val excludeAction = object : MarkExcludeRootAction() { fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) } } /** * Shows [EditorNotifications] in .ignore files with suggestion to exclude ignored directories. * Silently excludes them if [VcsConfiguration.MARK_IGNORED_AS_EXCLUDED] is enabled. * * Not internal service. Can be used directly in related modules. */ @Service class IgnoredToExcludedSynchronizer(project: Project) : FilesProcessorImpl(project, project) { private val queue = MergingUpdateQueue("IgnoredToExcludedSynchronizer", 1000, true, null, this, null, Alarm.ThreadToUse.POOLED_THREAD) init { val connection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(connection, MyRootChangeListener()) } /** * In case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated. * Filter directories which excluded or containing source roots and expire notification if needed. */ private fun updateNotificationState() { if (synchronizationTurnOff()) return if (isFilesEmpty()) return queue.queue(Update.create("update") { val fileIndex = ProjectFileIndex.getInstance(project) val sourceRoots = getProjectSourceRoots(project) val acquiredFiles = selectValidFiles() LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles) val filesToRemove = acquiredFiles .asSequence() .filter { file -> runReadAction { fileIndex.isExcluded(file) } || sourceRoots.contains(file) } .toList() LOG.debug("updateNotificationState, filesToRemove", filesToRemove) if (removeFiles(filesToRemove)) { EditorNotifications.getInstance(project).updateAllNotifications() } }) } fun isNotEmpty() = !isFilesEmpty() fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files) fun getValidFiles() = with(ChangeListManager.getInstance(project)) { selectValidFiles().filter(this::isIgnoredFile) } private fun wasAskedBefore() = PropertiesComponent.getInstance(project).getBoolean(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, false) fun muteForCurrentProject() { PropertiesComponent.getInstance(project).setValue(ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, true) clearFiles() } fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject() override fun doActionOnChosenFiles(files: Collection<VirtualFile>) { if (files.isEmpty()) return markIgnoredAsExcluded(project, files) } override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid) override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED fun ignoredUpdateFinished(ignoredPaths: Collection<FilePath>) { ProgressManager.checkCanceled() if (synchronizationTurnOff()) return if (mutedForCurrentProject()) return processIgnored(ignoredPaths) } private fun processIgnored(ignoredPaths: Collection<FilePath>) { val ignoredDirs = determineIgnoredDirsToExclude(project, ignoredPaths) if (allowShowNotification()) { processFiles(ignoredDirs) val editorNotifications = EditorNotifications.getInstance(project) FileEditorManager.getInstance(project).openFiles .forEach { openFile -> if (openFile.fileType is IgnoreFileType) { editorNotifications.updateNotifications(openFile) } } } else if (needDoForCurrentProject()) { doActionOnChosenFiles(doFilterFiles(ignoredDirs)) } } private inner class MyRootChangeListener : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { // listen content roots, source roots, excluded roots if (event.getChanges(ContentRootEntity::class.java).isNotEmpty()) { updateNotificationState() } } } } private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) { val ignoredDirsByModule = files .groupBy { ModuleUtil.findModuleForFile(it, project) } //if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing. .filterKeys(Objects::nonNull) for ((module, ignoredDirs) in ignoredDirsByModule) { excludeAction.exclude(module!!, ignoredDirs) } } private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction { OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet() } private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) = FileUtil.isAncestor(shelfPath, filePath.path, false) || FileUtil.isAncestor(filePath.path, shelfPath, false) private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> { val sourceRoots = getProjectSourceRoots(project) val fileIndex = ProjectFileIndex.getInstance(project) val shelfPath = ShelveChangesManager.getShelfPath(project) return ignoredPaths .asSequence() .filter(FilePath::isDirectory) //shelf directory usually contains in project and excluding it prevents local history to work on it .filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) } .mapNotNull(FilePath::getVirtualFile) .filterNot { runReadAction { fileIndex.isExcluded(it) } } //do not propose to exclude if there is a source root inside .filterNot { ignored -> sourceRoots.contains(ignored) } .toList() } private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> { val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs) if (!dialog.showAndGet()) return emptyList() return dialog.selectedFiles } private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true) private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true) class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { companion object { private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider") } override fun getKey(): Key<EditorNotificationPanel> = KEY private fun canCreateNotification(project: Project, file: VirtualFile) = file.fileType is IgnoreFileType && with(project.service<IgnoredToExcludedSynchronizer>()) { !synchronizationTurnOff() && allowShowNotification() && !mutedForCurrentProject() && isNotEmpty() } private fun showIgnoredAction(project: Project) { val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles() if (allFiles.isEmpty()) return val userSelectedFiles = selectFilesToExclude(project, allFiles) if (userSelectedFiles.isEmpty()) return with(project.service<IgnoredToExcludedSynchronizer>()) { markIgnoredAsExcluded(project, userSelectedFiles) clearFiles(userSelectedFiles) } } private fun muteAction(project: Project) = Runnable { project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject() EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider) } override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (!canCreateNotification(project, file)) return null return EditorNotificationPanel(fileEditor).apply { icon(AllIcons.General.Information) text = message("ignore.to.exclude.notification.message") createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) } createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project)) createActionLabel(message("ignore.to.exclude.notification.action.details")) { BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories") } } } } internal class CheckIgnoredToExcludeAction : DumbAwareAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! runModalTask(ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress"), project, true) { VcsIgnoreManagerImpl.getInstanceImpl(project).awaitRefreshQueue() val ignoredFilePaths = ChangeListManager.getInstance(project).ignoredFilePaths val dirsToExclude = determineIgnoredDirsToExclude(project, ignoredFilePaths) if (dirsToExclude.isEmpty()) { VcsNotifier.getInstance(project) .notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found")) } else { val userSelectedFiles = selectFilesToExclude(project, dirsToExclude) if (userSelectedFiles.isNotEmpty()) { markIgnoredAsExcluded(project, userSelectedFiles) } } } } } // do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked private class IgnoredToExcludeSelectDirectoriesDialog( project: Project?, files: List<VirtualFile> ) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) { init { title = message("ignore.to.exclude.view.dialog.title") selectedFiles = files setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action")) setCancelButtonText(CommonBundle.getCancelButtonText()) init() } }
apache-2.0
852146682cda67345f8f8fb9c8e0fddf
41.182119
146
0.77667
4.700738
false
false
false
false
siosio/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/MavenSyncConsole.kt
1
21307
// 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. package org.jetbrains.idea.maven.buildtool import com.intellij.build.BuildProgressListener import com.intellij.build.DefaultBuildDescriptor import com.intellij.build.FilePosition import com.intellij.build.SyncViewManager import com.intellij.build.events.EventResult import com.intellij.build.events.MessageEvent import com.intellij.build.events.MessageEventResult import com.intellij.build.events.impl.* import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.execution.ExecutionException import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.util.ExceptionUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.buildtool.quickfix.OffMavenOfflineModeQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenSettingsQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.UseBundledMavenQuickFix import org.jetbrains.idea.maven.execution.SyncBundle import org.jetbrains.idea.maven.externalSystemIntegration.output.importproject.quickfixes.DownloadArtifactBuildIssue import org.jetbrains.idea.maven.model.MavenProjectProblem import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.server.CannotStartServerException import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.server.MavenServerProgressIndicator import org.jetbrains.idea.maven.utils.MavenLog import org.jetbrains.idea.maven.utils.MavenUtil import java.io.File class MavenSyncConsole(private val myProject: Project) { @Volatile private var mySyncView: BuildProgressListener = BuildProgressListener { _, _ -> } private var mySyncId = createTaskId() private var finished = false private var started = false private var wrapperProgressIndicator: WrapperProgressIndicator? = null private var hasErrors = false private var hasUnresolved = false private val JAVADOC_AND_SOURCE_CLASSIFIERS = setOf("javadoc", "sources", "test-javadoc", "test-sources") private val shownIssues = HashSet<String>() private val myPostponed = ArrayList<() -> Unit>() private var myStartedSet = LinkedHashSet<Pair<Any, String>>() @Synchronized fun startImport(syncView: BuildProgressListener) { if (started) { return } val restartAction: AnAction = object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = !started || finished e.presentation.icon = AllIcons.Actions.Refresh } override fun actionPerformed(e: AnActionEvent) { e.project?.let { MavenProjectsManager.getInstance(it).forceUpdateAllProjectsOrFindAllAvailablePomFiles() } } } started = true finished = false hasErrors = false hasUnresolved = false wrapperProgressIndicator = WrapperProgressIndicator() mySyncView = syncView shownIssues.clear() mySyncId = createTaskId() val descriptor = DefaultBuildDescriptor(mySyncId, SyncBundle.message("maven.sync.title"), myProject.basePath!!, System.currentTimeMillis()) .withRestartAction(restartAction) descriptor.isActivateToolWindowWhenFailed = true descriptor.isActivateToolWindowWhenAdded = false mySyncView.onEvent(mySyncId, StartBuildEventImpl(descriptor, SyncBundle.message("maven.sync.project.title", myProject.name))) debugLog("maven sync: started importing $myProject") myPostponed.forEach(this::doIfImportInProcess) myPostponed.clear(); } private fun createTaskId() = ExternalSystemTaskId.create(MavenUtil.SYSTEM_ID, ExternalSystemTaskType.RESOLVE_PROJECT, myProject) fun getTaskId() = mySyncId fun addText(@Nls text: String) = addText(text, true) @Synchronized fun addText(@Nls text: String, stdout: Boolean) = doIfImportInProcess { addText(mySyncId, text, true) } @Synchronized private fun addText(parentId: Any, @Nls text: String, stdout: Boolean) = doIfImportInProcess { if (StringUtil.isEmpty(text)) { return } val toPrint = if (text.endsWith('\n')) text else "$text\n" mySyncView.onEvent(mySyncId, OutputBuildEventImpl(parentId, toPrint, stdout)) } @Synchronized fun addWarning(@Nls text: String, @Nls description: String) = addWarning(text, description, null) fun addBuildIssue(issue: BuildIssue, kind: MessageEvent.Kind) = doIfImportInProcessOrPostpone { if (!newIssue(issue.title + issue.description)) return@doIfImportInProcessOrPostpone; mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, issue, kind)) hasErrors = hasErrors || kind == MessageEvent.Kind.ERROR; } @Synchronized fun addWarning(@Nls text: String, @Nls description: String, filePosition: FilePosition?) = doIfImportInProcess { if (!newIssue(text + description + filePosition)) return; if (filePosition == null) { mySyncView.onEvent(mySyncId, MessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description)) } else { mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description, filePosition)) } } private fun newIssue(s: String): Boolean { return shownIssues.add(s) } @Synchronized fun finishImport() { debugLog("Maven sync: finishImport") doFinish() } @Synchronized fun terminated(exitCode: Int) = doIfImportInProcess { val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode))) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode)))) finished = true started = false } @Synchronized fun startWrapperResolving() { if (!started || finished) { startImport(myProject.getService(SyncViewManager::class.java)) } startTask(mySyncId, SyncBundle.message("maven.sync.wrapper")) } @Synchronized fun finishWrapperResolving(e: Throwable? = null) { if (e != null) { addWarning(SyncBundle.message("maven.sync.wrapper.failure"), e.localizedMessage) } completeTask(mySyncId, SyncBundle.message("maven.sync.wrapper"), SuccessResultImpl()) } fun progressIndicatorForWrapper(): ProgressIndicator { return wrapperProgressIndicator ?: EmptyProgressIndicator() } inner class WrapperProgressIndicator : EmptyProgressIndicator() { var myFraction: Long = 0 override fun setText(text: String) = doIfImportInProcess { addText(SyncBundle.message("maven.sync.wrapper"), text, true) } override fun setFraction(fraction: Double) = doIfImportInProcess { val newFraction = (fraction * 100).toLong() if (myFraction == newFraction) return@doIfImportInProcess myFraction = newFraction; mySyncView.onEvent(mySyncId, ProgressBuildEventImpl(SyncBundle.message("maven.sync.wrapper"), SyncBundle.message("maven.sync.wrapper"), System.currentTimeMillis(), SyncBundle.message("maven.sync.wrapper.dowloading"), 100, myFraction, "%" )) } } @Synchronized fun notifyReadingProblems(file: VirtualFile) = doIfImportInProcess { debugLog("reading problems in $file") hasErrors = true val desc = SyncBundle.message("maven.sync.failure.error.reading.file", file.path) mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), desc, desc, FilePosition(File(file.path), -1, -1))) } @Synchronized fun showProblem(problem: MavenProjectProblem) = doIfImportInProcess { hasErrors = true val group = SyncBundle.message("maven.sync.group.error") val description = problem.description val position = problem.getPosition() val eventImpl = FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, group, description, description, position) mySyncView.onEvent(mySyncId, eventImpl) } private fun MavenProjectProblem.getPosition(): FilePosition { val problemFile = File(path) try { if (type == MavenProjectProblem.ProblemType.STRUCTURE) { val pattern = Regex("@(\\d+):(\\d+)") val matchedCoordinates = pattern.findAll(description).lastOrNull() if (matchedCoordinates != null) { val (_, line, offset) = matchedCoordinates.groupValues return FilePosition(problemFile, line.toInt() - 1, offset.toInt()) } } } catch (ex: Exception) { MavenLog.LOG.error(ex) } return FilePosition(problemFile, -1, -1) } @Synchronized @ApiStatus.Internal fun addException(e: Throwable, progressListener: BuildProgressListener) { if (started && !finished) { MavenLog.LOG.warn(e) hasErrors = true @Suppress("HardCodedStringLiteral") mySyncView.onEvent(mySyncId, createMessageEvent(e)) } else { this.startImport(progressListener) this.addException(e, progressListener) this.finishImport() } } private fun createMessageEvent(e: Throwable): MessageEventImpl { if (e is CannotStartServerException) { val cause = ExceptionUtil.findCause(e, ExecutionException::class.java) if (cause != null) { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(cause), getExceptionText(cause)) } else { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(e), getExceptionText(e)) } } return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.error"), getExceptionText(e), getExceptionText(e)) } private fun getExceptionText(e: Throwable): @NlsSafe String { if (MavenWorkspaceSettingsComponent.getInstance(myProject).settings.getGeneralSettings().isPrintErrorStackTraces) { return ExceptionUtil.getThrowableText(e) } return e.localizedMessage.ifEmpty { if (StringUtil.isEmpty(e.message)) SyncBundle.message("build.event.title.error") else e.message!! } } fun getListener(type: MavenServerProgressIndicator.ResolveType): ArtifactSyncListener { return when (type) { MavenServerProgressIndicator.ResolveType.PLUGIN -> ArtifactSyncListenerImpl("maven.sync.plugins") MavenServerProgressIndicator.ResolveType.DEPENDENCY -> ArtifactSyncListenerImpl("maven.sync.dependencies") } } @Synchronized private fun doFinish() { val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, DerivedResultImpl()) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", if (hasErrors) FailureResultImpl() else DerivedResultImpl())) val generalSettings = MavenWorkspaceSettingsComponent.getInstance(myProject).settings.generalSettings if (hasUnresolved && generalSettings.isWorkOffline) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title: String = "Dependency Resolution Failed" override val description: String = "<a href=\"${OffMavenOfflineModeQuickFix.ID}\">Switch Off Offline Mode</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OffMavenOfflineModeQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } finished = true started = false } @Synchronized private fun showError(keyPrefix: String, dependency: String) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) mySyncView.onEvent(mySyncId, MessageEventImpl(umbrellaString, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), errorString, errorString)) addText(mySyncId, errorString, false) } @Synchronized private fun showBuildIssue(keyPrefix: String, dependency: String, quickFix: BuildIssueQuickFix,) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) val buildIssue = DownloadArtifactBuildIssue.getIssue(errorString, quickFix) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(umbrellaString, buildIssue, MessageEvent.Kind.ERROR)) addText(mySyncId, errorString, false) } @Synchronized private fun startTask(parentId: Any, @NlsSafe taskName: String) = doIfImportInProcess { debugLog("Maven sync: start $taskName") if (myStartedSet.add(parentId to taskName)) { mySyncView.onEvent(mySyncId, StartEventImpl(taskName, parentId, System.currentTimeMillis(), taskName)) } } @Synchronized private fun completeTask(parentId: Any, @NlsSafe taskName: String, result: EventResult) = doIfImportInProcess { hasErrors = hasErrors || result is FailureResultImpl debugLog("Maven sync: complete $taskName with $result") if (myStartedSet.remove(parentId to taskName)) { mySyncView.onEvent(mySyncId, FinishEventImpl(taskName, parentId, System.currentTimeMillis(), taskName, result)) } } private fun debugLog(s: String, exception: Throwable? = null) { MavenLog.LOG.debug(s, exception) } @Synchronized private fun completeUmbrellaEvents(keyPrefix: String) = doIfImportInProcess { val taskName = SyncBundle.message("${keyPrefix}.resolve") completeTask(mySyncId, taskName, DerivedResultImpl()) } @Synchronized private fun downloadEventStarted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) startTask(mySyncId, downloadString) startTask(downloadString, downloadArtifactString) } @Synchronized private fun downloadEventCompleted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) addText(downloadArtifactString, downloadArtifactString, true) completeTask(downloadString, downloadArtifactString, SuccessResultImpl(false)) } @Synchronized private fun downloadEventFailed(keyPrefix: String, @NlsSafe dependency: String, @NlsSafe error: String, @NlsSafe stackTrace: String?) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) if (isJavadocOrSource(dependency)) { addText(downloadArtifactString, SyncBundle.message("maven.sync.failure.dependency.not.found", dependency), true) completeTask(downloadString, downloadArtifactString, object : MessageEventResult { override fun getKind(): MessageEvent.Kind { return MessageEvent.Kind.WARNING } override fun getDetails(): String? { return SyncBundle.message("maven.sync.failure.dependency.not.found", dependency) } }) } else { if (stackTrace != null && Registry.`is`("maven.spy.events.debug")) { addText(downloadArtifactString, stackTrace, false) } else { addText(downloadArtifactString, error, true) } completeTask(downloadString, downloadArtifactString, FailureResultImpl(error)) } } @Synchronized fun showQuickFixBadMaven(message: String, kind: MessageEvent.Kind) { val bundledVersion = MavenServerManager.getMavenVersion(MavenServerManager.BUNDLED_MAVEN_3) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.version.issue.title") override val description: String = "${message}\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.open.settings") + "</a>\n" + "- <a href=\"${UseBundledMavenQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.use.bundled", bundledVersion) + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix(), UseBundledMavenQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, kind)) } @Synchronized fun showQuickFixJDK(version: String) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.quickfixes.maven.jdk.version.title") override val description: String = SyncBundle.message("maven.sync.quickfixes.upgrade.to.jdk7", version) + "\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.quickfixes.open.settings") + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } private fun isJavadocOrSource(dependency: String): Boolean { val split = dependency.split(':') if (split.size < 4) { return false } val classifier = split.get(2) return JAVADOC_AND_SOURCE_CLASSIFIERS.contains(classifier) } private inline fun doIfImportInProcess(action: () -> Unit) { if (!started || finished) return action.invoke() } private fun doIfImportInProcessOrPostpone(action: () -> Unit) { if (!started || finished) { myPostponed.add(action) } else { action.invoke() } } private inner class ArtifactSyncListenerImpl(val keyPrefix: String) : ArtifactSyncListener { override fun downloadStarted(dependency: String) { downloadEventStarted(keyPrefix, dependency) } override fun downloadCompleted(dependency: String) { downloadEventCompleted(keyPrefix, dependency) } override fun downloadFailed(dependency: String, error: String, stackTrace: String?) { downloadEventFailed(keyPrefix, dependency, error, stackTrace) } override fun finish() { completeUmbrellaEvents(keyPrefix) } override fun showError(dependency: String) { showError(keyPrefix, dependency) } override fun showBuildIssue(dependency: String, quickFix: BuildIssueQuickFix) { showBuildIssue(keyPrefix, dependency, quickFix) } } } interface ArtifactSyncListener { fun showError(dependency: String) fun showBuildIssue(dependency: String, quickFix: BuildIssueQuickFix) fun downloadStarted(dependency: String) fun downloadCompleted(dependency: String) fun downloadFailed(dependency: String, error: String, stackTrace: String?) fun finish() }
apache-2.0
a3caeed453f218d36673919706ef3f51
40.615234
140
0.703337
5.001643
false
false
false
false
jwren/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutor.kt
5
9870
// 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 org.jetbrains.plugins.github.api import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.EventDispatcher import com.intellij.util.ThrowableConvertor import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.io.HttpRequests import com.intellij.util.io.HttpSecurityUtil import com.intellij.util.io.RequestBuilder import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.github.api.data.GithubErrorMessage import org.jetbrains.plugins.github.exceptions.* import org.jetbrains.plugins.github.util.GithubSettings import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.net.HttpURLConnection import java.util.* import java.util.zip.GZIPInputStream /** * Executes API requests taking care of authentication, headers, proxies, timeouts, etc. */ sealed class GithubApiRequestExecutor { protected val authDataChangedEventDispatcher = EventDispatcher.create(AuthDataChangeListener::class.java) @RequiresBackgroundThread @Throws(IOException::class, ProcessCanceledException::class) abstract fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T @TestOnly @RequiresBackgroundThread @Throws(IOException::class, ProcessCanceledException::class) fun <T> execute(request: GithubApiRequest<T>): T = execute(EmptyProgressIndicator(), request) fun addListener(listener: AuthDataChangeListener, disposable: Disposable) = authDataChangedEventDispatcher.addListener(listener, disposable) fun addListener(disposable: Disposable, listener: () -> Unit) = authDataChangedEventDispatcher.addListener(object : AuthDataChangeListener { override fun authDataChanged() { listener() } }, disposable) class WithTokenAuth internal constructor(githubSettings: GithubSettings, token: String, private val useProxy: Boolean) : Base(githubSettings) { @Volatile internal var token: String = token set(value) { field = value authDataChangedEventDispatcher.multicaster.authDataChanged() } @Throws(IOException::class, ProcessCanceledException::class) override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T { check(!service<GHRequestExecutorBreaker>().isRequestsShouldFail) { "Request failure was triggered by user action. This a pretty long description of this failure that should resemble some long error which can go out of bounds." } service<GHEServerVersionChecker>().checkVersionSupported(request.url) indicator.checkCanceled() return createRequestBuilder(request) .tuner { connection -> request.additionalHeaders.forEach(connection::addRequestProperty) connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Bearer $token") } .useProxy(useProxy) .execute(request, indicator) } } class NoAuth internal constructor(githubSettings: GithubSettings) : Base(githubSettings) { override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T { indicator.checkCanceled() return createRequestBuilder(request) .tuner { connection -> request.additionalHeaders.forEach(connection::addRequestProperty) } .useProxy(true) .execute(request, indicator) } } abstract class Base(private val githubSettings: GithubSettings) : GithubApiRequestExecutor() { protected fun <T> RequestBuilder.execute(request: GithubApiRequest<T>, indicator: ProgressIndicator): T { indicator.checkCanceled() try { LOG.debug("Request: ${request.url} ${request.operationName} : Connecting") return connect { val connection = it.connection as HttpURLConnection if (request is GithubApiRequest.WithBody) { LOG.debug("Request: ${connection.requestMethod} ${connection.url} with body:\n${request.body} : Connected") request.body?.let { body -> it.write(body) } } else { LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Connected") } checkResponseCode(connection) indicator.checkCanceled() val result = request.extractResult(createResponse(it, indicator)) LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Result extracted") result } } catch (e: GithubStatusCodeException) { @Suppress("UNCHECKED_CAST") if (request is GithubApiRequest.Get.Optional<*> && e.statusCode == HttpURLConnection.HTTP_NOT_FOUND) return null as T else throw e } catch (e: GithubConfusingException) { if (request.operationName != null) { val errorText = "Can't ${request.operationName}" e.setDetails(errorText) LOG.debug(errorText, e) } throw e } } protected fun createRequestBuilder(request: GithubApiRequest<*>): RequestBuilder { return when (request) { is GithubApiRequest.Get -> HttpRequests.request(request.url) is GithubApiRequest.Patch -> HttpRequests.patch(request.url, request.bodyMimeType) is GithubApiRequest.Post -> HttpRequests.post(request.url, request.bodyMimeType) is GithubApiRequest.Put -> HttpRequests.put(request.url, request.bodyMimeType) is GithubApiRequest.Head -> HttpRequests.head(request.url) is GithubApiRequest.Delete -> { if (request.body == null) HttpRequests.delete(request.url) else HttpRequests.delete(request.url, request.bodyMimeType) } else -> throw UnsupportedOperationException("${request.javaClass} is not supported") } .connectTimeout(githubSettings.connectionTimeout) .userAgent("Intellij IDEA Github Plugin") .throwStatusCodeException(false) .forceHttps(false) .accept(request.acceptMimeType) } @Throws(IOException::class) private fun checkResponseCode(connection: HttpURLConnection) { if (connection.responseCode < 400) return val statusLine = "${connection.responseCode} ${connection.responseMessage}" val errorText = getErrorText(connection) LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Error ${statusLine} body:\n${errorText}") val jsonError = errorText?.let { getJsonError(connection, it) } jsonError ?: LOG.debug("Request: ${connection.requestMethod} ${connection.url} : Unable to parse JSON error") throw when (connection.responseCode) { HttpURLConnection.HTTP_UNAUTHORIZED, HttpURLConnection.HTTP_PAYMENT_REQUIRED, HttpURLConnection.HTTP_FORBIDDEN -> { if (jsonError?.containsReasonMessage("API rate limit exceeded") == true) { GithubRateLimitExceededException(jsonError.presentableError) } else GithubAuthenticationException("Request response: " + (jsonError?.presentableError ?: errorText ?: statusLine)) } else -> { if (jsonError != null) { GithubStatusCodeException("$statusLine - ${jsonError.presentableError}", jsonError, connection.responseCode) } else { GithubStatusCodeException("$statusLine - ${errorText}", connection.responseCode) } } } } private fun getErrorText(connection: HttpURLConnection): String? { val errorStream = connection.errorStream ?: return null val stream = if (connection.contentEncoding == "gzip") GZIPInputStream(errorStream) else errorStream return InputStreamReader(stream, Charsets.UTF_8).use { it.readText() } } private fun getJsonError(connection: HttpURLConnection, errorText: String): GithubErrorMessage? { if (!connection.contentType.startsWith(GithubApiContentHelper.JSON_MIME_TYPE)) return null return try { return GithubApiContentHelper.fromJson(errorText) } catch (jse: GithubJsonException) { null } } private fun createResponse(request: HttpRequests.Request, indicator: ProgressIndicator): GithubApiResponse { return object : GithubApiResponse { override fun findHeader(headerName: String): String? = request.connection.getHeaderField(headerName) override fun <T> readBody(converter: ThrowableConvertor<Reader, T, IOException>): T = request.getReader(indicator).use { converter.convert(it) } override fun <T> handleBody(converter: ThrowableConvertor<InputStream, T, IOException>): T = request.inputStream.use { converter.convert(it) } } } } class Factory { @CalledInAny fun create(token: String): WithTokenAuth { return create(token, true) } @CalledInAny fun create(token: String, useProxy: Boolean = true): WithTokenAuth { return WithTokenAuth(GithubSettings.getInstance(), token, useProxy) } @CalledInAny fun create() = NoAuth(GithubSettings.getInstance()) companion object { @JvmStatic fun getInstance(): Factory = service() } } companion object { private val LOG = logger<GithubApiRequestExecutor>() } interface AuthDataChangeListener : EventListener { fun authDataChanged() } }
apache-2.0
4078ff3be8c73b8d7170342c119fad88
40.301255
167
0.703749
4.94985
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Int.kt
1
5920
package com.simplemobiletools.commons.extensions import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.media.ExifInterface import android.text.format.DateFormat import android.text.format.DateUtils import android.text.format.Time import com.simplemobiletools.commons.helpers.DARK_GREY import java.text.DecimalFormat import java.util.* fun Int.getContrastColor(): Int { val y = (299 * Color.red(this) + 587 * Color.green(this) + 114 * Color.blue(this)) / 1000 return if (y >= 149 && this != Color.BLACK) DARK_GREY else Color.WHITE } fun Int.toHex() = String.format("#%06X", 0xFFFFFF and this).toUpperCase() fun Int.adjustAlpha(factor: Float): Int { val alpha = Math.round(Color.alpha(this) * factor) val red = Color.red(this) val green = Color.green(this) val blue = Color.blue(this) return Color.argb(alpha, red, green, blue) } fun Int.getFormattedDuration(forceShowHours: Boolean = false): String { val sb = StringBuilder(8) val hours = this / 3600 val minutes = this % 3600 / 60 val seconds = this % 60 if (this >= 3600) { sb.append(String.format(Locale.getDefault(), "%02d", hours)).append(":") } else if (forceShowHours) { sb.append("0:") } sb.append(String.format(Locale.getDefault(), "%02d", minutes)) sb.append(":").append(String.format(Locale.getDefault(), "%02d", seconds)) return sb.toString() } fun Int.formatSize(): String { if (this <= 0) { return "0 B" } val units = arrayOf("B", "kB", "MB", "GB", "TB") val digitGroups = (Math.log10(toDouble()) / Math.log10(1024.0)).toInt() return "${DecimalFormat("#,##0.#").format(this / Math.pow(1024.0, digitGroups.toDouble()))} ${units[digitGroups]}" } fun Int.formatDate(context: Context, dateFormat: String? = null, timeFormat: String? = null): String { val useDateFormat = dateFormat ?: context.baseConfig.dateFormat val useTimeFormat = timeFormat ?: context.getTimeFormat() val cal = Calendar.getInstance(Locale.ENGLISH) cal.timeInMillis = this * 1000L return DateFormat.format("$useDateFormat, $useTimeFormat", cal).toString() } // if the given date is today, we show only the time. Else we show the date and optionally the time too fun Int.formatDateOrTime(context: Context, hideTimeAtOtherDays: Boolean, showYearEvenIfCurrent: Boolean): String { val cal = Calendar.getInstance(Locale.ENGLISH) cal.timeInMillis = this * 1000L return if (DateUtils.isToday(this * 1000L)) { DateFormat.format(context.getTimeFormat(), cal).toString() } else { var format = context.baseConfig.dateFormat if (!showYearEvenIfCurrent && isThisYear()) { format = format.replace("y", "").trim().trim('-').trim('.').trim('/') } if (!hideTimeAtOtherDays) { format += ", ${context.getTimeFormat()}" } DateFormat.format(format, cal).toString() } } fun Int.isThisYear(): Boolean { val time = Time() time.set(this * 1000L) val thenYear = time.year time.set(System.currentTimeMillis()) return (thenYear == time.year) } fun Int.addBitIf(add: Boolean, bit: Int) = if (add) { addBit(bit) } else { removeBit(bit) } // TODO: how to do "bits & ~bit" in kotlin? fun Int.removeBit(bit: Int) = addBit(bit) - bit fun Int.addBit(bit: Int) = this or bit fun Int.flipBit(bit: Int) = if (this and bit == 0) addBit(bit) else removeBit(bit) fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start // taken from https://stackoverflow.com/a/40964456/1967672 fun Int.darkenColor(factor: Int = 8): Int { if (this == Color.WHITE || this == Color.BLACK) { return this } val DARK_FACTOR = factor var hsv = FloatArray(3) Color.colorToHSV(this, hsv) val hsl = hsv2hsl(hsv) hsl[2] -= DARK_FACTOR / 100f if (hsl[2] < 0) hsl[2] = 0f hsv = hsl2hsv(hsl) return Color.HSVToColor(hsv) } fun Int.lightenColor(factor: Int = 8): Int { if (this == Color.WHITE || this == Color.BLACK) { return this } val LIGHT_FACTOR = factor var hsv = FloatArray(3) Color.colorToHSV(this, hsv) val hsl = hsv2hsl(hsv) hsl[2] += LIGHT_FACTOR / 100f if (hsl[2] < 0) hsl[2] = 0f hsv = hsl2hsv(hsl) return Color.HSVToColor(hsv) } private fun hsl2hsv(hsl: FloatArray): FloatArray { val hue = hsl[0] var sat = hsl[1] val light = hsl[2] sat *= if (light < .5) light else 1 - light return floatArrayOf(hue, 2f * sat / (light + sat), light + sat) } private fun hsv2hsl(hsv: FloatArray): FloatArray { val hue = hsv[0] val sat = hsv[1] val value = hsv[2] val newHue = (2f - sat) * value var newSat = sat * value / if (newHue < 1f) newHue else 2f - newHue if (newSat > 1f) newSat = 1f return floatArrayOf(hue, newSat, newHue / 2f) } fun Int.orientationFromDegrees() = when (this) { 270 -> ExifInterface.ORIENTATION_ROTATE_270 180 -> ExifInterface.ORIENTATION_ROTATE_180 90 -> ExifInterface.ORIENTATION_ROTATE_90 else -> ExifInterface.ORIENTATION_NORMAL }.toString() fun Int.degreesFromOrientation() = when (this) { ExifInterface.ORIENTATION_ROTATE_270 -> 270 ExifInterface.ORIENTATION_ROTATE_180 -> 180 ExifInterface.ORIENTATION_ROTATE_90 -> 90 else -> 0 } fun Int.ensureTwoDigits(): String { return if (toString().length == 1) { "0$this" } else { toString() } } fun Int.getColorStateList(): ColorStateList { val states = arrayOf(intArrayOf(android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_checked), intArrayOf(android.R.attr.state_pressed) ) val colors = intArrayOf(this, this, this, this) return ColorStateList(states, colors) }
gpl-3.0
d3b89b01091462dc1687e56bb74c522b
29.358974
118
0.649662
3.542789
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/video/exo/GiphyMp4Cache.kt
2
4252
package org.thoughtcrime.securesms.video.exo import android.content.Context import android.net.Uri import androidx.annotation.WorkerThread import org.signal.core.util.StreamUtil import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.util.storage.FileStorage import java.io.IOException import java.io.InputStream /** * A simple disk cache for MP4 GIFS. While entries are stored on disk, the data has lifecycle of a single application session and will be cleared every app * start. This lets us keep stuff simple and maintain all of our metadata and state in memory. * * Features * - Write entire files into the cache * - Keep entries that are actively being read in the cache by maintaining locks on entries * - When the cache is over the size limit, inactive entries will be evicted in LRU order. */ class GiphyMp4Cache(private val maxSize: Long) { companion object { private val TAG = Log.tag(GiphyMp4Cache::class.java) private val DATA_LOCK = Object() private const val DIRECTORY = "mp4gif_cache" private const val PREFIX = "entry_" private const val EXTENSION = "mp4" } private val lockedUris: MutableSet<Uri> = mutableSetOf() private val uriToEntry: MutableMap<Uri, Entry> = mutableMapOf() @WorkerThread fun onAppStart(context: Context) { synchronized(DATA_LOCK) { lockedUris.clear() for (file in FileStorage.getAllFiles(context, DIRECTORY, PREFIX)) { if (!file.delete()) { Log.w(TAG, "Failed to delete: " + file.name) } } } } @Throws(IOException::class) fun write(context: Context, uri: Uri, inputStream: InputStream): ReadData { synchronized(DATA_LOCK) { lockedUris.add(uri) } val filename: String = FileStorage.save(context, inputStream, DIRECTORY, PREFIX, EXTENSION) val size = FileStorage.getFile(context, DIRECTORY, filename).length() synchronized(DATA_LOCK) { uriToEntry[uri] = Entry( uri = uri, filename = filename, size = size, lastAccessed = System.currentTimeMillis() ) } return readFromStorage(context, uri) ?: throw IOException("Could not find file immediately after writing!") } fun read(context: Context, uri: Uri): ReadData? { synchronized(DATA_LOCK) { lockedUris.add(uri) } return try { readFromStorage(context, uri) } catch (e: IOException) { null } } @Throws(IOException::class) fun readFromStorage(context: Context, uri: Uri): ReadData? { val entry: Entry = synchronized(DATA_LOCK) { uriToEntry[uri] } ?: return null val length: Long = FileStorage.getFile(context, DIRECTORY, entry.filename).length() val inputStream: InputStream = FileStorage.read(context, DIRECTORY, entry.filename) return ReadData(inputStream, length) { onEntryReleased(context, uri) } } private fun onEntryReleased(context: Context, uri: Uri) { synchronized(DATA_LOCK) { lockedUris.remove(uri) var totalSize: Long = calculateTotalSize(uriToEntry) if (totalSize > maxSize) { val evictCandidatesInLruOrder: MutableList<Entry> = ArrayList( uriToEntry.entries .filter { e -> !lockedUris.contains(e.key) } .map { e -> e.value } .sortedBy { e -> e.lastAccessed } ) while (totalSize > maxSize && evictCandidatesInLruOrder.isNotEmpty()) { val toEvict: Entry = evictCandidatesInLruOrder.removeAt(0) if (!FileStorage.getFile(context, DIRECTORY, toEvict.filename).delete()) { Log.w(TAG, "Failed to delete ${toEvict.filename}") } uriToEntry.remove(toEvict.uri) totalSize = calculateTotalSize(uriToEntry) } } } } private fun calculateTotalSize(data: Map<Uri, Entry>): Long { return data.values.map { e -> e.size }.reduceOrNull { sum, size -> sum + size } ?: 0 } fun interface Lease { fun release() } private data class Entry(val uri: Uri, val filename: String, val size: Long, val lastAccessed: Long) data class ReadData(val inputStream: InputStream, val length: Long, val lease: Lease) { fun release() { StreamUtil.close(inputStream) lease.release() } } }
gpl-3.0
9eb86ae40570613d161601faffc89bb3
30.496296
155
0.672389
4.112186
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/viewinterop/AndroidViewHolder.android.kt
3
19579
/* * 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.viewinterop import android.content.Context import android.graphics.Rect import android.graphics.Region import android.os.Build import android.os.Looper import android.view.View import android.view.ViewGroup import android.view.ViewParent import androidx.compose.runtime.CompositionContext import androidx.compose.runtime.snapshots.SnapshotStateObserver import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.pointer.pointerInteropFilter import androidx.compose.ui.input.canScroll import androidx.compose.ui.input.consumeScrollContainerInfo import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.IntrinsicMeasureScope import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.node.LayoutNode import androidx.compose.ui.platform.AndroidComposeView import androidx.compose.ui.platform.composeToViewOffset import androidx.compose.ui.platform.compositionContext import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Velocity import androidx.core.view.NestedScrollingParent3 import androidx.core.view.NestedScrollingParentHelper import androidx.core.view.ViewCompat import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner import kotlin.math.roundToInt import kotlinx.coroutines.launch /** * A base class used to host a [View] inside Compose. * This API is not designed to be used directly, but rather using the [AndroidView] and * `AndroidViewBinding` APIs, which are built on top of [AndroidViewHolder]. */ @OptIn(ExperimentalComposeUiApi::class) internal abstract class AndroidViewHolder( context: Context, parentContext: CompositionContext?, private val dispatcher: NestedScrollDispatcher ) : ViewGroup(context), NestedScrollingParent3 { init { // Any [Abstract]ComposeViews that are descendants of this view will host // subcompositions of the host composition. // UiApplier doesn't supply this, only AndroidView. parentContext?.let { compositionContext = it } // We save state ourselves, depending on composition. isSaveFromParentEnabled = false } /** * The view hosted by this holder. */ var view: View? = null internal set(value) { if (value !== field) { field = value removeAllViewsInLayout() if (value != null) { addView(value) runUpdate() } } } /** * The update logic of the [View]. */ var update: () -> Unit = {} protected set(value) { field = value hasUpdateBlock = true runUpdate() } private var hasUpdateBlock = false /** * The modifier of the `LayoutNode` corresponding to this [View]. */ var modifier: Modifier = Modifier set(value) { if (value !== field) { field = value onModifierChanged?.invoke(value) } } internal var onModifierChanged: ((Modifier) -> Unit)? = null /** * The screen density of the layout. */ var density: Density = Density(1f) set(value) { if (value !== field) { field = value onDensityChanged?.invoke(value) } } internal var onDensityChanged: ((Density) -> Unit)? = null /** Sets the [ViewTreeLifecycleOwner] for this view. */ var lifecycleOwner: LifecycleOwner? = null set(value) { if (value !== field) { field = value ViewTreeLifecycleOwner.set(this, value) } } /** Sets the ViewTreeSavedStateRegistryOwner for this view. */ var savedStateRegistryOwner: SavedStateRegistryOwner? = null set(value) { if (value !== field) { field = value setViewTreeSavedStateRegistryOwner(value) } } private val snapshotObserver = SnapshotStateObserver { command -> if (handler.looper === Looper.myLooper()) { command() } else { handler.post(command) } } private val onCommitAffectingUpdate: (AndroidViewHolder) -> Unit = { handler.post(runUpdate) } private val runUpdate: () -> Unit = { if (hasUpdateBlock) { snapshotObserver.observeReads(this, onCommitAffectingUpdate, update) } } internal var onRequestDisallowInterceptTouchEvent: ((Boolean) -> Unit)? = null private val location = IntArray(2) private var lastWidthMeasureSpec: Int = Unmeasured private var lastHeightMeasureSpec: Int = Unmeasured private val nestedScrollingParentHelper: NestedScrollingParentHelper = NestedScrollingParentHelper(this) private var isInScrollContainer: () -> Boolean = { true } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { view?.measure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(view?.measuredWidth ?: 0, view?.measuredHeight ?: 0) lastWidthMeasureSpec = widthMeasureSpec lastHeightMeasureSpec = heightMeasureSpec } fun remeasure() { if (lastWidthMeasureSpec == Unmeasured || lastHeightMeasureSpec == Unmeasured) { // This should never happen: it means that the views handler was measured without // the AndroidComposeView having been measured. return } measure(lastWidthMeasureSpec, lastHeightMeasureSpec) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { view?.layout(0, 0, r - l, b - t) } override fun getLayoutParams(): LayoutParams? { return view?.layoutParams ?: LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) } override fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { onRequestDisallowInterceptTouchEvent?.invoke(disallowIntercept) super.requestDisallowInterceptTouchEvent(disallowIntercept) } override fun onAttachedToWindow() { super.onAttachedToWindow() snapshotObserver.start() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() snapshotObserver.stop() // remove all observations: snapshotObserver.clear() } // When there is no hardware acceleration invalidates are intercepted using this method, // otherwise using onDescendantInvalidated. Return null to avoid invalidating the // AndroidComposeView or the handler. @Suppress("Deprecation") override fun invalidateChildInParent(location: IntArray?, dirty: Rect?): ViewParent? { super.invalidateChildInParent(location, dirty) layoutNode.invalidateLayer() return null } override fun onDescendantInvalidated(child: View, target: View) { // We need to call super here in order to correctly update the dirty flags of the holder. super.onDescendantInvalidated(child, target) layoutNode.invalidateLayer() } override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility) // On Lollipop, when the Window becomes visible, child Views need to be explicitly // invalidated for some reason. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && visibility == View.VISIBLE) { layoutNode.invalidateLayer() } } // Always mark the region of the View to not be transparent to disable an optimisation which // would otherwise cause certain buggy drawing scenarios. For example, Compose drawing on top // of SurfaceViews included in Compose would sometimes not be displayed, as the drawing is // not done by Views, therefore the area is not known as non-transparent to the View system. override fun gatherTransparentRegion(region: Region?): Boolean { if (region == null) return true getLocationInWindow(location) region.op( location[0], location[1], location[0] + width, location[1] + height, Region.Op.DIFFERENCE ) return true } /** * A [LayoutNode] tree representation for this Android [View] holder. * The [LayoutNode] will proxy the Compose core calls to the [View]. */ val layoutNode: LayoutNode = run { // Prepare layout node that proxies measure and layout passes to the View. val layoutNode = LayoutNode() val coreModifier = Modifier .pointerInteropFilter(this) .drawBehind { drawIntoCanvas { canvas -> (layoutNode.owner as? AndroidComposeView) ?.drawAndroidView(this@AndroidViewHolder, canvas.nativeCanvas) } } .onGloballyPositioned { // The global position of this LayoutNode can change with it being replaced. For // these cases, we need to inform the View. layoutAccordingTo(layoutNode) } .consumeScrollContainerInfo { scrollContainerInfo -> isInScrollContainer = { scrollContainerInfo?.canScroll() == true } } layoutNode.modifier = modifier.then(coreModifier) onModifierChanged = { layoutNode.modifier = it.then(coreModifier) } layoutNode.density = density onDensityChanged = { layoutNode.density = it } var viewRemovedOnDetach: View? = null layoutNode.onAttach = { owner -> (owner as? AndroidComposeView)?.addAndroidView(this, layoutNode) if (viewRemovedOnDetach != null) view = viewRemovedOnDetach } layoutNode.onDetach = { owner -> (owner as? AndroidComposeView)?.removeAndroidView(this) viewRemovedOnDetach = view view = null } layoutNode.measurePolicy = object : MeasurePolicy { override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult { if (constraints.minWidth != 0) { getChildAt(0).minimumWidth = constraints.minWidth } if (constraints.minHeight != 0) { getChildAt(0).minimumHeight = constraints.minHeight } measure( obtainMeasureSpec( constraints.minWidth, constraints.maxWidth, layoutParams!!.width ), obtainMeasureSpec( constraints.minHeight, constraints.maxHeight, layoutParams!!.height ) ) return layout(measuredWidth, measuredHeight) { layoutAccordingTo(layoutNode) } } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = intrinsicWidth(height) override fun IntrinsicMeasureScope.maxIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = intrinsicWidth(height) private fun intrinsicWidth(height: Int): Int { measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), obtainMeasureSpec(0, height, layoutParams!!.height) ) return measuredWidth } override fun IntrinsicMeasureScope.minIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = intrinsicHeight(width) override fun IntrinsicMeasureScope.maxIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = intrinsicHeight(width) private fun intrinsicHeight(width: Int): Int { measure( obtainMeasureSpec(0, width, layoutParams!!.width), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) ) return measuredHeight } } layoutNode } /** * Intersects [Constraints] and [View] LayoutParams to obtain the suitable [View.MeasureSpec] * for measuring the [View]. */ private fun obtainMeasureSpec( min: Int, max: Int, preferred: Int ): Int = when { preferred >= 0 || min == max -> { // Fixed size due to fixed size layout param or fixed constraints. MeasureSpec.makeMeasureSpec(preferred.coerceIn(min, max), MeasureSpec.EXACTLY) } preferred == LayoutParams.WRAP_CONTENT && max != Constraints.Infinity -> { // Wrap content layout param with finite max constraint. If max constraint is infinite, // we will measure the child with UNSPECIFIED. MeasureSpec.makeMeasureSpec(max, MeasureSpec.AT_MOST) } preferred == LayoutParams.MATCH_PARENT && max != Constraints.Infinity -> { // Match parent layout param, so we force the child to fill the available space. MeasureSpec.makeMeasureSpec(max, MeasureSpec.EXACTLY) } else -> { // max constraint is infinite and layout param is WRAP_CONTENT or MATCH_PARENT. MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) } } override fun shouldDelayChildPressedState(): Boolean = isInScrollContainer() // NestedScrollingParent3 override fun onStartNestedScroll(child: View, target: View, axes: Int, type: Int): Boolean { return (axes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0 || (axes and ViewCompat.SCROLL_AXIS_HORIZONTAL) != 0 } override fun getNestedScrollAxes(): Int { return nestedScrollingParentHelper.nestedScrollAxes } override fun onNestedScrollAccepted(child: View, target: View, axes: Int, type: Int) { nestedScrollingParentHelper.onNestedScrollAccepted(child, target, axes, type) } override fun onStopNestedScroll(target: View, type: Int) { nestedScrollingParentHelper.onStopNestedScroll(target, type) } override fun onNestedScroll( target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { if (!isNestedScrollingEnabled) return val consumedByParent = dispatcher.dispatchPostScroll( consumed = Offset(dxConsumed.toComposeOffset(), dyConsumed.toComposeOffset()), available = Offset(dxUnconsumed.toComposeOffset(), dyUnconsumed.toComposeOffset()), source = toNestedScrollSource(type) ) consumed[0] = composeToViewOffset(consumedByParent.x) consumed[1] = composeToViewOffset(consumedByParent.y) } override fun onNestedScroll( target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int ) { if (!isNestedScrollingEnabled) return dispatcher.dispatchPostScroll( consumed = Offset(dxConsumed.toComposeOffset(), dyConsumed.toComposeOffset()), available = Offset(dxUnconsumed.toComposeOffset(), dyUnconsumed.toComposeOffset()), source = toNestedScrollSource(type) ) } override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { if (!isNestedScrollingEnabled) return val consumedByParent = dispatcher.dispatchPreScroll( available = Offset(dx.toComposeOffset(), dy.toComposeOffset()), source = toNestedScrollSource(type) ) consumed[0] = composeToViewOffset(consumedByParent.x) consumed[1] = composeToViewOffset(consumedByParent.y) } override fun onNestedFling( target: View, velocityX: Float, velocityY: Float, consumed: Boolean ): Boolean { if (!isNestedScrollingEnabled) return false val viewVelocity = Velocity(velocityX.toComposeVelocity(), velocityY.toComposeVelocity()) dispatcher.coroutineScope.launch { if (!consumed) { dispatcher.dispatchPostFling( consumed = Velocity.Zero, available = viewVelocity ) } else { dispatcher.dispatchPostFling( consumed = viewVelocity, available = Velocity.Zero ) } } return false } override fun onNestedPreFling(target: View, velocityX: Float, velocityY: Float): Boolean { if (!isNestedScrollingEnabled) return false val toBeConsumed = Velocity(velocityX.toComposeVelocity(), velocityY.toComposeVelocity()) dispatcher.coroutineScope.launch { dispatcher.dispatchPreFling(toBeConsumed) } return false } override fun isNestedScrollingEnabled(): Boolean { return view?.isNestedScrollingEnabled ?: super.isNestedScrollingEnabled() } } private fun View.layoutAccordingTo(layoutNode: LayoutNode) { val position = layoutNode.coordinates.positionInRoot() val x = position.x.roundToInt() val y = position.y.roundToInt() layout(x, y, x + measuredWidth, y + measuredHeight) } private const val Unmeasured = Int.MIN_VALUE private fun Int.toComposeOffset() = toFloat() * -1 private fun Float.toComposeVelocity(): Float = this * -1f private fun toNestedScrollSource(type: Int): NestedScrollSource = when (type) { ViewCompat.TYPE_TOUCH -> NestedScrollSource.Drag else -> NestedScrollSource.Fling }
apache-2.0
59a0de7db15e6fae874627522baff61e
35.943396
99
0.641402
5.261758
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/shortcut/result/DeleteOrUpdateMethodAdapter.kt
3
4152
/* * Copyright 2018 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.room.solver.shortcut.result import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.XTypeSpec import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.isInt import androidx.room.compiler.processing.isKotlinUnit import androidx.room.compiler.processing.isVoid import androidx.room.compiler.processing.isVoidObject import androidx.room.ext.KotlinTypeNames import androidx.room.ext.isNotKotlinUnit import androidx.room.ext.isNotVoid import androidx.room.ext.isNotVoidObject import androidx.room.solver.CodeGenScope import androidx.room.vo.ShortcutQueryParameter /** * Class that knows how to generate a delete or update method body. */ class DeleteOrUpdateMethodAdapter private constructor(private val returnType: XType) { companion object { fun create(returnType: XType): DeleteOrUpdateMethodAdapter? { if (isDeleteOrUpdateValid(returnType)) { return DeleteOrUpdateMethodAdapter(returnType) } return null } private fun isDeleteOrUpdateValid(returnType: XType): Boolean { return returnType.isVoid() || returnType.isInt() || returnType.isVoidObject() || returnType.isKotlinUnit() } } fun createDeleteOrUpdateMethodBody( parameters: List<ShortcutQueryParameter>, adapters: Map<String, Pair<XPropertySpec, XTypeSpec>>, dbProperty: XPropertySpec, scope: CodeGenScope ) { val resultVar = if (hasResultValue(returnType)) { scope.getTmpVar("_total") } else { null } scope.builder.apply { if (resultVar != null) { addLocalVariable( name = resultVar, typeName = XTypeName.PRIMITIVE_INT, isMutable = true, assignExpr = XCodeBlock.of(language, "0") ) } addStatement("%N.beginTransaction()", dbProperty) beginControlFlow("try").apply { parameters.forEach { param -> val adapter = adapters.getValue(param.name).first addStatement( "%L%L.%L(%L)", if (resultVar == null) "" else "$resultVar += ", adapter.name, param.handleMethodName(), param.name ) } addStatement("%N.setTransactionSuccessful()", dbProperty) if (resultVar != null) { addStatement("return %L", resultVar) } else if (returnType.isVoidObject()) { addStatement("return null") } else if (returnType.isKotlinUnit() && scope.language == CodeLanguage.JAVA) { addStatement("return %T.INSTANCE", KotlinTypeNames.UNIT) } } nextControlFlow("finally").apply { addStatement("%N.endTransaction()", dbProperty) } endControlFlow() } } private fun hasResultValue(returnType: XType): Boolean { return returnType.isNotVoid() && returnType.isNotVoidObject() && returnType.isNotKotlinUnit() } }
apache-2.0
8846f3dc03868a640dd816b9f53cb7ad
37.100917
94
0.617775
5.094479
false
false
false
false
google-developer-training/android-basics-kotlin-lunch-tray-app
app/src/main/java/com/example/lunchtray/model/OrderViewModel.kt
1
4831
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lunchtray.model import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.example.lunchtray.data.DataSource import java.text.NumberFormat class OrderViewModel : ViewModel() { // Map of menu items val menuItems = DataSource.menuItems // Default values for item prices private var previousEntreePrice = 0.0 private var previousSidePrice = 0.0 private var previousAccompanimentPrice = 0.0 // Default tax rate private val taxRate = 0.08 // Entree for the order private val _entree = MutableLiveData<MenuItem?>() val entree: LiveData<MenuItem?> = _entree // Side for the order private val _side = MutableLiveData<MenuItem?>() val side: LiveData<MenuItem?> = _side // Accompaniment for the order. private val _accompaniment = MutableLiveData<MenuItem?>() val accompaniment: LiveData<MenuItem?> = _accompaniment // Subtotal for the order private val _subtotal = MutableLiveData(0.0) val subtotal: LiveData<String> = Transformations.map(_subtotal) { NumberFormat.getCurrencyInstance().format(it) } // Total cost of the order private val _total = MutableLiveData(0.0) val total: LiveData<String> = Transformations.map(_total) { NumberFormat.getCurrencyInstance().format(it) } // Tax for the order private val _tax = MutableLiveData(0.0) val tax: LiveData<String> = Transformations.map(_tax) { NumberFormat.getCurrencyInstance().format(it) } /** * Set the entree for the order. */ fun setEntree(entree: String) { // TODO: if _entree.value is not null, set the previous entree price to the current // entree price. // TODO: if _subtotal.value is not null subtract the previous entree price from the current // subtotal value. This ensures that we only charge for the currently selected entree. // TODO: set the current entree value to the menu item corresponding to the passed in string // TODO: update the subtotal to reflect the price of the selected entree. } /** * Set the side for the order. */ fun setSide(side: String) { // TODO: if _side.value is not null, set the previous side price to the current side price. // TODO: if _subtotal.value is not null subtract the previous side price from the current // subtotal value. This ensures that we only charge for the currently selected side. // TODO: set the current side value to the menu item corresponding to the passed in string // TODO: update the subtotal to reflect the price of the selected side. } /** * Set the accompaniment for the order. */ fun setAccompaniment(accompaniment: String) { // TODO: if _accompaniment.value is not null, set the previous accompaniment price to the // current accompaniment price. // TODO: if _accompaniment.value is not null subtract the previous accompaniment price from // the current subtotal value. This ensures that we only charge for the currently selected // accompaniment. // TODO: set the current accompaniment value to the menu item corresponding to the passed in // string // TODO: update the subtotal to reflect the price of the selected accompaniment. } /** * Update subtotal value. */ private fun updateSubtotal(itemPrice: Double) { // TODO: if _subtotal.value is not null, update it to reflect the price of the recently // added item. // Otherwise, set _subtotal.value to equal the price of the item. // TODO: calculate the tax and resulting total } /** * Calculate tax and update total. */ fun calculateTaxAndTotal() { // TODO: set _tax.value based on the subtotal and the tax rate. // TODO: set the total based on the subtotal and _tax.value. } /** * Reset all values pertaining to the order. */ fun resetOrder() { // TODO: Reset all values associated with an order } }
apache-2.0
5b6bb603c057c47bc90f174a08903c1a
34.522059
100
0.679155
4.43211
false
false
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/providers/CloudFullLineCompletionProvider.kt
2
10068
package org.jetbrains.completion.full.line.providers import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.intellij.lang.Language import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.HttpRequests import org.jetbrains.completion.full.line.FullLineCompletionMode import org.jetbrains.completion.full.line.FullLineProposal import org.jetbrains.completion.full.line.RawFullLineProposal import org.jetbrains.completion.full.line.awaitWithCheckCanceled import org.jetbrains.completion.full.line.language.KeepKind import org.jetbrains.completion.full.line.models.RequestError import org.jetbrains.completion.full.line.platform.FullLineCompletionQuery import org.jetbrains.completion.full.line.platform.diagnostics.FullLinePart import org.jetbrains.completion.full.line.platform.diagnostics.logger import org.jetbrains.completion.full.line.settings.FullLineNotifications import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings import org.jetbrains.completion.full.line.settings.state.MlServerCompletionAuthState import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import java.net.ConnectException import java.net.HttpURLConnection import java.net.SocketTimeoutException import java.net.URL import java.util.concurrent.Callable import java.util.concurrent.ExecutionException import java.util.concurrent.ExecutorService import java.util.concurrent.Future class CloudFullLineCompletionProvider : FullLineCompletionProvider { override fun getId(): String = "server" override fun getVariants(query: FullLineCompletionQuery, indicator: ProgressIndicator): List<RawFullLineProposal> { if (MlServerCompletionAuthState.getInstance().state.authToken.isBlank()) { FullLineNotifications.Cloud.showAuthorizationError(query.project) return emptyList() } val start = System.currentTimeMillis() val future = submitQuery(query) return future.awaitWithCheckCanceled(start, Registry.get("full.line.server.host.max.latency").asInteger(), indicator) .also { LOG.info("Time to predict completions is ${(System.currentTimeMillis() - start) / 1000.0} sec") } .map { it.asRaw() } .also { emulateServerDelay(start) } } internal fun submitQuery(query: FullLineCompletionQuery): Future<List<ServerFullLineProposition>> { return executor.submit(Callable { try { HttpRequests.post("${getServer(query.language).asString()}/v1/complete/gpt", "application/json") .connect { r -> r.connection.setRequestProperty("Authorization", MlServerCompletionAuthState.getInstance().state.authToken) val request = FullLineCompletionServerRequest.fromSettings(query) r.write(GSON.toJson(request)) if ((r.connection as HttpURLConnection).responseCode == 403) { FullLineNotifications.Cloud.showAuthorizationError(query.project) emptyList() } else { val raw = r.reader.readText() GSON.fromJson(raw, ServerFullLineResult::class.java)?.completions ?: logError(GSON.fromJson(raw, RequestError::class.java)) } } } catch (e: Exception) { val message = when (e) { is ConnectException -> return@Callable emptyList() is SocketTimeoutException -> "Timeout. Probably IP is wrong" is HttpRequests.HttpStatusException -> "Something wrong with completion server" is ExecutionException, is IllegalStateException -> "Error while getting completions from server" else -> "Some other error occurred" } logError(message, e) } }) } private fun ServerFullLineProposition.asRaw(): RawFullLineProposal { return RawFullLineProposal( suggestion, score, FullLineProposal.BasicSyntaxCorrectness.fromBoolean(isSyntaxCorrect) ) } private fun logError(msg: String, throwable: Throwable): List<ServerFullLineProposition> { LOG.debug(msg, throwable) return emptyList() } private fun logError(error: RequestError): List<ServerFullLineProposition> = logError("Server bad response", error) private fun emulateServerDelay(start: Long) { val registryValue = Registry.get("full.line.server.emulate.model.response") if (registryValue.isChangedFromDefault) { val delay = registryValue.asInteger() val waitFor = delay - (System.currentTimeMillis() - start) if (waitFor > 0) { LOG.info("Emulating server delay for next $waitFor ms...") Thread.sleep(waitFor) LOG.info("Emulating server delay finished") } } } companion object { private val GSON = Gson() private val LOG = logger<CloudFullLineCompletionProvider>(FullLinePart.NETWORK) private const val timeout = 3L //Completion server cancels all threads besides the last one //We need at least 2 threads, the second one must (almost) instantly cancel the first one, otherwise, UI will freeze val executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("ML Server Completion", 2) /** * return Response status for connection with server or throws an error if it can't connect to server * for specific authentication token * - 200 - Success * - 403 - Forbidden * - 500 - Server error */ fun checkStatus(language: Language, authToken: String): Promise<Int> { LOG.info("Getting ${language.id} server status") val promise = executor.submitAndGetPromise { val serverReg = getServer(language) try { val myURLConnection = URL("${serverReg.asString()}/v1/status").openConnection() as HttpURLConnection myURLConnection.apply { setRequestProperty("Authorization", authToken) requestMethod = "GET" }.let { it.disconnect() it.responseCode } } catch (e: Throwable) { throw if (serverReg.isChangedFromDefault) CloudExceptionWithCustomRegistry(e, serverReg) else e } } ProgressManager.checkCanceled() return promise } @Suppress("UnresolvedPluginConfigReference") private fun getServer(language: Language) = Registry.get( when (MLServerCompletionSettings.getInstance().getModelState(language).psiBased) { false -> "full.line.server.host.${language.id.toLowerCase()}" true -> "full.line.server.host.psi.${language.id.toLowerCase()}" } ) } private data class ServerFullLineResult(val completions: List<ServerFullLineProposition>) // Set default `isSyntaxCorrect` to null since the server doesn't support and may not to return this feature yet internal data class ServerFullLineProposition( val score: Double, val suggestion: String, val isSyntaxCorrect: Boolean? = null ) private data class FullLineCompletionServerRequest( val code: String, @SerializedName("prefix") val token: String, val offset: Int, val filename: String, val language: String, val mode: FullLineCompletionMode, @SerializedName("num_iterations") val numIterations: Int, @SerializedName("beam_size") val beamSize: Int, @SerializedName("diversity_groups") val diversityGroups: Int, @SerializedName("diversity_strength") val diversityStrength: Double, @SerializedName("len_norm_base") val lenNormBase: Double, @SerializedName("len_norm_pow") val lenNormPow: Double, @SerializedName("top_n") val topN: Int?, @SerializedName("group_top_n") val groupTopN: Int?, @SerializedName("only_full_lines") val onlyFullLines: Boolean, val model: String?, @SerializedName("group_answers") val groupAnswers: Boolean?, @SerializedName("context_len") val contextLength: Int, @SerializedName("started_ts") val startedTs: Long, @SerializedName("min_prefix_dist") val minimumPrefixDist: Double?, @SerializedName("min_edit_dist") val minimumEditDist: Double?, @SerializedName("keep_kinds") val keepKinds: Set<KeepKind>?, @SerializedName("rollback_prefix") val rollbackPrefix: List<String>, ) { companion object { fun fromSettings( query: FullLineCompletionQuery, settings: MLServerCompletionSettings = MLServerCompletionSettings.getInstance(), ): FullLineCompletionServerRequest { val langState = settings.getLangState(query.language) val modelState = settings.getModelState(langState) return with(query) { FullLineCompletionServerRequest( context, prefix, offset, filename, language.displayName, mode, modelState.numIterations, modelState.beamSize, modelState.diversityGroups, modelState.diversityStrength, modelState.lenBase, modelState.lenPow, settings.topN(), settings.groupTopN(language), langState.onlyFullLines, null, langState.groupAnswers, modelState.contextLength(), System.currentTimeMillis(), modelState.minimumPrefixDist, modelState.minimumEditDist, modelState.keepKinds, rollbackPrefix, ) } } } } } class CloudExceptionWithCustomRegistry(cause: Throwable, val registry: RegistryValue) : Throwable(cause) fun <T> ExecutorService.submitAndGetPromise(callable: () -> T): Promise<T> { val promise = AsyncPromise<T>() execute { val result = try { callable() } catch (e: Throwable) { promise.setError(e) return@execute } promise.setResult(result) } return promise }
apache-2.0
31707fa9eb2bc6bdf2c7998e6a80d5fc
35.610909
121
0.698351
4.689334
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/minimap/MinimapService.kt
1
3182
// 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.ide.minimap import com.intellij.ide.minimap.settings.MinimapSettings import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import java.awt.BorderLayout import javax.swing.JPanel class MinimapService : Disposable { companion object { fun getInstance() = service<MinimapService>() private val MINI_MAP_PANEL_KEY: Key<MinimapPanel> = Key.create("com.intellij.ide.minimap.panel") } private val settings = MinimapSettings.getInstance() private val onSettingsChange = { type: MinimapSettings.SettingsChangeType -> if (type == MinimapSettings.SettingsChangeType.WithUiRebuild) { updateAllEditors() } } init { MinimapSettings.getInstance().settingsChangeCallback += onSettingsChange } fun updateAllEditors() { EditorFactory.getInstance().allEditors.forEach { editor -> getEditorImpl(editor)?.let { removeMinimap(it) if (settings.state.enabled) { addMinimap(it) } } } } override fun dispose() { MinimapSettings.getInstance().settingsChangeCallback -= onSettingsChange } private fun getEditorImpl(editor: Editor): EditorImpl? { val editorImpl = editor as? EditorImpl ?: return null val virtualFile = editorImpl.virtualFile ?: FileDocumentManager.getInstance().getFile(editor.document) ?: return null if (settings.state.fileTypes.isNotEmpty() && !settings.state.fileTypes.contains(virtualFile.fileType.defaultExtension)) return null return editorImpl } fun editorOpened(editor: Editor) { if (!settings.state.enabled) { return } getEditorImpl(editor)?.let { addMinimap(it) } } private fun getPanel(fileEditor: EditorImpl): JPanel? { return fileEditor.component as? JPanel } private fun addMinimap(textEditor: EditorImpl) { val panel = getPanel(textEditor) ?: return val where = if (settings.state.rightAligned) BorderLayout.LINE_END else BorderLayout.LINE_START if ((panel.layout as? BorderLayout)?.getLayoutComponent(where) == null) { val minimapPanel = MinimapPanel(textEditor.disposable, textEditor, panel) panel.add(minimapPanel, where) textEditor.putUserData(MINI_MAP_PANEL_KEY, minimapPanel) Disposer.register(textEditor.disposable) { textEditor.getUserData(MINI_MAP_PANEL_KEY)?.onClose() textEditor.putUserData(MINI_MAP_PANEL_KEY, null) } panel.revalidate() panel.repaint() } } private fun removeMinimap(editor: EditorImpl) { val minimapPanel = editor.getUserData(MINI_MAP_PANEL_KEY) ?: return minimapPanel.onClose() editor.putUserData(MINI_MAP_PANEL_KEY, null) minimapPanel.parent?.apply { remove(minimapPanel) revalidate() repaint() } } }
apache-2.0
0979c09912ee581cd5bbe7012837e225
31.479592
135
0.727844
4.329252
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/AbstractKotlinHighlightVisitor.kt
2
11273
// 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.highlighter import com.intellij.codeInsight.daemon.impl.Divider import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.HighlightVisitor import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder import com.intellij.codeInsight.daemon.impl.analysis.HighlightingLevelManager import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.CommonProcessors import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext import org.jetbrains.kotlin.diagnostics.rendering.parameters import org.jetbrains.kotlin.idea.base.fe10.highlighting.suspender.KotlinHighlightingSuspender import org.jetbrains.kotlin.idea.base.highlighting.shouldHighlightErrors import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.util.actionUnderSafeAnalyzeBlock import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext abstract class AbstractKotlinHighlightVisitor : HighlightVisitor { private var afterAnalysisVisitor: Array<AfterAnalysisHighlightingVisitor>? = null override fun suitableForFile(file: PsiFile) = file is KtFile override fun visit(element: PsiElement) { afterAnalysisVisitor?.forEach(element::accept) } override fun analyze(psiFile: PsiFile, updateWholeFile: Boolean, holder: HighlightInfoHolder, action: Runnable): Boolean { val file = psiFile as? KtFile ?: return false val highlightingLevelManager = HighlightingLevelManager.getInstance(file.project) if (highlightingLevelManager.runEssentialHighlightingOnly(file)) { return true } try { analyze(file, holder) action.run() } catch (e: Throwable) { if (e is ControlFlowException) throw e if (KotlinHighlightingSuspender.getInstance(file.project).suspend(file.virtualFile)) { throw e } else { LOG.warn(e) } } finally { afterAnalysisVisitor = null } return true } private fun analyze(file: KtFile, holder: HighlightInfoHolder) { val dividedElements: List<Divider.DividedElements> = ArrayList() Divider.divideInsideAndOutsideAllRoots( file, file.textRange, file.textRange, { true }, CommonProcessors.CollectProcessor(dividedElements) ) // TODO: for the sake of check that element belongs to the file // for some reason analyzeWithAllCompilerChecks could return psiElements those do not belong to the file // see [ScriptConfigurationHighlightingTestGenerated$Highlighting.testCustomExtension] val elements = dividedElements.flatMap(Divider.DividedElements::inside).toSet() // annotate diagnostics on fly: show diagnostics as soon as front-end reports them // don't create quick fixes as it could require some resolve val highlightInfoByDiagnostic = mutableMapOf<Diagnostic, HighlightInfo>() val highlightInfoByTextRange = mutableMapOf<TextRange, HighlightInfo>() // render of on-fly diagnostics with descriptors could lead to recursion fun checkIfDescriptor(candidate: Any?): Boolean = candidate is DeclarationDescriptor || candidate is Collection<*> && candidate.any(::checkIfDescriptor) val shouldHighlightErrors = file.shouldHighlightErrors() val analysisResult = if (shouldHighlightErrors) { file.analyzeWithAllCompilerChecks( { val element = it.psiElement if (element in elements && it !in highlightInfoByDiagnostic && !RenderingContext.parameters(it).any(::checkIfDescriptor) ) { annotateDiagnostic( element, holder, it, highlightInfoByDiagnostic, highlightInfoByTextRange ) } } ) } else { file.analyzeWithAllCompilerChecks() } // resolve is done! val bindingContext = file.actionUnderSafeAnalyzeBlock( { analysisResult.throwIfError() analysisResult.bindingContext }, { BindingContext.EMPTY } ) afterAnalysisVisitor = getAfterAnalysisVisitor(holder, bindingContext) cleanUpCalculatingAnnotations(highlightInfoByTextRange) if (!shouldHighlightErrors) return for (diagnostic in bindingContext.diagnostics) { val psiElement = diagnostic.psiElement if (psiElement !in elements) continue // has been processed earlier e.g. on-fly or for some reasons it could be duplicated diagnostics for the same factory // see [PsiCheckerTestGenerated$Checker.testRedeclaration] if (diagnostic in highlightInfoByDiagnostic) continue // annotate diagnostics those were not possible to report (and therefore render) on-the-fly annotateDiagnostic(psiElement, holder, diagnostic, highlightInfoByDiagnostic, calculatingInProgress = false) } // apply quick fixes for all diagnostics grouping by element highlightInfoByDiagnostic.keys .groupBy { it.psiElement } .forEach { annotateQuickFixes(it.key, it.value, highlightInfoByDiagnostic) } } private fun annotateDiagnostic( element: PsiElement, holder: HighlightInfoHolder, diagnostic: Diagnostic, highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>? = null, highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>? = null, calculatingInProgress: Boolean = true ) = annotateDiagnostics( element, holder, listOf(diagnostic), highlightInfoByDiagnostic, highlightInfoByTextRange, calculatingInProgress ) private fun cleanUpCalculatingAnnotations(highlightInfoByTextRange: Map<TextRange, HighlightInfo>) { highlightInfoByTextRange.values.forEach { annotation -> annotation.unregisterQuickFix { it is CalculatingIntentionAction } } } private fun annotateDiagnostics( element: PsiElement, holder: HighlightInfoHolder, diagnostics: List<Diagnostic>, highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>? = null, highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>? = null, calculatingInProgress: Boolean = false ) = annotateDiagnostics( element, holder, diagnostics, highlightInfoByDiagnostic, highlightInfoByTextRange, ::shouldSuppressUnusedParameter, noFixes = true, calculatingInProgress = calculatingInProgress ) /** * [diagnostics] has to belong to the same element */ private fun annotateQuickFixes( element: PsiElement, diagnostics: List<Diagnostic>, highlightInfoByDiagnostic: Map<Diagnostic, HighlightInfo> ) { if (diagnostics.isEmpty()) return assertBelongsToTheSameElement(element, diagnostics) ElementAnnotator(element) { param -> shouldSuppressUnusedParameter(param) }.registerDiagnosticsQuickFixes(diagnostics, highlightInfoByDiagnostic) } protected open fun shouldSuppressUnusedParameter(parameter: KtParameter): Boolean = false companion object { private val LOG = Logger.getInstance(AbstractKotlinHighlightVisitor::class.java) private val UNRESOLVED_KEY = Key<Unit>("KotlinHighlightVisitor.UNRESOLVED_KEY") private val DO_NOT_HIGHLIGHT_KEY = Key<Unit>("DO_NOT_HIGHLIGHT_KEY") @JvmStatic fun KtElement.suppressHighlight() { putUserData(DO_NOT_HIGHLIGHT_KEY, Unit) forEachDescendantOfType<KtElement> { it.putUserData(DO_NOT_HIGHLIGHT_KEY, Unit) } } @JvmStatic fun KtElement.unsuppressHighlight() { putUserData(DO_NOT_HIGHLIGHT_KEY, null) forEachDescendantOfType<KtElement> { it.putUserData(DO_NOT_HIGHLIGHT_KEY, null) } } fun getAfterAnalysisVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) = arrayOf( PropertiesHighlightingVisitor(holder, bindingContext), FunctionsHighlightingVisitor(holder, bindingContext), VariablesHighlightingVisitor(holder, bindingContext), TypeKindHighlightingVisitor(holder, bindingContext) ) fun wasUnresolved(element: KtNameReferenceExpression) = element.getUserData(UNRESOLVED_KEY) != null internal fun assertBelongsToTheSameElement(element: PsiElement, diagnostics: Collection<Diagnostic>) { assert(diagnostics.all { it.psiElement == element }) } fun annotateDiagnostics( element: PsiElement, holder: HighlightInfoHolder, diagnostics: Collection<Diagnostic>, highlightInfoByDiagnostic: MutableMap<Diagnostic, HighlightInfo>? = null, highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>? = null, shouldSuppressUnusedParameter: (KtParameter) -> Boolean = { false }, noFixes: Boolean = false, calculatingInProgress: Boolean = false ) { if (diagnostics.isEmpty()) return element.getUserData(DO_NOT_HIGHLIGHT_KEY)?.let { return } assertBelongsToTheSameElement(element, diagnostics) if (element is KtNameReferenceExpression) { val unresolved = diagnostics.any { it.factory == Errors.UNRESOLVED_REFERENCE } element.putUserData(UNRESOLVED_KEY, if (unresolved) Unit else null) } ElementAnnotator(element) { param -> shouldSuppressUnusedParameter(param) }.registerDiagnosticsAnnotations( holder, diagnostics, highlightInfoByDiagnostic, highlightInfoByTextRange, noFixes = noFixes, calculatingInProgress = calculatingInProgress ) } } }
apache-2.0
30375051a12d3a1c66dc7f7d24dd127d
41.063433
129
0.67054
5.792909
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinSetupEnvironmentNotificationProvider.kt
1
6737
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.configuration import com.intellij.ide.JavaUiBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.EditorNotificationProvider.CONST_NULL import com.intellij.ui.EditorNotifications import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.configuration.ui.KotlinConfigurationCheckerService import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.idea.versions.SuppressNotificationState import org.jetbrains.kotlin.idea.versions.UnsupportedAbiVersionNotificationPanelProvider import org.jetbrains.kotlin.idea.versions.createComponentActionLabel import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import java.util.function.Function import javax.swing.JComponent // Code is partially copied from com.intellij.codeInsight.daemon.impl.SetupSDKNotificationProvider class KotlinSetupEnvironmentNotificationProvider : EditorNotificationProvider { override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!file.isKotlinFileType()) { return CONST_NULL } val psiFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return CONST_NULL if (psiFile.language !== KotlinLanguage.INSTANCE) { return CONST_NULL } val module = ModuleUtilCore.findModuleForPsiElement(psiFile) ?: return CONST_NULL if (!ModuleRootManager.getInstance(module).fileIndex.isInSourceContent(file)) { return CONST_NULL } if (ModuleRootManager.getInstance(module).sdk == null && TargetPlatformDetector.getPlatform(psiFile).isJvm() ) { return createSetupSdkPanel(project, psiFile) } val configurationChecker = KotlinConfigurationCheckerService.getInstance(module.project) if (!configurationChecker.isSyncing && isNotConfiguredNotificationRequired(module.toModuleGroup()) && !hasAnyKotlinRuntimeInScope(module) && UnsupportedAbiVersionNotificationPanelProvider.collectBadRoots(module).isEmpty() ) { return createKotlinNotConfiguredPanel(module, getAbleToRunConfigurators(module).toList()) } return CONST_NULL } companion object { private fun createSetupSdkPanel(project: Project, file: PsiFile): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor).apply { text = JavaUiBundle.message("project.sdk.not.defined") createActionLabel(ProjectBundle.message("project.sdk.setup")) { ProjectSettingsService.getInstance(project).chooseAndSetSdk() ?: return@createActionLabel runWriteAction { val module = ModuleUtilCore.findModuleForPsiElement(file) if (module != null) { ModuleRootModificationUtil.setSdkInherited(module) } } } } } private fun createKotlinNotConfiguredPanel(module: Module, configurators: List<KotlinProjectConfigurator>): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor).apply { text = KotlinJvmBundle.message("kotlin.not.configured") if (configurators.isNotEmpty()) { val project = module.project createComponentActionLabel(KotlinJvmBundle.message("action.text.configure")) { label -> val singleConfigurator = configurators.singleOrNull() if (singleConfigurator != null) { singleConfigurator.apply(project) } else { val configuratorsPopup = createConfiguratorsPopup(project, configurators) configuratorsPopup.showUnderneathOf(label) } } createComponentActionLabel(KotlinJvmBundle.message("action.text.ignore")) { SuppressNotificationState.suppressKotlinNotConfigured(module) EditorNotifications.getInstance(project).updateAllNotifications() } } } } private fun KotlinProjectConfigurator.apply(project: Project) { configure(project, emptyList()) EditorNotifications.getInstance(project).updateAllNotifications() checkHideNonConfiguredNotifications(project) } fun createConfiguratorsPopup(project: Project, configurators: List<KotlinProjectConfigurator>): ListPopup { val step = object : BaseListPopupStep<KotlinProjectConfigurator>( KotlinJvmBundle.message("title.choose.configurator"), configurators ) { override fun getTextFor(value: KotlinProjectConfigurator?) = value?.presentableText ?: "<none>" override fun onChosen(selectedValue: KotlinProjectConfigurator?, finalChoice: Boolean): PopupStep<*>? { return doFinalStep { selectedValue?.apply(project) } } } return JBPopupFactory.getInstance().createListPopup(step) } } }
apache-2.0
a48ffceb1ad7d26bb3fdda0c4183cf1c
47.467626
158
0.680422
5.772922
false
true
false
false
Zeroami/CommonLib-Kotlin
commonlib/src/main/java/com/zeroami/commonlib/utils/LCircularAnimUtils.kt
1
6305
package com.zeroami.commonlib.utils import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewAnimationUtils import android.view.ViewGroup import android.widget.ImageView /** * Android水波动画帮助类,轻松实现View show/hide/startActivity()特效 * * @author Zeroami */ object LCircularAnimUtils { val PERFECT_MILLS: Long = 618 val MINI_RADIUS = 0 /** * 向四周伸张,直到完成显示。 */ @SuppressLint("NewApi") fun show(myView: View, startRadius: Float, durationMills: Long) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { myView.visibility = View.VISIBLE return } val cx = (myView.left + myView.right) / 2 val cy = (myView.top + myView.bottom) / 2 val w = myView.width val h = myView.height // 勾股定理 & 进一法 val finalRadius = Math.sqrt((w * w + h * h).toDouble()).toInt() + 1 val anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, startRadius, finalRadius.toFloat()) myView.visibility = View.VISIBLE anim.duration = durationMills anim.start() } /** * 由满向中间收缩,直到隐藏。 */ @SuppressLint("NewApi") fun hide(myView: View, endRadius: Float, durationMills: Long) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { myView.visibility = View.INVISIBLE return } val cx = (myView.left + myView.right) / 2 val cy = (myView.top + myView.bottom) / 2 val w = myView.width val h = myView.height // 勾股定理 & 进一法 val initialRadius = Math.sqrt((w * w + h * h).toDouble()).toInt() + 1 val anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius.toFloat(), endRadius) anim.duration = durationMills anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) myView.visibility = View.INVISIBLE } }) anim.start() } /** * 从指定View开始向四周伸张(伸张颜色或图片为colorOrImageRes), 然后进入另一个Activity,返回至 @thisActivity 后显示收缩动画。 */ @SuppressLint("NewApi") fun startActivityForResult( thisActivity: Activity, intent: Intent, requestCode: Int?, bundle: Bundle?, triggerView: View, colorOrImageRes: Int, durationMills: Long) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { thisActivity.startActivity(intent) return } val location = IntArray(2) triggerView.getLocationInWindow(location) val cx = location[0] + triggerView.width / 2 val cy = location[1] + triggerView.height / 2 val view = ImageView(thisActivity) view.scaleType = ImageView.ScaleType.CENTER_CROP view.setImageResource(colorOrImageRes) val decorView = thisActivity.window.decorView as ViewGroup val w = decorView.width val h = decorView.height decorView.addView(view, w, h) val finalRadius = Math.sqrt((w * w + h * h).toDouble()).toInt() + 1 val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0f, finalRadius.toFloat()) anim.duration = durationMills anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) if (requestCode == null) { thisActivity.startActivity(intent) } else if (bundle == null) { thisActivity.startActivityForResult(intent, requestCode) } else { thisActivity.startActivityForResult(intent, requestCode, bundle) } // 默认渐隐过渡动画. thisActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) // 默认显示返回至当前Activity的动画. triggerView.postDelayed({ val anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, finalRadius.toFloat(), 0f) anim.duration = durationMills anim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) try { decorView.removeView(view) } catch (e: Exception) { e.printStackTrace() } } }) anim.start() }, 1000) } }) anim.start() } /*下面的方法全是重载,用简化上面方法的构建*/ fun startActivityForResult( thisActivity: Activity, intent: Intent, requestCode: Int?, triggerView: View, colorOrImageRes: Int) { startActivityForResult(thisActivity, intent, requestCode, null, triggerView, colorOrImageRes, PERFECT_MILLS) } @JvmOverloads fun startActivity( thisActivity: Activity, intent: Intent, triggerView: View, colorOrImageRes: Int, durationMills: Long = PERFECT_MILLS) { startActivityForResult(thisActivity, intent, null, null, triggerView, colorOrImageRes, durationMills) } fun startActivity(thisActivity: Activity, targetClass: Class<*>, triggerView: View, colorOrImageRes: Int) { startActivity(thisActivity, Intent(thisActivity, targetClass), triggerView, colorOrImageRes, PERFECT_MILLS) } fun show(myView: View) { show(myView, MINI_RADIUS.toFloat(), PERFECT_MILLS) } fun hide(myView: View) { hide(myView, MINI_RADIUS.toFloat(), PERFECT_MILLS) } }
apache-2.0
46ae9d8d2412e7ae3aaf24dbf5c86b97
34.769231
131
0.608437
4.308624
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/util/animation/Animations.kt
8
6396
// 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("Animations") package com.intellij.util.animation import com.intellij.ui.ColorUtil import java.awt.Color import java.awt.Dimension import java.awt.Point import java.awt.Rectangle import java.util.function.Consumer import java.util.function.DoubleConsumer import java.util.function.DoubleFunction import java.util.function.IntConsumer import java.util.function.LongConsumer import kotlin.math.roundToInt import kotlin.math.roundToLong /** * Update [animations] delay time in such a way that * animations will be run one by one. */ fun makeSequent(vararg animations: Animation): Collection<Animation> { for (i in 1 until animations.size) { val prev = animations[i - 1] val curr = animations[i] curr.delay += prev.delay + prev.duration } return animations.toList() } /** * Empty animation (do nothing). * * May be used as an anchor frame for any of [Animation.runWhenScheduled], [Animation.runWhenUpdated] or [Animation.runWhenExpired] methods. */ fun animation(): Animation = Animation {} /** * Very common animation. */ fun animation(consumer: DoubleConsumer) = Animation(consumer) fun animation(from: Int, to: Int, consumer: IntConsumer): Animation { return Animation(DoubleConsumer { value -> consumer.accept((from + value * (to - from)).roundToInt()) }) } fun <T> animation(context: AnimationContext<T>, function: DoubleFunction<T>): Animation { return Animation.withContext(context, function) } fun animation(from: Long, to: Long, consumer: LongConsumer): Animation { return Animation(DoubleConsumer { value -> consumer.accept((from + value * (to - from)).roundToLong()) }) } fun animation(from: Float, to: Float, consumer: FloatConsumer): Animation { // To prevent precision lost, convert values into double. // Example of precision lost is: // 0.9f + (1.0f * (0.1f - 0.9f)) == 0.100000024 return animation(from.toDouble(), to.toDouble(), DoubleConsumer { consumer.accept(it.toFloat()) }) } fun animation(from: Double, to: Double, consumer: DoubleConsumer): Animation { return Animation(DoubleConsumer { value -> consumer.accept(from + value * (to - from)) }) } fun animation(from: Point, to: Point, consumer: Consumer<Point>): Animation { return Animation(DoublePointFunction(from, to), consumer) } fun animation(from: Rectangle, to: Rectangle, consumer: Consumer<Rectangle>): Animation { return Animation(DoubleRectangleFunction(from, to), consumer) } fun <T> animation(values: Array<T>, consumer: Consumer<T>): Animation { return Animation(DoubleArrayFunction(values), consumer) } fun animation(from: Dimension, to: Dimension, consumer: Consumer<Dimension>): Animation { return Animation(DoubleDimensionFunction(from, to), consumer) } fun animation(from: Color, to: Color, consumer: Consumer<Color>): Animation { return Animation(DoubleColorFunction(from, to), consumer) } fun transparent(color: Color, consumer: Consumer<Color>) = animation(color, ColorUtil.withAlpha(color, 0.0), consumer) fun <T> consumer(function: DoubleFunction<T>, consumer: Consumer<T>): DoubleConsumer { return DoubleConsumer { consumer.accept(function.apply(it)) } } private fun text(from: String, to: String): DoubleFunction<String> { val shorter = if (from.length < to.length) from else to val longer = if (from === shorter) to else from if (shorter.length == longer.length || !longer.startsWith(shorter)) { val fraction = from.length.toDouble() / (from.length + to.length) return DoubleFunction { timeline: Double -> if (timeline < fraction) { from.substring(0, (from.length * ((fraction - timeline) / fraction)).roundToInt()) } else { to.substring(0, (to.length * (timeline - fraction) / (1 - fraction)).roundToInt()) } } } return if (from === shorter) { DoubleFunction { timeline: Double -> longer.substring(0, (shorter.length + (longer.length - shorter.length) * timeline).roundToInt()) } } else { DoubleFunction { timeline: Double -> longer.substring(0, (longer.length - (longer.length - shorter.length) * timeline).roundToInt()) } } } fun animation(from: String, to: String, consumer: Consumer<String>): Animation { return Animation(text(from, to), consumer) } private fun range(from: Int, to: Int): DoubleIntFunction { return DoubleIntFunction { value -> (from + value * (to - from)).toInt() } } private fun interface DoubleIntFunction { fun apply(value: Double): Int } class DoubleColorFunction( val from: Color, val to: Color ) : DoubleFunction<Color> { private val red = range(from.red, to.red) private val green = range(from.green, to.green) private val blue = range(from.blue, to.blue) private val alpha = range(from.alpha, to.alpha) override fun apply(value: Double) = Color( red.apply(value), green.apply(value), blue.apply(value), alpha.apply(value) ) } class DoublePointFunction( val from: Point, val to: Point ) : DoubleFunction<Point> { private val x = range(from.x, to.x) private val y = range(from.y, to.y) override fun apply(value: Double): Point { return Point(x.apply(value), y.apply(value)) } } class DoubleDimensionFunction( val from: Dimension, val to: Dimension ) : DoubleFunction<Dimension> { private val width = range(from.width, to.width) private val height = range(from.height, to.height) override fun apply(value: Double) = Dimension( width.apply(value), height.apply(value) ) } class DoubleRectangleFunction( val from: Rectangle, val to: Rectangle ) : DoubleFunction<Rectangle> { private val x = range(from.x, to.x) private val y = range(from.y, to.y) private val width = range(from.width, to.width) private val height = range(from.height, to.height) override fun apply(value: Double) = Rectangle( x.apply(value), y.apply(value), width.apply(value), height.apply(value) ) } /** * For any value in [0.0, 1.0] chooses value from an array. */ class DoubleArrayFunction<T>( val array: Array<T> ) : DoubleFunction<T> { override fun apply(value: Double): T { return array[(array.size * value).roundToInt().coerceIn(0, (array.size - 1))] } } fun interface FloatConsumer { fun accept(value: Float) }
apache-2.0
4c9a9ce3b640ae20a83d125ff0e4ac80
28.753488
140
0.702939
3.636157
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ConverterSettings.kt
2
881
// 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.j2k data class ConverterSettings( var forceNotNullTypes: Boolean, var specifyLocalVariableTypeByDefault: Boolean, var specifyFieldTypeByDefault: Boolean, var openByDefault: Boolean, var publicByDefault: Boolean ) { companion object { val defaultSettings: ConverterSettings = ConverterSettings( forceNotNullTypes = true, specifyLocalVariableTypeByDefault = false, specifyFieldTypeByDefault = false, openByDefault = false, publicByDefault = false ) val publicByDefault: ConverterSettings = defaultSettings.copy(publicByDefault = true) } }
apache-2.0
7f4a9f42912ce48f56676bb5b0733646
35.708333
158
0.677639
5.404908
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/GroovyClosureType.kt
5
3779
// 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 org.jetbrains.plugins.groovy.lang.typing import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.util.containers.minimalElements import com.intellij.util.recursionSafeLazy import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.groovy.lang.psi.impl.GrLiteralClassType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.resolve.api.ArgumentMapping import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.api.CallSignature import org.jetbrains.plugins.groovy.lang.resolve.impl.compare import org.jetbrains.plugins.groovy.lang.resolve.impl.filterApplicable abstract class GroovyClosureType( private val myContext: PsiElement ) : GrLiteralClassType(LanguageLevel.JDK_1_5, myContext) { override fun isValid(): Boolean = myContext.isValid final override fun getJavaClassName(): String = GROOVY_LANG_CLOSURE final override fun setLanguageLevel(languageLevel: LanguageLevel): PsiClassType = error("must not be called") @NonNls final override fun toString(): String = "Closure" final override fun getParameters(): Array<out PsiType?> = myTypeArguments ?: PsiType.EMPTY_ARRAY private val myTypeArguments: Array<out PsiType?>? by recursionSafeLazy { val closureClazz = resolve() if (closureClazz == null || closureClazz.typeParameters.size != 1) { return@recursionSafeLazy PsiType.EMPTY_ARRAY } val type: PsiType? = returnType(null) if (type == null || type === PsiType.NULL) { arrayOf<PsiType?>(null) } else { arrayOf(TypesUtil.boxPrimitiveType(type, psiManager, resolveScope, true)) } } abstract val signatures: List<@JvmWildcard CallSignature<*>> open fun curry(position: Int, arguments: Arguments, context: PsiElement): PsiType { return GroovyCurriedClosureType(this, position, arguments, 0, context) } open fun returnType(arguments: Arguments?): PsiType? { val returnTypes = applicableSignatures(arguments).map { it.returnType } return when (returnTypes.size) { 0 -> null 1 -> returnTypes[0] else -> TypesUtil.getLeastUpperBoundNullable(returnTypes, myContext.manager) } } fun applicableSignatures(arguments: Arguments?): Collection<CallSignature<*>> { return if (arguments == null) { signatures } else { doApplyTo(arguments).map { it.first } } } fun applyTo(arguments: Arguments): Collection<ArgumentMapping<*>> { return doApplyTo(arguments).map { it.second } } private fun doApplyTo(arguments: Arguments): Collection<SignatureMapping> { val allMappings: List<SignatureMapping> = signatures.mapNotNull { it.applyTo(arguments, myContext)?.let { mapping -> SignatureMapping(it, mapping) } } val (applicable, canChooseOverload) = allMappings.filterApplicable { (_, mapping) -> mapping.applicability() } if (applicable.isEmpty()) { return allMappings } return if (canChooseOverload) { applicable.minimalElements(comparator) } else { applicable } } } private typealias SignatureMapping = Pair<CallSignature<*>, ArgumentMapping<*>> private val comparator: Comparator<SignatureMapping> = Comparator.comparing( { it.second }, { left: ArgumentMapping<*>, right: ArgumentMapping<*> -> compare(left, right) } )
apache-2.0
cdb3d1cdd729e90c07505cdaf478d275
34.990476
140
0.733792
4.313927
false
false
false
false
smmribeiro/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/elements/ProductionModuleSourceElementType.kt
9
1502
// 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.packaging.impl.elements import com.intellij.icons.AllIcons import com.intellij.openapi.compiler.JavaCompilerBundle import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModulePointer import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ModulesProvider import javax.swing.Icon class ProductionModuleSourceElementType private constructor() : ModuleElementTypeBase<ProductionModuleSourcePackagingElement>( "module-source", JavaCompilerBundle.messagePointer("element.type.name.module.source")) { override fun isSuitableModule(modulesProvider: ModulesProvider, module: Module): Boolean { return modulesProvider.getRootModel(module).getSourceRootUrls(false).isNotEmpty() } override fun createElement(project: Project, pointer: ModulePointer) = ProductionModuleSourcePackagingElement(project, pointer) override fun createEmpty(project: Project) = ProductionModuleSourcePackagingElement(project) override fun getCreateElementIcon(): Icon = AllIcons.Nodes.Package override fun getElementIcon(module: Module?): Icon = AllIcons.Nodes.Package override fun getElementText(moduleName: String) = JavaCompilerBundle.message("node.text.0.module.sources", moduleName) companion object { @JvmField val ELEMENT_TYPE = ProductionModuleSourceElementType() } }
apache-2.0
6b628688f26c3b55547a21600de98632
50.793103
140
0.819574
4.664596
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/typealiasExpansionIndex/generics.kt
13
125
class A<T> typealias TA<T> = A<T> // CONTAINS (key="A", value="TA") typealias TB = A<Any> // CONTAINS (key="A", value="TB")
apache-2.0
7101d82ec73967e15648380bdd6f90f3
17
33
0.592
2.358491
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/ResourceProvider.kt
5
4636
// 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 org.intellij.plugins.markdown.ui.preview import org.jetbrains.annotations.ApiStatus import java.io.File import kotlin.reflect.KClass interface ResourceProvider { /** * Resource description, containing resource content and it's type. * In case type is null, [PreviewStaticServer] will try to guess it based * on resource name. */ class Resource( val content: ByteArray, val type: String? = null ) /** * @return true if this resource provider can load resource [resourceName] * with it's [loadResource] method. */ fun canProvide(resourceName: String): Boolean /** * Load [resourceName] contents. * * @param resourceName Resource path. * @return [Resource] if resource was successfully loaded or null if load failed. */ fun loadResource(resourceName: String): Resource? /** * Default resource provider implementation with * [canProvide] and [loadResource] returning always false and null. */ class DefaultResourceProvider: ResourceProvider { override fun canProvide(resourceName: String): Boolean = false override fun loadResource(resourceName: String): Resource? = null } companion object { /** * Shared instance of [DefaultResourceProvider]. */ val default: ResourceProvider = DefaultResourceProvider() /** * Load resource using [cls]'s [ClassLoader]. * Note: You might want to explicitly set [contentType] for your resource * if you *care about the encoding*. * * @param cls Java class to get the [ClassLoader] of. * @param path Path of the resource to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. The [PreviewStaticServer] won't set * any charset for guessed content type (except for types declared in [PreviewStaticServer.typesForExplicitUtfCharset]). * You might want to [explicitly set](https://www.w3.org/International/articles/http-charset/index.en#charset) * [contentType] if you *care about encoding*. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun <T> loadInternalResource(cls: Class<T>, path: String, contentType: String? = null): Resource? { return cls.getResourceAsStream(path)?.use { Resource(it.readBytes(), contentType) } } /** * Load resource using [cls]'s [ClassLoader]. * * @param cls Kotlin class to get the [ClassLoader] of. * @param path Path of the resource to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. See [loadInternalResource]. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun <T : Any> loadInternalResource(cls: KClass<T>, path: String, contentType: String? = null): Resource? { return loadInternalResource(cls.java, path, contentType) } /** * See [loadInternalResource] */ @JvmStatic inline fun <reified T : Any> loadInternalResource(path: String, contentType: String? = null): Resource? { return loadInternalResource(T::class.java, path, contentType) } /** * Load resource from the filesystem. * * @param file File to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. See [loadInternalResource]. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun loadExternalResource(file: File, contentType: String? = null): Resource? { if (!file.exists()) { return null } val content = file.inputStream().use { it.readBytes() } return Resource(content, contentType) } @ApiStatus.Experimental @JvmStatic fun createResourceProviderChain(vararg providers: ResourceProvider): ResourceProvider { return object: ResourceProvider { override fun canProvide(resourceName: String): Boolean { return providers.any { it.canProvide(resourceName) } } override fun loadResource(resourceName: String): Resource? { return providers.firstNotNullOfOrNull { it.loadResource(resourceName) } } } } } }
apache-2.0
09a4bd1b65fbae047f570da7af80ddd9
36.088
140
0.683348
4.571992
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/groovyPatterns.kt
3
1715
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.patterns import com.intellij.openapi.util.Key import com.intellij.patterns.PatternCondition import com.intellij.util.ProcessingContext import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression val closureCallKey = Key.create<GrCall>("groovy.pattern.closure.call") inline fun <reified T : GroovyPsiElement> groovyElement() = GroovyElementPattern.Capture(T::class.java) inline fun <reified T : GrExpression> groovyExpression() = GroovyExpressionPattern.Capture(T::class.java) fun groovyList() = groovyExpression<GrListOrMap>().with(object : PatternCondition<GrListOrMap>("isList") { override fun accepts(t: GrListOrMap, context: ProcessingContext?) = !t.isMap }) fun psiMethod(containingClass: String, vararg name: String) = GroovyPatterns.psiMethod().withName(*name).definedInClass(containingClass) fun groovyClosure() = GroovyClosurePattern() val groovyAnnotationArgumentValue = groovyElement<GrAnnotationMemberValue>() val groovyAnnotationArgument = GroovyAnnotationArgumentPattern.Capture() val groovyAnnotationArgumentList = groovyElement<GrAnnotationArgumentList>()
apache-2.0
d82c163ef3bacaac85ed208f667cce9c
56.166667
140
0.830321
4.330808
false
false
false
false
NicholasFeldman/NudeKt
src/main/kotlin/tech/feldman/nudekt/region/Region.kt
1
785
package tech.feldman.nudekt.region import tech.feldman.nudekt.extensions.Polygon import tech.feldman.nudekt.extensions.contains internal class Region : ArrayList<Pixel>() { fun leftMost() = minBy { it.x } ?: this[0] fun rightMost() = maxBy { it.x } ?: this[0] fun upperMost() = minBy { it.y } ?: this[0] fun lowerMost() = maxBy { it.y } ?: this[0] fun skinRateInBoundingPolygon(): Float { val poly = Polygon(leftMost(), upperMost(), rightMost(), lowerMost()) var total = 0F var skin = 0F for (pixel in this) { if (poly.contains(pixel) && pixel.isSkin) { skin++ } total++ } return skin / total } fun averageIntensity() = map { it.v }.sum() / size }
mit
0ea0c1fc785c095ae4b6f1e6b44d5994
25.166667
77
0.565605
3.488889
false
false
false
false
drmashu/koshop
src/main/kotlin/io/github/drmashu/koshop/action/manage/ManageItemAction.kt
1
3881
package io.github.drmashu.koshop.action.manage import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import io.github.drmashu.buri.HtmlAction import io.github.drmashu.dikon.inject import io.github.drmashu.koshop.action.ItemAction import io.github.drmashu.koshop.dao.ItemDao import io.github.drmashu.koshop.dao.ItemImageDao import io.github.drmashu.koshop.dao.getNextId import io.github.drmashu.koshop.model.Item import io.github.drmashu.koshop.model.ItemImage import org.apache.logging.log4j.LogManager import org.seasar.doma.jdbc.Config import org.seasar.doma.jdbc.tx.TransactionManager import javax.servlet.ServletContext import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.Part import javax.sql.rowset.serial.SerialBlob import kotlin.text.Regex /** * Created by drmashu on 2015/10/17. */ public class ManageItemAction(context: ServletContext, request: HttpServletRequest, response: HttpServletResponse, @inject("doma_config") val domaConfig: Config, val itemDao: ItemDao, val itemImageDao: ItemImageDao, val id: String?): HtmlAction(context, request, response) { companion object{ val logger = LogManager.getLogger(ItemAction::class.java) val objectMapper = ObjectMapper().registerModule(KotlinModule()) } val transactionManager: TransactionManager init { logger.entry(request, response, itemDao, id) transactionManager = domaConfig.transactionManager } /** * */ override fun get() { logger.entry() val itemId = id!! val item = itemDao.selectById(itemId) item.images = itemImageDao.selectByItemIdWithoutBlob(itemId).toArrayList() responseByJson(item) logger.exit() } /** * */ override fun post() { logger.entry() transactionManager.required { val id = itemDao.getNextId() val item = getItem() item.id = id itemDao.insert(item) insertItemImages(item, request.parts) responseByJson(item) } logger.exit() } /** * */ private fun getItem(): Item { logger.entry() val reader = request.getPart("item").inputStream.bufferedReader("UTF-8") var data = "" while(reader.ready()) { data += reader.readLine() } logger.trace(data) val result = objectMapper.readValue(data, Item::class.java) logger.exit(result) return result } /** * */ override fun put() { logger.entry() transactionManager.required { val item = getItem() itemDao.update(item) insertItemImages(item, request.parts) responseByJson(item) } logger.exit() } private fun insertItemImages(item: Item, parts: MutableCollection<Part>) { for (part in parts) { logger.trace(part.name) insertItemImage(item, part) } } private fun insertItemImage(item: Item, part: Part) { val itemImg = ItemImage() itemImg.itemId = item.id val matched = Regex("images\\[([0-9]+)\\]").matchEntire(part.name) if (matched != null) { itemImg.index = matched.groups[1]!!.value.toInt() as Byte itemImg.contentType = part.contentType val buf = part.inputStream.readBytes() val image = SerialBlob(buf) itemImg.image = image itemImageDao.insert(itemImg) } } /** * */ override fun delete() { logger.entry() transactionManager.required { val item = getItem() itemDao.delete(item) responseByJson(item) } logger.exit() } }
apache-2.0
276ecb3161aceda975bf91c9880d1bf6
29.093023
274
0.632054
4.283664
false
false
false
false
sg26565/hott-transmitter-config
HoTT-TTS/src/main/kotlin/de/treichels/hott/tts/Text2SpeechProvider.kt
1
1398
package de.treichels.hott.tts import java.util.* import javax.sound.sampled.AudioInputStream enum class Gender { Male, Female, Unknown } enum class Age { Adult, Child, Unknown } open class Voice { var enabled: Boolean = false lateinit var age: Age lateinit var locale: Locale lateinit var description: String lateinit var gender: Gender lateinit var id: String lateinit var name: String override fun toString() = description } open class Quality(val sampleRate: Int, val channels: Int, val sampleSize: Int = 16) { override fun toString(): String { return "${sampleRate / 1000}kHz ${if (channels == 1) "mono" else "stereo"}" } } abstract class Text2SpeechProvider { abstract val enabled: Boolean abstract val qualities: List<Quality> abstract val name: String open val defaultVoice: Voice get() = installedVoices().find { it.locale == Locale.getDefault() } ?: installedVoices().first() open val defaultQuality: Quality = Quality(24000, 2) open val speedSupported = true open val volumeSupported = true open val ssmlSupported = true abstract fun installedVoices(): List<Voice> abstract fun speak(text: String, voice: Voice = defaultVoice, speed: Int = 0, volume: Int = 100, quality: Quality = defaultQuality, ssml: Boolean = false): AudioInputStream override fun toString() = name }
lgpl-3.0
1b11525e5e1694198d7fd984c12c1924
28.744681
176
0.697425
4.223565
false
false
false
false
ZoranPandovski/al-go-rithms
data_structures/y_fast_trie/Kotlin/YFastTrie.kt
1
7046
/** * Y-fast trie is a data structure for storing integers from a bounded domain * It supports exact and predecessor or successor queries in time O(log log M), using O(n) space, * where n is the number of stored values and M is the maximum value in the domain. * More info about the structure and complexity here: https://en.wikipedia.org/wiki/Y-fast_trie * * The prerequisites are the XFastTrie (al-go-rithms/data_structures/x_fast_trie/Kotlin/XFastTrie.kt) and a Balanced BST. * In this implementation a Treap is used (al-go-rithms/data_structures/treap/Kotlin/persistent_treap.kt) */ class XFastMap<T>(domain: Long) { private val base = XFastTrie(domain) private val valueTable: MutableMap<Long, T> = HashMap() fun add(entry: Pair<Long, T>) { base.add(entry.first) valueTable.put(entry.first, entry.second) } fun emplace(key: Long, value: T) { valueTable[key] = value } fun successor(key: Long): Pair<Long?, T?> { val nextKey = base.successor(key) return Pair(nextKey, valueTable.get(nextKey)) } fun predecessor(key: Long): Pair<Long?, T?> { val nextKey = base.predecessor(key) return Pair(nextKey, valueTable.get(nextKey)) } fun get(key: Long) = valueTable.get(key) fun delete(key: Long) { base.delete(key) valueTable.remove(key) } } class YFastTrie(domain: Long) { class Node(val representative: Long, val bst: PersistentTreap<Long> = PersistentTreap()) private val xFast: XFastMap<Node> = XFastMap(domain) private val logM: Int = java.lang.Long.numberOfLeadingZeros(0) - java.lang.Long.numberOfLeadingZeros(domain) + 1 fun find(key: Long): Boolean { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key+1).second return (succRepr?.bst?.search(key) ?: false) or (prevRepr?.bst?.search(key) ?: false) } fun successor(key: Long): Long? { var succRepr = xFast.successor(key).second if (succRepr != null && succRepr.bst.successor(key) == null) succRepr = xFast.successor(succRepr.representative).second val prevRepr = xFast.predecessor(key+1).second val succ1 = succRepr?.bst?.successor(key) val succ2 = prevRepr?.bst?.successor(key) if (succ1 == null) return succ2 if (succ2 == null) return succ1 return java.lang.Long.min(succ1, succ2) } fun predecessor(key: Long): Long? { val succRepr = xFast.successor(key).second var prevRepr = xFast.predecessor(key+1).second if (prevRepr != null && prevRepr.bst.predecessor(key) == null) prevRepr = xFast.predecessor(prevRepr.representative).second val succ1 = succRepr?.bst?.predecessor(key) val succ2 = prevRepr?.bst?.predecessor(key) if (succ1 == null) return succ2 if (succ2 == null) return succ1 return java.lang.Long.max(succ1, succ2) } fun add(key: Long) { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key+1).second val succ1 = succRepr?.bst?.successor(key) val succ2 = prevRepr?.bst?.successor(key) val reprNode = when { succ1 == null -> prevRepr succ2 == null -> succRepr succ1 < succ2 -> succRepr else -> prevRepr } val tree = reprNode?.bst if (tree == null) { val addedTree = PersistentTreap<Long>() + key xFast.add(Pair(key, Node(key, addedTree))) return } val newTree = tree + key if (newTree.size > 2*logM) { val pivot = when { newTree.root!!.rightChild == null -> newTree.root.value - 1 newTree.root.leftChild == null -> newTree.root.value + 1 else -> newTree.root.value } val (leftTree, rightTree) = newTree.split(pivot) xFast.delete(reprNode.representative) val leftRepr = leftTree.root!!.value val rightRepr = rightTree.root!!.value xFast.add(Pair(leftRepr, Node(leftRepr, leftTree))) xFast.add(Pair(rightRepr, Node(rightRepr, rightTree))) } else xFast.emplace(reprNode.representative, Node(reprNode.representative, newTree)) } fun delete(key: Long): Boolean { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key + 1).second val myRepr = when { succRepr?.bst?.search(key) == true -> succRepr prevRepr?.bst?.search(key) == true -> prevRepr else -> return false } val newTree = myRepr.bst - key if (newTree.size >= logM / 4) xFast.emplace(myRepr.representative, Node(myRepr.representative, newTree)) else { val toJoin = xFast.successor(myRepr.representative).second ?: xFast.predecessor(myRepr.representative).second if (toJoin == null) { xFast.emplace(myRepr.representative, Node(myRepr.representative, newTree)) return true } xFast.delete(myRepr.representative) xFast.delete(toJoin.representative) val newR = myRepr.representative xFast.add(Pair(newR, Node(newR, newTree.join(toJoin.bst, newR)))) } return true } } fun<T> List<T>.firstOrNullBinary(predicate: (T) -> Boolean): T? { var step = 1 var pos = this.size while (step < this.size) step *= 2 while (step > 0) { if (pos - step >= 0 && predicate(this[pos-step])) pos -= step step /= 2 } if (pos == this.size) return null return this[pos] } fun checkContains(trie: YFastTrie, values: List<Long>, MAX_VALUE: Long) { val sortedValues = values.sorted() val reverseSortedValues = sortedValues.reversed() for (i in 0..MAX_VALUE) { val myNext = sortedValues.firstOrNullBinary({it > i}) val actualNext = trie.successor(i) val myPrev = reverseSortedValues.firstOrNullBinary({it < i}) val actualPrev = trie.predecessor(i) if (myNext != actualNext) println("error") if (myPrev != actualPrev) println("error") } val myContent = (0..MAX_VALUE).filter { trie.find(it) }.sorted().toLongArray() if (!(myContent contentEquals values.sorted().toLongArray())) println("error") } fun main(args: Array<String>) { val MAX_VALUE = 1000005L val TO_ADD = 200000 val TO_DELETE = 50000 val trie = YFastTrie(MAX_VALUE) val values = (0..MAX_VALUE).shuffled().subList(0, TO_ADD) values.forEach { trie.add(it) } println("Check inserts") checkContains(trie, values, MAX_VALUE) val toDel = values.shuffled().subList(0, TO_DELETE).toSet() val rest = values.filter { !toDel.contains(it) } toDel.forEach { trie.delete(it) } println("Check after delete") checkContains(trie, rest, MAX_VALUE) }
cc0-1.0
45efc84d113b7b426f62eec69f5c4a54
34.054726
121
0.61212
3.692872
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/db/mappers/OrgTimestampMapper.kt
1
4291
package com.orgzly.android.db.mappers import com.orgzly.android.db.entity.OrgTimestamp import com.orgzly.org.datetime.OrgDateTime import com.orgzly.org.datetime.OrgDelay import com.orgzly.org.datetime.OrgInterval import com.orgzly.org.datetime.OrgRepeater import java.util.* /** * <2017-04-16 Sun> * <2017-01-02 Mon 13:00> * <2017-04-16 Sun .+1d> * <2017-01-02 Mon 09:00 ++1d/2d> * <2017-04-16 Sun .+1d -0d> * <2006-11-02 Thu 20:00-22:00> */ object OrgTimestampMapper { fun fromOrgDateTime(dt: OrgDateTime): OrgTimestamp { val string = dt.toString() val isActive = dt.isActive val year = dt.calendar.get(Calendar.YEAR) val month = dt.calendar.get(Calendar.MONTH) + 1 val day = dt.calendar.get(Calendar.DAY_OF_MONTH) val hour = if (dt.hasTime()) dt.calendar.get(Calendar.HOUR_OF_DAY) else null val minute = if (dt.hasTime()) dt.calendar.get(Calendar.MINUTE) else null val second = if (dt.hasTime()) dt.calendar.get(Calendar.SECOND) else null val timestamp = dt.calendar.timeInMillis val endHour = if (dt.hasEndTime()) dt.endCalendar.get(Calendar.HOUR_OF_DAY) else null val endMinute = if (dt.hasEndTime()) dt.endCalendar.get(Calendar.MINUTE) else null val endSecond = if (dt.hasEndTime()) dt.endCalendar.get(Calendar.SECOND) else null val endTimestamp = if (dt.hasEndTime()) dt.endCalendar.timeInMillis else null var repeaterType: Int? = null var repeaterValue: Int? = null var repeaterUnit: Int? = null var habitDeadlineValue: Int? = null var habitDeadlineUnit: Int? = null if (dt.hasRepeater()) { repeaterType = repeaterType(dt.repeater.type) repeaterValue = dt.repeater.value repeaterUnit = timeUnit(dt.repeater.unit) if (dt.repeater.hasHabitDeadline()) { habitDeadlineValue = dt.repeater.habitDeadline.value habitDeadlineUnit = timeUnit(dt.repeater.habitDeadline.unit) } } var delayType: Int? = null var delayValue: Int? = null var delayUnit: Int? = null if (dt.hasDelay()) { delayType = delayType(dt.delay.type) delayValue = dt.delay.value delayUnit = timeUnit(dt.delay.unit) } return OrgTimestamp( 0, string, isActive, year, month, day, hour, minute, second, endHour, endMinute, endSecond, repeaterType, repeaterValue, repeaterUnit, habitDeadlineValue, habitDeadlineUnit, delayType, delayValue, delayUnit, timestamp, endTimestamp ) } private const val UNIT_HOUR = 360 private const val UNIT_DAY = 424 private const val UNIT_WEEK = 507 private const val UNIT_MONTH = 604 private const val UNIT_YEAR = 712 private const val REPEATER_TYPE_CUMULATE = 20 private const val REPEATER_TYPE_CATCH_UP = 22 private const val REPEATER_TYPE_RESTART = 12 private const val DELAY_TYPE_ALL = 1 private const val DELAY_TYPE_FIRST_ONLY = 2 fun repeaterType(type: OrgRepeater.Type): Int { return when (type) { OrgRepeater.Type.CUMULATE -> REPEATER_TYPE_CUMULATE OrgRepeater.Type.CATCH_UP -> REPEATER_TYPE_CATCH_UP OrgRepeater.Type.RESTART -> REPEATER_TYPE_RESTART else -> 0 } } fun timeUnit(unit: OrgInterval.Unit): Int { return when (unit) { OrgInterval.Unit.HOUR -> UNIT_HOUR OrgInterval.Unit.DAY -> UNIT_DAY OrgInterval.Unit.WEEK -> UNIT_WEEK OrgInterval.Unit.MONTH -> UNIT_MONTH OrgInterval.Unit.YEAR -> UNIT_YEAR else -> 0 } } fun delayType(type: OrgDelay.Type): Int { return when (type) { OrgDelay.Type.ALL -> DELAY_TYPE_ALL OrgDelay.Type.FIRST_ONLY -> DELAY_TYPE_FIRST_ONLY else -> 0 } } }
gpl-3.0
835c120bcb5cc26b893ed23739ac1546
30.792593
93
0.58145
3.962142
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/cpu/InstructionEvaluator.kt
1
20078
package com.soywiz.kpspemu.cpu open class InstructionEvaluator<T> : InstructionDecoder() { open fun unimplemented(s: T, i: InstructionType): Unit = TODO("unimplemented: ${i.name} : " + i) open fun add(i: Int, s: T): Unit = unimplemented(s, Instructions.add) open fun addu(i: Int, s: T): Unit = unimplemented(s, Instructions.addu) open fun addi(i: Int, s: T): Unit = unimplemented(s, Instructions.addi) open fun addiu(i: Int, s: T): Unit = unimplemented(s, Instructions.addiu) open fun sub(i: Int, s: T): Unit = unimplemented(s, Instructions.sub) open fun subu(i: Int, s: T): Unit = unimplemented(s, Instructions.subu) open fun and(i: Int, s: T): Unit = unimplemented(s, Instructions.and) open fun andi(i: Int, s: T): Unit = unimplemented(s, Instructions.andi) open fun nor(i: Int, s: T): Unit = unimplemented(s, Instructions.nor) open fun or(i: Int, s: T): Unit = unimplemented(s, Instructions.or) open fun ori(i: Int, s: T): Unit = unimplemented(s, Instructions.ori) open fun xor(i: Int, s: T): Unit = unimplemented(s, Instructions.xor) open fun xori(i: Int, s: T): Unit = unimplemented(s, Instructions.xori) open fun sll(i: Int, s: T): Unit = unimplemented(s, Instructions.sll) open fun sllv(i: Int, s: T): Unit = unimplemented(s, Instructions.sllv) open fun sra(i: Int, s: T): Unit = unimplemented(s, Instructions.sra) open fun srav(i: Int, s: T): Unit = unimplemented(s, Instructions.srav) open fun srl(i: Int, s: T): Unit = unimplemented(s, Instructions.srl) open fun srlv(i: Int, s: T): Unit = unimplemented(s, Instructions.srlv) open fun rotr(i: Int, s: T): Unit = unimplemented(s, Instructions.rotr) open fun rotrv(i: Int, s: T): Unit = unimplemented(s, Instructions.rotrv) open fun slt(i: Int, s: T): Unit = unimplemented(s, Instructions.slt) open fun slti(i: Int, s: T): Unit = unimplemented(s, Instructions.slti) open fun sltu(i: Int, s: T): Unit = unimplemented(s, Instructions.sltu) open fun sltiu(i: Int, s: T): Unit = unimplemented(s, Instructions.sltiu) open fun lui(i: Int, s: T): Unit = unimplemented(s, Instructions.lui) open fun seb(i: Int, s: T): Unit = unimplemented(s, Instructions.seb) open fun seh(i: Int, s: T): Unit = unimplemented(s, Instructions.seh) open fun bitrev(i: Int, s: T): Unit = unimplemented(s, Instructions.bitrev) open fun max(i: Int, s: T): Unit = unimplemented(s, Instructions.max) open fun min(i: Int, s: T): Unit = unimplemented(s, Instructions.min) open fun div(i: Int, s: T): Unit = unimplemented(s, Instructions.div) open fun divu(i: Int, s: T): Unit = unimplemented(s, Instructions.divu) open fun mult(i: Int, s: T): Unit = unimplemented(s, Instructions.mult) open fun multu(i: Int, s: T): Unit = unimplemented(s, Instructions.multu) open fun madd(i: Int, s: T): Unit = unimplemented(s, Instructions.madd) open fun maddu(i: Int, s: T): Unit = unimplemented(s, Instructions.maddu) open fun msub(i: Int, s: T): Unit = unimplemented(s, Instructions.msub) open fun msubu(i: Int, s: T): Unit = unimplemented(s, Instructions.msubu) open fun mfhi(i: Int, s: T): Unit = unimplemented(s, Instructions.mfhi) open fun mflo(i: Int, s: T): Unit = unimplemented(s, Instructions.mflo) open fun mthi(i: Int, s: T): Unit = unimplemented(s, Instructions.mthi) open fun mtlo(i: Int, s: T): Unit = unimplemented(s, Instructions.mtlo) open fun movz(i: Int, s: T): Unit = unimplemented(s, Instructions.movz) open fun movn(i: Int, s: T): Unit = unimplemented(s, Instructions.movn) open fun ext(i: Int, s: T): Unit = unimplemented(s, Instructions.ext) open fun ins(i: Int, s: T): Unit = unimplemented(s, Instructions.ins) open fun clz(i: Int, s: T): Unit = unimplemented(s, Instructions.clz) open fun clo(i: Int, s: T): Unit = unimplemented(s, Instructions.clo) open fun wsbh(i: Int, s: T): Unit = unimplemented(s, Instructions.wsbh) open fun wsbw(i: Int, s: T): Unit = unimplemented(s, Instructions.wsbw) open fun beq(i: Int, s: T): Unit = unimplemented(s, Instructions.beq) open fun beql(i: Int, s: T): Unit = unimplemented(s, Instructions.beql) open fun bgez(i: Int, s: T): Unit = unimplemented(s, Instructions.bgez) open fun bgezl(i: Int, s: T): Unit = unimplemented(s, Instructions.bgezl) open fun bgezal(i: Int, s: T): Unit = unimplemented(s, Instructions.bgezal) open fun bgezall(i: Int, s: T): Unit = unimplemented(s, Instructions.bgezall) open fun bltz(i: Int, s: T): Unit = unimplemented(s, Instructions.bltz) open fun bltzl(i: Int, s: T): Unit = unimplemented(s, Instructions.bltzl) open fun bltzal(i: Int, s: T): Unit = unimplemented(s, Instructions.bltzal) open fun bltzall(i: Int, s: T): Unit = unimplemented(s, Instructions.bltzall) open fun blez(i: Int, s: T): Unit = unimplemented(s, Instructions.blez) open fun blezl(i: Int, s: T): Unit = unimplemented(s, Instructions.blezl) open fun bgtz(i: Int, s: T): Unit = unimplemented(s, Instructions.bgtz) open fun bgtzl(i: Int, s: T): Unit = unimplemented(s, Instructions.bgtzl) open fun bne(i: Int, s: T): Unit = unimplemented(s, Instructions.bne) open fun bnel(i: Int, s: T): Unit = unimplemented(s, Instructions.bnel) open fun j(i: Int, s: T): Unit = unimplemented(s, Instructions.j) open fun jr(i: Int, s: T): Unit = unimplemented(s, Instructions.jr) open fun jalr(i: Int, s: T): Unit = unimplemented(s, Instructions.jalr) open fun jal(i: Int, s: T): Unit = unimplemented(s, Instructions.jal) open fun bc1f(i: Int, s: T): Unit = unimplemented(s, Instructions.bc1f) open fun bc1t(i: Int, s: T): Unit = unimplemented(s, Instructions.bc1t) open fun bc1fl(i: Int, s: T): Unit = unimplemented(s, Instructions.bc1fl) open fun bc1tl(i: Int, s: T): Unit = unimplemented(s, Instructions.bc1tl) open fun lb(i: Int, s: T): Unit = unimplemented(s, Instructions.lb) open fun lh(i: Int, s: T): Unit = unimplemented(s, Instructions.lh) open fun lw(i: Int, s: T): Unit = unimplemented(s, Instructions.lw) open fun lwl(i: Int, s: T): Unit = unimplemented(s, Instructions.lwl) open fun lwr(i: Int, s: T): Unit = unimplemented(s, Instructions.lwr) open fun lbu(i: Int, s: T): Unit = unimplemented(s, Instructions.lbu) open fun lhu(i: Int, s: T): Unit = unimplemented(s, Instructions.lhu) open fun sb(i: Int, s: T): Unit = unimplemented(s, Instructions.sb) open fun sh(i: Int, s: T): Unit = unimplemented(s, Instructions.sh) open fun sw(i: Int, s: T): Unit = unimplemented(s, Instructions.sw) open fun swl(i: Int, s: T): Unit = unimplemented(s, Instructions.swl) open fun swr(i: Int, s: T): Unit = unimplemented(s, Instructions.swr) open fun ll(i: Int, s: T): Unit = unimplemented(s, Instructions.ll) open fun sc(i: Int, s: T): Unit = unimplemented(s, Instructions.sc) open fun lwc1(i: Int, s: T): Unit = unimplemented(s, Instructions.lwc1) open fun swc1(i: Int, s: T): Unit = unimplemented(s, Instructions.swc1) open fun add_s(i: Int, s: T): Unit = unimplemented(s, Instructions.add_s) open fun sub_s(i: Int, s: T): Unit = unimplemented(s, Instructions.sub_s) open fun mul_s(i: Int, s: T): Unit = unimplemented(s, Instructions.mul_s) open fun div_s(i: Int, s: T): Unit = unimplemented(s, Instructions.div_s) open fun sqrt_s(i: Int, s: T): Unit = unimplemented(s, Instructions.sqrt_s) open fun abs_s(i: Int, s: T): Unit = unimplemented(s, Instructions.abs_s) open fun mov_s(i: Int, s: T): Unit = unimplemented(s, Instructions.mov_s) open fun neg_s(i: Int, s: T): Unit = unimplemented(s, Instructions.neg_s) open fun round_w_s(i: Int, s: T): Unit = unimplemented(s, Instructions.round_w_s) open fun trunc_w_s(i: Int, s: T): Unit = unimplemented(s, Instructions.trunc_w_s) open fun ceil_w_s(i: Int, s: T): Unit = unimplemented(s, Instructions.ceil_w_s) open fun floor_w_s(i: Int, s: T): Unit = unimplemented(s, Instructions.floor_w_s) open fun cvt_s_w(i: Int, s: T): Unit = unimplemented(s, Instructions.cvt_s_w) open fun cvt_w_s(i: Int, s: T): Unit = unimplemented(s, Instructions.cvt_w_s) open fun mfc1(i: Int, s: T): Unit = unimplemented(s, Instructions.mfc1) open fun mtc1(i: Int, s: T): Unit = unimplemented(s, Instructions.mtc1) open fun cfc1(i: Int, s: T): Unit = unimplemented(s, Instructions.cfc1) open fun ctc1(i: Int, s: T): Unit = unimplemented(s, Instructions.ctc1) open fun c_f_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_f_s) open fun c_un_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_un_s) open fun c_eq_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_eq_s) open fun c_ueq_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ueq_s) open fun c_olt_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_olt_s) open fun c_ult_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ult_s) open fun c_ole_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ole_s) open fun c_ule_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ule_s) open fun c_sf_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_sf_s) open fun c_ngle_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ngle_s) open fun c_seq_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_seq_s) open fun c_ngl_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ngl_s) open fun c_lt_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_lt_s) open fun c_nge_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_nge_s) open fun c_le_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_le_s) open fun c_ngt_s(i: Int, s: T): Unit = unimplemented(s, Instructions.c_ngt_s) open fun syscall(i: Int, s: T): Unit = unimplemented(s, Instructions.syscall) open fun cache(i: Int, s: T): Unit = unimplemented(s, Instructions.cache) open fun sync(i: Int, s: T): Unit = unimplemented(s, Instructions.sync) open fun _break(i: Int, s: T): Unit = unimplemented(s, Instructions._break) open fun dbreak(i: Int, s: T): Unit = unimplemented(s, Instructions.dbreak) open fun halt(i: Int, s: T): Unit = unimplemented(s, Instructions.halt) open fun dret(i: Int, s: T): Unit = unimplemented(s, Instructions.dret) open fun eret(i: Int, s: T): Unit = unimplemented(s, Instructions.eret) open fun mfic(i: Int, s: T): Unit = unimplemented(s, Instructions.mfic) open fun mtic(i: Int, s: T): Unit = unimplemented(s, Instructions.mtic) open fun mfdr(i: Int, s: T): Unit = unimplemented(s, Instructions.mfdr) open fun mtdr(i: Int, s: T): Unit = unimplemented(s, Instructions.mtdr) open fun cfc0(i: Int, s: T): Unit = unimplemented(s, Instructions.cfc0) open fun ctc0(i: Int, s: T): Unit = unimplemented(s, Instructions.ctc0) open fun mfc0(i: Int, s: T): Unit = unimplemented(s, Instructions.mfc0) open fun mtc0(i: Int, s: T): Unit = unimplemented(s, Instructions.mtc0) open fun mfv(i: Int, s: T): Unit = unimplemented(s, Instructions.mfv) open fun mfvc(i: Int, s: T): Unit = unimplemented(s, Instructions.mfvc) open fun mtv(i: Int, s: T): Unit = unimplemented(s, Instructions.mtv) open fun mtvc(i: Int, s: T): Unit = unimplemented(s, Instructions.mtvc) open fun lv_s(i: Int, s: T): Unit = unimplemented(s, Instructions.lv_s) open fun lv_q(i: Int, s: T): Unit = unimplemented(s, Instructions.lv_q) open fun lvl_q(i: Int, s: T): Unit = unimplemented(s, Instructions.lvl_q) open fun lvr_q(i: Int, s: T): Unit = unimplemented(s, Instructions.lvr_q) open fun sv_q(i: Int, s: T): Unit = unimplemented(s, Instructions.sv_q) open fun vdot(i: Int, s: T): Unit = unimplemented(s, Instructions.vdot) open fun vscl(i: Int, s: T): Unit = unimplemented(s, Instructions.vscl) open fun vsge(i: Int, s: T): Unit = unimplemented(s, Instructions.vsge) open fun vslt(i: Int, s: T): Unit = unimplemented(s, Instructions.vslt) open fun vrot(i: Int, s: T): Unit = unimplemented(s, Instructions.vrot) open fun vzero(i: Int, s: T): Unit = unimplemented(s, Instructions.vzero) open fun vone(i: Int, s: T): Unit = unimplemented(s, Instructions.vone) open fun vmov(i: Int, s: T): Unit = unimplemented(s, Instructions.vmov) open fun vabs(i: Int, s: T): Unit = unimplemented(s, Instructions.vabs) open fun vneg(i: Int, s: T): Unit = unimplemented(s, Instructions.vneg) open fun vocp(i: Int, s: T): Unit = unimplemented(s, Instructions.vocp) open fun vsgn(i: Int, s: T): Unit = unimplemented(s, Instructions.vsgn) open fun vrcp(i: Int, s: T): Unit = unimplemented(s, Instructions.vrcp) open fun vrsq(i: Int, s: T): Unit = unimplemented(s, Instructions.vrsq) open fun vsin(i: Int, s: T): Unit = unimplemented(s, Instructions.vsin) open fun vcos(i: Int, s: T): Unit = unimplemented(s, Instructions.vcos) open fun vexp2(i: Int, s: T): Unit = unimplemented(s, Instructions.vexp2) open fun vlog2(i: Int, s: T): Unit = unimplemented(s, Instructions.vlog2) open fun vsqrt(i: Int, s: T): Unit = unimplemented(s, Instructions.vsqrt) open fun vasin(i: Int, s: T): Unit = unimplemented(s, Instructions.vasin) open fun vnrcp(i: Int, s: T): Unit = unimplemented(s, Instructions.vnrcp) open fun vnsin(i: Int, s: T): Unit = unimplemented(s, Instructions.vnsin) open fun vrexp2(i: Int, s: T): Unit = unimplemented(s, Instructions.vrexp2) open fun vsat0(i: Int, s: T): Unit = unimplemented(s, Instructions.vsat0) open fun vsat1(i: Int, s: T): Unit = unimplemented(s, Instructions.vsat1) open fun vcst(i: Int, s: T): Unit = unimplemented(s, Instructions.vcst) open fun vmmul(i: Int, s: T): Unit = unimplemented(s, Instructions.vmmul) open fun vhdp(i: Int, s: T): Unit = unimplemented(s, Instructions.vhdp) open fun vcrs_t(i: Int, s: T): Unit = unimplemented(s, Instructions.vcrs_t) open fun vcrsp_t(i: Int, s: T): Unit = unimplemented(s, Instructions.vcrsp_t) open fun vi2c(i: Int, s: T): Unit = unimplemented(s, Instructions.vi2c) open fun vi2uc(i: Int, s: T): Unit = unimplemented(s, Instructions.vi2uc) open fun vtfm2(i: Int, s: T): Unit = unimplemented(s, Instructions.vtfm2) open fun vtfm3(i: Int, s: T): Unit = unimplemented(s, Instructions.vtfm3) open fun vtfm4(i: Int, s: T): Unit = unimplemented(s, Instructions.vtfm4) open fun vhtfm2(i: Int, s: T): Unit = unimplemented(s, Instructions.vhtfm2) open fun vhtfm3(i: Int, s: T): Unit = unimplemented(s, Instructions.vhtfm3) open fun vhtfm4(i: Int, s: T): Unit = unimplemented(s, Instructions.vhtfm4) open fun vsrt3(i: Int, s: T): Unit = unimplemented(s, Instructions.vsrt3) open fun vfad(i: Int, s: T): Unit = unimplemented(s, Instructions.vfad) open fun vmin(i: Int, s: T): Unit = unimplemented(s, Instructions.vmin) open fun vmax(i: Int, s: T): Unit = unimplemented(s, Instructions.vmax) open fun vadd(i: Int, s: T): Unit = unimplemented(s, Instructions.vadd) open fun vsub(i: Int, s: T): Unit = unimplemented(s, Instructions.vsub) open fun vdiv(i: Int, s: T): Unit = unimplemented(s, Instructions.vdiv) open fun vmul(i: Int, s: T): Unit = unimplemented(s, Instructions.vmul) open fun vidt(i: Int, s: T): Unit = unimplemented(s, Instructions.vidt) open fun vmidt(i: Int, s: T): Unit = unimplemented(s, Instructions.vmidt) open fun viim(i: Int, s: T): Unit = unimplemented(s, Instructions.viim) open fun vmmov(i: Int, s: T): Unit = unimplemented(s, Instructions.vmmov) open fun vmzero(i: Int, s: T): Unit = unimplemented(s, Instructions.vmzero) open fun vmone(i: Int, s: T): Unit = unimplemented(s, Instructions.vmone) open fun vnop(i: Int, s: T): Unit = unimplemented(s, Instructions.vnop) open fun vsync(i: Int, s: T): Unit = unimplemented(s, Instructions.vsync) open fun vflush(i: Int, s: T): Unit = unimplemented(s, Instructions.vflush) open fun vpfxd(i: Int, s: T): Unit = unimplemented(s, Instructions.vpfxd) open fun vpfxs(i: Int, s: T): Unit = unimplemented(s, Instructions.vpfxs) open fun vpfxt(i: Int, s: T): Unit = unimplemented(s, Instructions.vpfxt) open fun vdet(i: Int, s: T): Unit = unimplemented(s, Instructions.vdet) open fun vrnds(i: Int, s: T): Unit = unimplemented(s, Instructions.vrnds) open fun vrndi(i: Int, s: T): Unit = unimplemented(s, Instructions.vrndi) open fun vrndf1(i: Int, s: T): Unit = unimplemented(s, Instructions.vrndf1) open fun vrndf2(i: Int, s: T): Unit = unimplemented(s, Instructions.vrndf2) open fun vcmp(i: Int, s: T): Unit = unimplemented(s, Instructions.vcmp) open fun vcmovf(i: Int, s: T): Unit = unimplemented(s, Instructions.vcmovf) open fun vcmovt(i: Int, s: T): Unit = unimplemented(s, Instructions.vcmovt) open fun vavg(i: Int, s: T): Unit = unimplemented(s, Instructions.vavg) open fun vf2id(i: Int, s: T): Unit = unimplemented(s, Instructions.vf2id) open fun vf2in(i: Int, s: T): Unit = unimplemented(s, Instructions.vf2in) open fun vf2iu(i: Int, s: T): Unit = unimplemented(s, Instructions.vf2iu) open fun vf2iz(i: Int, s: T): Unit = unimplemented(s, Instructions.vf2iz) open fun vi2f(i: Int, s: T): Unit = unimplemented(s, Instructions.vi2f) open fun vscmp(i: Int, s: T): Unit = unimplemented(s, Instructions.vscmp) open fun vmscl(i: Int, s: T): Unit = unimplemented(s, Instructions.vmscl) open fun vt4444_q(i: Int, s: T): Unit = unimplemented(s, Instructions.vt4444_q) open fun vt5551_q(i: Int, s: T): Unit = unimplemented(s, Instructions.vt5551_q) open fun vt5650_q(i: Int, s: T): Unit = unimplemented(s, Instructions.vt5650_q) open fun vmfvc(i: Int, s: T): Unit = unimplemented(s, Instructions.vmfvc) open fun vmtvc(i: Int, s: T): Unit = unimplemented(s, Instructions.vmtvc) open fun mfvme(i: Int, s: T): Unit = unimplemented(s, Instructions.mfvme) open fun mtvme(i: Int, s: T): Unit = unimplemented(s, Instructions.mtvme) open fun sv_s(i: Int, s: T): Unit = unimplemented(s, Instructions.sv_s) open fun vfim(i: Int, s: T): Unit = unimplemented(s, Instructions.vfim) open fun svl_q(i: Int, s: T): Unit = unimplemented(s, Instructions.svl_q) open fun svr_q(i: Int, s: T): Unit = unimplemented(s, Instructions.svr_q) open fun vbfy1(i: Int, s: T): Unit = unimplemented(s, Instructions.vbfy1) open fun vbfy2(i: Int, s: T): Unit = unimplemented(s, Instructions.vbfy2) open fun vf2h(i: Int, s: T): Unit = unimplemented(s, Instructions.vf2h) open fun vh2f(i: Int, s: T): Unit = unimplemented(s, Instructions.vh2f) open fun vi2s(i: Int, s: T): Unit = unimplemented(s, Instructions.vi2s) open fun vi2us(i: Int, s: T): Unit = unimplemented(s, Instructions.vi2us) open fun vlgb(i: Int, s: T): Unit = unimplemented(s, Instructions.vlgb) open fun vqmul(i: Int, s: T): Unit = unimplemented(s, Instructions.vqmul) open fun vs2i(i: Int, s: T): Unit = unimplemented(s, Instructions.vs2i) open fun vc2i(i: Int, s: T): Unit = unimplemented(s, Instructions.vc2i) open fun vuc2i(i: Int, s: T): Unit = unimplemented(s, Instructions.vuc2i) open fun vsbn(i: Int, s: T): Unit = unimplemented(s, Instructions.vsbn) open fun vsbz(i: Int, s: T): Unit = unimplemented(s, Instructions.vsbz) open fun vsocp(i: Int, s: T): Unit = unimplemented(s, Instructions.vsocp) open fun vsrt1(i: Int, s: T): Unit = unimplemented(s, Instructions.vsrt1) open fun vsrt2(i: Int, s: T): Unit = unimplemented(s, Instructions.vsrt2) open fun vsrt4(i: Int, s: T): Unit = unimplemented(s, Instructions.vsrt4) open fun vus2i(i: Int, s: T): Unit = unimplemented(s, Instructions.vus2i) open fun vwbn(i: Int, s: T): Unit = unimplemented(s, Instructions.vwbn) open fun bvf(i: Int, s: T): Unit = unimplemented(s, Instructions.bvf) open fun bvt(i: Int, s: T): Unit = unimplemented(s, Instructions.bvt) open fun bvfl(i: Int, s: T): Unit = unimplemented(s, Instructions.bvfl) open fun bvtl(i: Int, s: T): Unit = unimplemented(s, Instructions.bvtl) }
mit
51b4b3bf562e9211de381ead12eeca2c
75.05303
100
0.66934
2.922137
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/presentation/view/component/adapter/ReadableMoreRecyclerAdapter.kt
1
4787
package net.ketc.numeri.presentation.view.component.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.ViewGroup import net.ketc.numeri.domain.model.cache.Cacheable import net.ketc.numeri.presentation.view.component.FooterViewHolder import net.ketc.numeri.presentation.view.component.ReadableMore import net.ketc.numeri.presentation.view.component.ui.UI import net.ketc.numeri.presentation.view.component.ui.footer.EmptyViewUI import net.ketc.numeri.presentation.view.component.ui.footer.FooterViewUI import net.ketc.numeri.util.indexesIf import net.ketc.numeri.util.rx.AutoDisposable import kotlin.collections.ArrayList class ReadableMoreRecyclerAdapter<T>(private val autoDisposable: AutoDisposable, private val create: () -> ReadableMoreViewHolder<T>, private val readableMore: ReadableMore<MutableList<T>>? = null) : RecyclerView.Adapter<ReadableMoreViewHolder<T>>() { private val itemList = ArrayList<T>() val last: T? get() = itemList.lastOrNull() val first: T? get() = itemList.firstOrNull() private var viewAddition = 0 private val enabledAdditions = BooleanArray(2) { false } private var enabledTypeList: ArrayList<Int> = ArrayList() var isReadMoreEnabled: Boolean get() = enabledAdditions[TYPE_READ_MORE.second] set(value) { setAdditionEnabled(TYPE_READ_MORE, value) } var isEmptyFooterEnabled: Boolean get() = enabledAdditions[TYPE_EMPTY.second] set(value) { setAdditionEnabled(TYPE_EMPTY, value) } private fun setAdditionEnabled(pair: Pair<Int, Int>, enabled: Boolean) { val key = pair.second val upperEnabledCount = enabledAdditions.filterIndexed { i, _ -> key < i }.count { it } val changingPosition = viewAddition - upperEnabledCount + itemList.size val previous = enabledAdditions[key] enabledAdditions[key] = enabled val index = changingPosition - itemList.size if (previous != enabled) { if (enabled) { notifyItemInserted(changingPosition) enabledTypeList.add(index, pair.first) viewAddition++ } else { notifyItemRemoved(changingPosition) enabledTypeList.removeAt(index) viewAddition-- } } } override fun getItemViewType(position: Int): Int { return if (itemList.lastIndex >= position) { RecyclerView.INVALID_TYPE } else { enabledTypeList[position - itemList.size] } } override fun onBindViewHolder(holder: ReadableMoreViewHolder<T>, position: Int) { if (itemList.lastIndex >= position) holder.bind(itemList[position]) } override fun getItemCount() = itemList.size + viewAddition override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReadableMoreViewHolder<T> { return when (viewType) { TYPE_READ_MORE.first -> FooterViewHolder(FooterViewUI(parent.context), readableMore ?: throw IllegalStateException("readableMore is not initialized"), autoDisposable) TYPE_EMPTY.first -> EmptyViewHolder(parent.context) else -> create() } } fun insertTop(t: T) { itemList.add(0, t) notifyItemInserted(0) } fun insertAllToTop(list: List<T>) { itemList.addAll(0, list) notifyItemRangeInserted(0, list.size) } fun addAll(list: List<T>) { itemList.addAll(list) notifyItemRangeInserted(itemList.lastIndex, list.size) } fun remove(t: T) { val index = itemList.indexOf(t) if (index != -1) { itemList.remove(t) notifyItemRemoved(index) } } fun removeIf(predicate: (T) -> Boolean) { itemList.indexesIf(predicate).forEach { itemList.removeAt(it) notifyItemRemoved(it) } } companion object { val TYPE_READ_MORE = 300 to 0 val TYPE_EMPTY = 400 to 1 } class EmptyViewHolder<in RMT>(ctx: Context) : ReadableMoreViewHolder<RMT>(EmptyViewUI(ctx), {}) { override val autoDisposable: AutoDisposable get() = throw IllegalStateException() override fun bind(value: RMT) { } } } fun <T : Cacheable<Long>> ReadableMoreRecyclerAdapter<T>.remove(id: Long) = removeIf { it.id == id } abstract class ReadableMoreViewHolder<in T>(ui: UI, protected val onClick: (T) -> Unit) : RecyclerView.ViewHolder(ui.createView()) { abstract protected val autoDisposable: AutoDisposable abstract fun bind(value: T) }
mit
b4057af410004ae4c71261e819a0e20c
33.695652
162
0.646543
4.469655
false
false
false
false
Assassinss/Jandan-Kotlin
app/src/main/java/me/zsj/dan/ui/fragment/JokeFragment.kt
1
3310
package me.zsj.dan.ui.fragment import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import me.zsj.dan.R import me.zsj.dan.data.Callback import me.zsj.dan.data.ICall import me.zsj.dan.data.api.DataApi import me.zsj.dan.model.Comment import me.zsj.dan.model.Joke import me.zsj.dan.ui.adapter.JokeAdapter import me.zsj.dan.ui.adapter.common.OnLoadDataListener import me.zsj.dan.utils.getColor import me.zsj.dan.utils.recyclerview.RecyclerViewExtensions import retrofit2.Call /** * @author zsj */ class JokeFragment : LazyLoadFragment(), ICall<Joke>, Callback, RecyclerViewExtensions, OnLoadDataListener { private var refreshLayout: SwipeRefreshLayout? = null private var recyclerView: RecyclerView? = null private lateinit var adapter: JokeAdapter private var jokeList: ArrayList<Comment> = ArrayList() private var page: Int = 1 private var clear: Boolean = false override fun initViews(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater!!.inflate(R.layout.fragment_joke, container, false) refreshLayout = view.findViewById(R.id.swipe_refresh_layout) recyclerView = view.findViewById(R.id.joke_list) return view } override fun createCall(arg: Any?): Call<Joke> { return dataManager.createApi(DataApi::class.java)!!.loadJokes(arg as Int) } override fun initData() { refreshLayout?.setColorSchemeColors(getColor(R.color.colorAccent)) setupRecyclerView() dataManager.setCallback(this) refreshLayout?.setOnRefreshListener { page = 1 clear = true dataManager.loadData(createCall(page)) } refreshLayout?.isRefreshing = true recyclerView?.postDelayed({ dataManager.loadData(createCall(page)) }, 350) } private fun setupRecyclerView() { adapter = JokeAdapter(activity!!, jokeList, dataManager) adapter.setOnLoadDataListener(this) recyclerView?.itemAnimator?.changeDuration = 0 recyclerView?.adapter = adapter recyclerView?.onLoadMore { onLoadMoreData() } } override fun onLoadMoreData() { if (!dataManager.isLoading() && !isLoadMore) { page += 1 clear = false isLoadMore = true recyclerView?.postDelayed({ dataManager.loadData(createCall(page)) }, 1000) } } private var isLoadMore = false override fun onSuccess(data: Any?) { val joke = data as Joke refreshLayout?.isRefreshing = false if (clear) { jokeList.clear() } adapter.onLoadingError(false) isLoadMore = false jokeList.addAll(joke.comments) dataManager.setComments(jokeList) adapter.notifyItemRangeChanged(jokeList.size - joke.comments.size - 1, jokeList.size) } override fun onFailure(t: Throwable?) { isLoadMore = false refreshLayout?.isRefreshing = false if (page > 1) page -= 1 adapter.onLoadingError(true) } }
gpl-3.0
c72ab941dd77d2a00bcaae865a491c76
28.828829
113
0.667674
4.378307
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Show.kt
1
4298
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.TwitterList /** * Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-show) * * @param listId The numerical id of the list. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.show( listId: Long, vararg options: Option ) = show(listId, null, null, null, *options) /** * Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerScreenName The screen name of the user who owns the list being requested by a slug. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.showByOwnerScreenName( slug: String, ownerScreenName: String, vararg options: Option ) = show(null, slug, ownerScreenName, null, *options) /** * Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerId The user ID of the user who owns the list being requested by a slug. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.showByOwnerId( slug: String, ownerId: Long, vararg options: Option ) = show(null, slug, null, ownerId, *options) private fun Lists.show( listId: Long? = null, slug: String? = null, ownerScreenName: String? = null, ownerId: Long? = null, vararg options: Option ) = client.session.get("/1.1/lists/show.json") { parameters( "list_id" to listId, "slug" to slug, "owner_screen_name" to ownerScreenName, "owner_id" to ownerId, *options ) }.jsonObject<TwitterList>()
mit
71d3c0c67ee4332fad4cfc442af81130
42.414141
208
0.742438
4.016822
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/extensions/models/builder/CustomStatusEventBuilder.kt
1
2943
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED") package jp.nephy.penicillin.extensions.models.builder import jp.nephy.jsonkt.* import jp.nephy.penicillin.core.experimental.PenicillinExperimentalApi import jp.nephy.penicillin.core.streaming.handler.UserStreamEvent import jp.nephy.penicillin.extensions.parseModel import jp.nephy.penicillin.models.Stream import java.time.temporal.TemporalAccessor import kotlin.collections.set /** * Custom payload builder for [Stream.StatusEvent]. */ class CustomStatusEventBuilder(type: UserStreamEvent): JsonBuilder<Stream.StatusEvent>, JsonMap by jsonMapOf( "event" to type.key, "source" to null, "target" to null, "target_object" to null, "created_at" to null ) { private var source = CustomUserBuilder() /** * Sets source. */ fun source(builder: CustomUserBuilder.() -> Unit) { source.apply(builder) } private var target = CustomUserBuilder() /** * Sets target. */ fun target(builder: CustomUserBuilder.() -> Unit) { target.apply(builder) } private var targetObject = CustomStatusBuilder() /** * Sets target_object. */ fun targetObject(builder: CustomStatusBuilder.() -> Unit) { targetObject.apply(builder) } /** * "created_at". */ var createdAt: TemporalAccessor? = null @UseExperimental(PenicillinExperimentalApi::class) override fun build(): Stream.StatusEvent { val source = source.build() val target = target.build() val targetObject = targetObject.build() this["source"] = source this["target"] = target this["target_object"] = targetObject this["created_at"] = createdAt.toCreatedAt() return toJsonObject().parseModel() } }
mit
c4a7e4798887c0357d252faf8e6b2940
32.067416
109
0.700985
4.29635
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-rolling-bukkit/src/main/kotlin/com/rpkit/rolling/bukkit/turnorder/RPKTurnOrderService.kt
1
1924
/* * Copyright 2022 Ren Binden * * 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.rpkit.rolling.bukkit.turnorder import com.rpkit.core.service.Service import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.rolling.bukkit.RPKRollingBukkit import org.bukkit.scoreboard.Scoreboard class RPKTurnOrderService(override val plugin: RPKRollingBukkit) : Service { private val turnOrders = mutableMapOf<String, RPKTurnOrder>() private var emptyScoreboard: Scoreboard? = plugin.server.scoreboardManager?.newScoreboard fun addTurnOrder(turnOrder: RPKTurnOrder) { turnOrders[turnOrder.name] = turnOrder } fun removeTurnOrder(turnOrder: RPKTurnOrder) { turnOrders.remove(turnOrder.name) } fun getTurnOrder(name: String): RPKTurnOrder? { return turnOrders[name] } fun getActiveTurnOrder(minecraftProfile: RPKMinecraftProfile): RPKTurnOrder? { return turnOrders.values.singleOrNull { it.isActiveFor(minecraftProfile) } } fun hideTurnOrder(minecraftProfile: RPKMinecraftProfile) { val bukkitPlayer = plugin.server.getPlayer(minecraftProfile.minecraftUUID) ?: return if (emptyScoreboard == null) emptyScoreboard = plugin.server.scoreboardManager?.newScoreboard val finalEmptyScoreboard = emptyScoreboard ?: return bukkitPlayer.scoreboard = finalEmptyScoreboard } }
apache-2.0
8c540c605d74bd65df276b94ff0021ea
36.019231
101
0.752599
4.570071
false
false
false
false
UniversityOfBrightonComputing/iCurves
src/main/kotlin/icurves/diagram/curve/PathCurve.kt
1
3401
package icurves.diagram.curve import icurves.description.AbstractCurve import icurves.diagram.Curve import javafx.scene.paint.Color import javafx.scene.shape.* import math.geom2d.Point2D import math.geom2d.polygon.Polygon2D import math.geom2d.polygon.SimplePolygon2D /** * * * @author Almas Baimagambetov ([email protected]) */ class PathCurve(abstractCurve: AbstractCurve, val path: Path) : Curve(abstractCurve) { init { path.elements.addAll(ClosePath()) path.fill = Color.TRANSPARENT } override fun computeShape(): Shape { val bbox = Rectangle(10000.0, 10000.0) bbox.translateX = -3000.0 bbox.translateY = -3000.0 val shape = Shape.intersect(bbox, path) shape.fill = Color.TRANSPARENT shape.stroke = Color.DARKBLUE shape.strokeWidth = 2.0 return shape } override fun computePolygon(): Polygon2D { val moveTo = path.elements[0] as MoveTo val polygonPoints = arrayListOf<Point2D>() val p0 = Point2D(moveTo.x, moveTo.y) polygonPoints.add(p0) // drop moveTo and close() path.elements.drop(1).dropLast(1).forEach { when (it) { is QuadCurveTo -> { val smoothFactor = 10 val p1 = polygonPoints.last() val p2 = Point2D(it.controlX, it.controlY) val p3 = Point2D(it.x, it.y) var t = 0.01 while (t < 1.01) { polygonPoints.add(getQuadValue(p1, p2, p3, t)) t += 1.0 / smoothFactor } polygonPoints.add(p3) } is CubicCurveTo -> { val smoothFactor = 10 val p1 = polygonPoints.last() val p2 = Point2D(it.controlX1, it.controlY1) val p3 = Point2D(it.controlX2, it.controlY2) val p4 = Point2D(it.x, it.y) var t = 0.01 while (t < 1.01) { polygonPoints.add(getCubicValue(p1, p2, p3, p4, t)) t += 1.0 / smoothFactor } polygonPoints.add(p4) } is LineTo -> { polygonPoints.add(Point2D(it.x, it.y)) } is ClosePath -> { // ignore } else -> { throw IllegalArgumentException("Unknown path element: $it") } } } return SimplePolygon2D(polygonPoints) } private fun getQuadValue(p1: Point2D, p2: Point2D, p3: Point2D, t: Double): Point2D { val x = (1 - t) * (1 - t) * p1.x() + 2 * (1 - t) * t * p2.x() + t * t * p3.x() val y = (1 - t) * (1 - t) * p1.y() + 2 * (1 - t) * t * p2.y() + t * t * p3.y() return Point2D(x, y) } private fun getCubicValue(p1: Point2D, p2: Point2D, p3: Point2D, p4: Point2D, t: Double): Point2D { val x = Math.pow(1 - t, 3.0) * p1.x + 3 * t * Math.pow(1 - t, 2.0) * p2.x + 3 * t*t * (1 - t) * p3.x + t*t*t*p4.x val y = Math.pow(1 - t, 3.0) * p1.y + 3 * t * Math.pow(1 - t, 2.0) * p2.y + 3 * t*t * (1 - t) * p3.y + t*t*t*p4.y return Point2D(x, y) } }
mit
8e450900d67fc40eb3e281133b23b817
29.927273
121
0.486916
3.456301
false
false
false
false
robedmo/vlc-android
vlc-android/src/org/videolan/vlc/gui/audio/AudioPlayer.kt
1
26935
/***************************************************************************** * AudioPlayer.java * * Copyright © 2011-2014 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.audio import android.Manifest import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.preference.PreferenceManager import android.support.annotation.MainThread import android.support.annotation.RequiresPermission import android.support.design.widget.BottomSheetBehavior import android.support.design.widget.Snackbar import android.support.v4.app.FragmentActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.PopupMenu import android.support.v7.widget.helper.ItemTouchHelper import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import kotlinx.coroutines.experimental.CoroutineStart import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.channels.Channel import kotlinx.coroutines.experimental.channels.actor import kotlinx.coroutines.experimental.launch import org.videolan.libvlc.Media import org.videolan.libvlc.MediaPlayer import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.Tools import org.videolan.medialibrary.media.MediaWrapper import org.videolan.vlc.PlaybackService import org.videolan.vlc.R import org.videolan.vlc.VLCApplication import org.videolan.vlc.databinding.AudioPlayerBinding import org.videolan.vlc.gui.AudioPlayerContainerActivity import org.videolan.vlc.gui.PlaybackServiceFragment import org.videolan.vlc.gui.dialogs.AdvOptionsDialog import org.videolan.vlc.gui.helpers.AudioUtil import org.videolan.vlc.gui.helpers.SwipeDragItemTouchHelperCallback import org.videolan.vlc.gui.helpers.UiTools import org.videolan.vlc.gui.preferences.PreferencesActivity import org.videolan.vlc.gui.video.VideoPlayerActivity import org.videolan.vlc.gui.view.AudioMediaSwitcher.AudioMediaSwitcherListener import org.videolan.vlc.util.AndroidDevices import org.videolan.vlc.util.Constants @Suppress("UNUSED_PARAMETER") class AudioPlayer : PlaybackServiceFragment(), PlaybackService.Callback, PlaylistAdapter.IPlayer, TextWatcher { private lateinit var mBinding: AudioPlayerBinding private lateinit var mPlaylistAdapter: PlaylistAdapter private lateinit var mSettings: SharedPreferences private val mHandler by lazy(LazyThreadSafetyMode.NONE) { Handler() } private val updateActor = actor<Unit>(UI, capacity = Channel.CONFLATED) { for (entry in channel) doUpdate() } private var mShowRemainingTime = false private var mPreviewingSeek = false private var mAdvFuncVisible = false private var mPlaylistSwitchVisible = false private var mSearchVisible = false private var mHeaderPlayPauseVisible = false private var mProgressBarVisible = false private var mHeaderTimeVisible = false private var mPlayerState = 0 private var mCurrentCoverArt: String? = null companion object { const val TAG = "VLC/AudioPlayer" private var DEFAULT_BACKGROUND_DARKER_ID = 0 private var DEFAULT_BACKGROUND_ID = 0 const private val SEARCH_TIMEOUT_MILLIS = 5000 /** * Show the audio player from an intent * * @param context The context of the activity */ fun start(context: Context) { context.applicationContext.sendBroadcast(Intent(Constants.ACTION_SHOW_PLAYER)) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { mPlayerState = it.getInt("player_state")} mPlaylistAdapter = PlaylistAdapter(this) mSettings = PreferenceManager.getDefaultSharedPreferences(activity) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mBinding = AudioPlayerBinding.inflate(inflater) return mBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (AndroidUtil.isJellyBeanMR1OrLater) { DEFAULT_BACKGROUND_DARKER_ID = UiTools.getResourceFromAttribute(view.context, R.attr.background_default_darker) DEFAULT_BACKGROUND_ID = UiTools.getResourceFromAttribute(view.context, R.attr.background_default) } mBinding.songsList.layoutManager = LinearLayoutManager(view.context) mBinding.songsList.adapter = mPlaylistAdapter mBinding.audioMediaSwitcher.setAudioMediaSwitcherListener(mHeaderMediaSwitcherListener) mBinding.coverMediaSwitcher.setAudioMediaSwitcherListener(mCoverMediaSwitcherListener) mBinding.playlistSearchText.editText?.addTextChangedListener(this) val callback = SwipeDragItemTouchHelperCallback(mPlaylistAdapter) val touchHelper = ItemTouchHelper(callback) touchHelper.attachToRecyclerView(mBinding.songsList) setHeaderVisibilities(false, false, true, true, true, false) mBinding.fragment = this mBinding.next.setOnTouchListener(LongSeekListener(true, UiTools.getResourceFromAttribute(view.context, R.attr.ic_next), R.drawable.ic_next_pressed)) mBinding.previous.setOnTouchListener(LongSeekListener(false, UiTools.getResourceFromAttribute(view.context, R.attr.ic_previous), R.drawable.ic_previous_pressed)) registerForContextMenu(mBinding.songsList) userVisibleHint = true mBinding.showCover = mSettings.getBoolean("audio_player_show_cover", false) mBinding.playlistSwitch.setImageResource(UiTools.getResourceFromAttribute(view.context, if (mBinding.showCover) R.attr.ic_playlist else R.attr.ic_playlist_on)) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("player_state", mPlayerState) } override fun onPopupMenu(anchor: View, position: Int) { val activity = activity if (activity === null || position >= mPlaylistAdapter.itemCount) return val mw = mPlaylistAdapter.getItem(position) val popupMenu = PopupMenu(activity, anchor) popupMenu.menuInflater.inflate(R.menu.audio_player, popupMenu.menu) popupMenu.menu.setGroupVisible(R.id.phone_only, mw!!.type != MediaWrapper.TYPE_VIDEO && TextUtils.equals(mw.uri.scheme, "file") && AndroidDevices.isPhone) popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item -> if (item.itemId == R.id.audio_player_mini_remove) { if (mService != null) { mService.remove(position) return@OnMenuItemClickListener true } } else if (item.itemId == R.id.audio_player_set_song) { AudioUtil.setRingtone(mw, activity as FragmentActivity) return@OnMenuItemClickListener true } false }) popupMenu.show() } override fun update() { if (!updateActor.isClosedForSend) updateActor.offer(Unit) } private fun doUpdate() { if (mService === null || activity === null) return if (mService.hasMedia() && !mService.isVideoPlaying) { //Check fragment resumed to not restore video on device turning off if (isVisible && mSettings.getBoolean(PreferencesActivity.VIDEO_RESTORE, false)) { mSettings.edit().putBoolean(PreferencesActivity.VIDEO_RESTORE, false).apply() mService.currentMediaWrapper.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) mService.switchToVideo() return } else show() } else { hide() return } mBinding.audioMediaSwitcher.updateMedia(mService) mBinding.coverMediaSwitcher.updateMedia(mService) mBinding.playlistPlayasaudioOff.visibility = if (mService.videoTracksCount > 0) View.VISIBLE else View.GONE val playing = mService.isPlaying val imageResId = UiTools.getResourceFromAttribute(activity, if (playing) R.attr.ic_pause else R.attr.ic_play) val text = getString(if (playing) R.string.pause else R.string.play) mBinding.playPause.setImageResource(imageResId) mBinding.playPause.contentDescription = text mBinding.headerPlayPause.setImageResource(imageResId) mBinding.headerPlayPause.contentDescription = text mBinding.shuffle.setImageResource(UiTools.getResourceFromAttribute(activity, if (mService.isShuffling) R.attr.ic_shuffle_on else R.attr.ic_shuffle)) mBinding.shuffle.contentDescription = resources.getString(if (mService.isShuffling) R.string.shuffle_on else R.string.shuffle) when (mService.repeatType) { Constants.REPEAT_ONE -> { mBinding.repeat.setImageResource(UiTools.getResourceFromAttribute(activity, R.attr.ic_repeat_one)) mBinding.repeat.contentDescription = resources.getString(R.string.repeat_single) } Constants.REPEAT_ALL -> { mBinding.repeat.setImageResource(UiTools.getResourceFromAttribute(activity, R.attr.ic_repeat_all)) mBinding.repeat.contentDescription = resources.getString(R.string.repeat_all) } else -> { mBinding.repeat.setImageResource(UiTools.getResourceFromAttribute(activity, R.attr.ic_repeat)) mBinding.repeat.contentDescription = resources.getString(R.string.repeat) } } mBinding.shuffle.visibility = if (mService.canShuffle()) View.VISIBLE else View.INVISIBLE mBinding.timeline.setOnSeekBarChangeListener(mTimelineListner) updateList() updateBackground() } override fun updateProgress() { if (mService === null) return val time = mService.time val length = mService.length mBinding.headerTime.text = Tools.millisToString(time) mBinding.length.text = Tools.millisToString(length) mBinding.timeline.max = length.toInt() mBinding.progressBar.max = length.toInt() if (!mPreviewingSeek) { mBinding.time.text = Tools.millisToString((if (mShowRemainingTime) time - length else time)) mBinding.timeline.progress = time.toInt() mBinding.progressBar.progress = time.toInt() } } override fun onMediaEvent(event: Media.Event) {} override fun onMediaPlayerEvent(event: MediaPlayer.Event) { when (event.type) { MediaPlayer.Event.Opening -> hideSearchField() MediaPlayer.Event.Stopped -> hide() } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private fun updateBackground() { if (AndroidUtil.isJellyBeanMR1OrLater) { launch(UI, CoroutineStart.UNDISPATCHED) { val mw = mService.currentMediaWrapper if (mw === null || TextUtils.equals(mCurrentCoverArt, mw.artworkMrl)) return@launch mCurrentCoverArt = mw.artworkMrl if (TextUtils.isEmpty(mw.artworkMrl)) { setDefaultBackground() } else { val blurredCover = async { UiTools.blurBitmap(AudioUtil.readCoverBitmap(Uri.decode(mw.artworkMrl), mBinding.contentLayout.width)) }.await() if (blurredCover !== null) { val activity = activity as? AudioPlayerContainerActivity if (activity === null) return@launch mBinding.backgroundView.setColorFilter(UiTools.getColorFromAttribute(activity, R.attr.audio_player_background_tint)) mBinding.backgroundView.setImageBitmap(blurredCover) mBinding.backgroundView.visibility = View.VISIBLE mBinding.songsList.setBackgroundResource(0) if (mPlayerState == BottomSheetBehavior.STATE_EXPANDED) mBinding.header.setBackgroundResource(0) } else setDefaultBackground() } } } if ((activity as AudioPlayerContainerActivity).isAudioPlayerExpanded) setHeaderVisibilities(true, true, false, false, false, true) } @MainThread private fun setDefaultBackground() { mBinding.songsList.setBackgroundResource(DEFAULT_BACKGROUND_ID) mBinding.header.setBackgroundResource(DEFAULT_BACKGROUND_ID) mBinding.backgroundView.visibility = View.INVISIBLE } override fun updateList() { hideSearchField() if (mService !== null) mPlaylistAdapter.update(mService.medias) } override fun onSelectionSet(position: Int) { if (mPlayerState != BottomSheetBehavior.STATE_COLLAPSED && mPlayerState != BottomSheetBehavior.STATE_HIDDEN) { mBinding.songsList.scrollToPosition(position) } } fun onTimeLabelClick(view: View) { mShowRemainingTime = !mShowRemainingTime update() } fun onPlayPauseClick(view: View) { mService?.run { if (isPlaying) pause() else play() } } fun onStopClick(view: View): Boolean { if (mService === null) return false mService.stop() return true } fun onNextClick(view: View) { if (mService === null) return if (mService.hasNext()) mService.next() else Snackbar.make(mBinding.root, R.string.lastsong, Snackbar.LENGTH_SHORT).show() } fun onPreviousClick(view: View) { if (mService === null) return if (mService.hasPrevious() || mService.isSeekable) mService.previous(false) else Snackbar.make(mBinding.root, R.string.firstsong, Snackbar.LENGTH_SHORT).show() } fun onRepeatClick(view: View) { if (mService === null) return when (mService.repeatType) { Constants.REPEAT_NONE -> mService.repeatType = Constants.REPEAT_ALL Constants.REPEAT_ALL -> mService.repeatType = Constants.REPEAT_ONE else -> mService.repeatType = Constants.REPEAT_NONE } update() } fun onPlaylistSwitchClick(view: View) { mBinding.showCover = !mBinding.showCover mSettings.edit().putBoolean("audio_player_show_cover", mBinding.showCover).apply() mBinding.playlistSwitch.setImageResource(UiTools.getResourceFromAttribute(view.context, if (mBinding.showCover) R.attr.ic_playlist else R.attr.ic_playlist_on)) } fun onShuffleClick(view: View) { if (mService === null) return mService.shuffle() update() } fun onResumeToVideoClick(v: View) { if (mService == null) return if (mService.hasRenderer()) VideoPlayerActivity.startOpened(VLCApplication.getAppContext(), mService.currentMediaWrapper.uri, mService.currentMediaPosition) else if (mService.hasMedia()) { mService.currentMediaWrapper.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) mService.switchToVideo() } } fun showAdvancedOptions(v: View) { if (!isVisible) return val advOptionsDialog = AdvOptionsDialog() advOptionsDialog.arguments = Bundle().apply { putInt(AdvOptionsDialog.MODE_KEY, AdvOptionsDialog.MODE_AUDIO) } advOptionsDialog.show(activity.supportFragmentManager, "fragment_adv_options") } fun show() { val activity = activity as? AudioPlayerContainerActivity if (activity?.isAudioPlayerReady == true) activity.showAudioPlayer() } fun hide() { val activity = activity as? AudioPlayerContainerActivity activity?.hideAudioPlayer() } private fun setHeaderVisibilities(advFuncVisible: Boolean, playlistSwitchVisible: Boolean, headerPlayPauseVisible: Boolean, progressBarVisible: Boolean, headerTimeVisible: Boolean, searchVisible: Boolean) { mAdvFuncVisible = advFuncVisible mPlaylistSwitchVisible = playlistSwitchVisible mHeaderPlayPauseVisible = headerPlayPauseVisible mProgressBarVisible = progressBarVisible mHeaderTimeVisible = headerTimeVisible mSearchVisible = searchVisible restoreHeaderButtonVisibilities() } private fun restoreHeaderButtonVisibilities() { mBinding.advFunction.visibility = if (mAdvFuncVisible) View.VISIBLE else View.GONE mBinding.playlistSwitch.visibility = if (mPlaylistSwitchVisible) View.VISIBLE else View.GONE mBinding.playlistSearch.visibility = if (mSearchVisible) View.VISIBLE else View.GONE mBinding.headerPlayPause.visibility = if (mHeaderPlayPauseVisible) View.VISIBLE else View.GONE mBinding.progressBar.visibility = if (mProgressBarVisible) View.VISIBLE else View.GONE mBinding.headerTime.visibility = if (mHeaderTimeVisible) View.VISIBLE else View.GONE } private fun hideHeaderButtons() { mBinding.advFunction.visibility = View.GONE mBinding.playlistSwitch.visibility = View.GONE mBinding.playlistSearch.visibility = View.GONE mBinding.headerPlayPause.visibility = View.GONE mBinding.progressBar.visibility = View.GONE mBinding.headerTime.visibility = View.GONE } fun onSearchClick(v: View) { mBinding.playlistSearch.visibility = View.GONE mBinding.playlistSearchText.visibility = View.VISIBLE if (mBinding.playlistSearchText.editText != null) mBinding.playlistSearchText.editText!!.requestFocus() val imm = VLCApplication.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(mBinding.playlistSearchText.editText, InputMethodManager.SHOW_IMPLICIT) mHandler.postDelayed(hideSearchRunnable, SEARCH_TIMEOUT_MILLIS.toLong()) } override fun beforeTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {} fun clearSearch(): Boolean { mPlaylistAdapter.restoreList() return hideSearchField() } private fun hideSearchField(): Boolean { if (mBinding.playlistSearchText.visibility != View.VISIBLE) return false mBinding.playlistSearchText.editText?.apply { removeTextChangedListener(this@AudioPlayer) setText("") addTextChangedListener(this@AudioPlayer) } UiTools.setKeyboardVisibility(mBinding.playlistSearchText, false) mBinding.playlistSearch.visibility = View.VISIBLE mBinding.playlistSearchText.visibility = View.GONE return true } override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) { val length = charSequence.length if (length > 1) { mPlaylistAdapter.filter.filter(charSequence) mHandler.removeCallbacks(hideSearchRunnable) } else if (length == 0) { mPlaylistAdapter.restoreList() hideSearchField() } } override fun afterTextChanged(editable: Editable) {} override fun onConnected(service: PlaybackService) { super.onConnected(service) mService.addCallback(this) mPlaylistAdapter.setService(service) update() } override fun onStop() { /* unregister before super.onStop() since mService is set to null from this call */ mService?.removeCallback(this) super.onStop() } private inner class LongSeekListener(internal var forward: Boolean, internal var normal: Int, internal var pressed: Int) : View.OnTouchListener { internal var length = -1L internal var possibleSeek = 0 internal var vibrated = false @RequiresPermission(Manifest.permission.VIBRATE) internal var seekRunnable: Runnable = object : Runnable { override fun run() { if (!vibrated) { (VLCApplication.getAppContext().getSystemService(Context.VIBRATOR_SERVICE) as android.os.Vibrator) .vibrate(80) vibrated = true } if (forward) { if (length <= 0 || possibleSeek < length) possibleSeek += 4000 } else { if (possibleSeek > 4000) possibleSeek -= 4000 else if (possibleSeek <= 4000) possibleSeek = 0 } mBinding.time.text = Tools.millisToString(if (mShowRemainingTime) possibleSeek - length else possibleSeek.toLong()) mBinding.timeline.progress = possibleSeek mBinding.progressBar.progress = possibleSeek mHandler.postDelayed(this, 50) } } override fun onTouch(v: View, event: MotionEvent): Boolean { if (mService === null) return false when (event.action) { MotionEvent.ACTION_DOWN -> { (if (forward) mBinding.next else mBinding.previous).setImageResource(this.pressed) possibleSeek = mService.time.toInt() mPreviewingSeek = true vibrated = false length = mService.length mHandler.postDelayed(seekRunnable, 1000) return true } MotionEvent.ACTION_UP -> { (if (forward) mBinding.next else mBinding.previous).setImageResource(this.normal) mHandler.removeCallbacks(seekRunnable) mPreviewingSeek = false if (event.eventTime - event.downTime < 1000) { if (forward) onNextClick(v) else onPreviousClick(v) } else { if (forward) { if (possibleSeek < mService.length) mService.time = possibleSeek.toLong() else onNextClick(v) } else { if (possibleSeek > 0) mService.time = possibleSeek.toLong() else onPreviousClick(v) } } return true } } return false } } private fun showPlaylistTips() { val activity = activity as? AudioPlayerContainerActivity activity?.showTipViewIfNeeded(R.id.audio_playlist_tips, Constants.PREF_PLAYLIST_TIPS_SHOWN) } fun onStateChanged(newState: Int) { mPlayerState = newState when (newState) { BottomSheetBehavior.STATE_COLLAPSED -> { mBinding.header.setBackgroundResource(DEFAULT_BACKGROUND_DARKER_ID) setHeaderVisibilities(false, false, true, true, true, false) } BottomSheetBehavior.STATE_EXPANDED -> { mBinding.header.setBackgroundResource(0) setHeaderVisibilities(true, true, false, false, false, true) showPlaylistTips() if (mService != null) mPlaylistAdapter.currentIndex = mService.currentMediaPosition } else -> mBinding.header.setBackgroundResource(0) } } private var mTimelineListner: OnSeekBarChangeListener = object : OnSeekBarChangeListener { override fun onStopTrackingTouch(seekBar: SeekBar) {} override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onProgressChanged(sb: SeekBar, progress: Int, fromUser: Boolean) { if (fromUser && mService !== null) { mService.time = progress.toLong() mBinding.time.text = Tools.millisToString(if (mShowRemainingTime) progress - mService.length else progress.toLong()) mBinding.headerTime.text = Tools.millisToString(progress.toLong()) } } } private val mHeaderMediaSwitcherListener = object : AudioMediaSwitcherListener { override fun onMediaSwitching() {} override fun onMediaSwitched(position: Int) { if (mService === null) return when (position) { AudioMediaSwitcherListener.PREVIOUS_MEDIA -> mService.previous(true) AudioMediaSwitcherListener.NEXT_MEDIA -> mService.next() } } override fun onTouchDown() { hideHeaderButtons() } override fun onTouchUp() { restoreHeaderButtonVisibilities() } override fun onTouchClick() { val activity = activity as AudioPlayerContainerActivity activity.slideUpOrDownAudioPlayer() } } private val mCoverMediaSwitcherListener = object : AudioMediaSwitcherListener { override fun onMediaSwitching() {} override fun onMediaSwitched(position: Int) { if (mService === null) return when (position) { AudioMediaSwitcherListener.PREVIOUS_MEDIA -> mService.previous(true) AudioMediaSwitcherListener.NEXT_MEDIA -> mService.next() } } override fun onTouchDown() {} override fun onTouchUp() {} override fun onTouchClick() {} } private val hideSearchRunnable by lazy(LazyThreadSafetyMode.NONE) { Runnable { hideSearchField() mPlaylistAdapter.restoreList() } } }
gpl-2.0
fd1a2151a73846a5bb215b4e67aa9f3f
41.282575
167
0.662137
4.985008
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/manga/MangaViewModel.kt
1
4811
package me.proxer.app.manga import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.schedulers.Schedulers import me.proxer.app.base.BaseViewModel import me.proxer.app.exception.AgeConfirmationRequiredException import me.proxer.app.exception.NotLoggedInException import me.proxer.app.exception.PartialException import me.proxer.app.util.ErrorUtils import me.proxer.app.util.ErrorUtils.ErrorAction.ButtonAction import me.proxer.app.util.data.ResettingMutableLiveData import me.proxer.app.util.extension.buildPartialErrorSingle import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.isAgeRestricted import me.proxer.app.util.extension.isOfficial import me.proxer.app.util.extension.subscribeAndLogErrors import me.proxer.app.util.extension.toMediaLanguage import me.proxer.app.util.extension.toPrefixedHttpUrl import me.proxer.library.api.Endpoint import me.proxer.library.entity.info.EntryCore import me.proxer.library.enums.Category import me.proxer.library.enums.Language import kotlin.properties.Delegates /** * @author Ruben Gees */ class MangaViewModel( private val entryId: String, private val language: Language, episode: Int ) : BaseViewModel<MangaChapterInfo>() { override val dataSingle: Single<MangaChapterInfo> get() = Single.fromCallable { validate() } .flatMap { entrySingle() } .doOnSuccess { if (it.isAgeRestricted && !preferenceHelper.isAgeRestrictedMediaAllowed) { throw AgeConfirmationRequiredException() } } .flatMap { entry -> chapterSingle(entry) .doOnSuccess { if (!it.chapter.isOfficial && !storageHelper.isLoggedIn) { throw NotLoggedInException() } } .map { data -> if (data.chapter.isOfficial) { throw PartialException( MangaLinkException(data.chapter.title, data.chapter.server.toPrefixedHttpUrl()), entry ) } else if (data.chapter.pages == null) { throw PartialException(MangaNotAvailableException(), entry) } data } } val userStateData = ResettingMutableLiveData<Unit?>() val userStateError = ResettingMutableLiveData<ErrorUtils.ErrorAction?>() var episode by Delegates.observable(episode) { _, old, new -> if (old != new) reload() } private var cachedEntryCore: EntryCore? = null private var userStateDisposable: Disposable? = null init { disposables += preferenceHelper.isAgeRestrictedMediaAllowedObservable .subscribe { if (error.value?.buttonAction == ButtonAction.AGE_CONFIRMATION) { reload() } } } override fun onCleared() { userStateDisposable?.dispose() userStateDisposable = null super.onCleared() } fun setEpisode(value: Int, trigger: Boolean = true) { if (episode != value) { episode = value if (trigger) reload() } } fun markAsFinished() = updateUserState(api.info.markAsFinished(entryId)) fun bookmark(episode: Int) = updateUserState( api.ucp.setBookmark(entryId, episode, language.toMediaLanguage(), Category.MANGA) ) private fun entrySingle(): Single<EntryCore> = when (cachedEntryCore != null) { true -> Single.just(cachedEntryCore) false -> api.info.entryCore(entryId).buildSingle() } private fun chapterSingle(entry: EntryCore) = api.manga.chapter(entryId, episode, language) .buildPartialErrorSingle(entry) .map { MangaChapterInfo(it, entry.name, entry.episodeAmount) } @Suppress("ForbiddenVoid") private fun updateUserState(endpoint: Endpoint<Unit?>) { userStateDisposable?.dispose() userStateDisposable = Single.fromCallable { validators.validateLogin() } .flatMap { endpoint.buildSingle() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeAndLogErrors( { userStateError.value = null userStateData.value = Unit }, { userStateData.value = null userStateError.value = ErrorUtils.handle(it) } ) } }
gpl-3.0
125a6180a96dfe3cb4074c8d6c6d8b5c
34.902985
112
0.62274
4.985492
false
false
false
false
MaibornWolff/codecharta
analysis/import/SVNLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/input/metrics/RangeOfWeeksWithCommitsTest.kt
1
2406
package de.maibornwolff.codecharta.importer.svnlogparser.input.metrics import de.maibornwolff.codecharta.importer.svnlogparser.input.Commit import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.time.OffsetDateTime import java.time.ZoneOffset class RangeOfWeeksWithCommitsTest { private val zoneOffset = ZoneOffset.UTC @Test fun initial_value_zero() { // when val metric = RangeOfWeeksWithCommits() // then assertThat(metric.value()).isEqualTo(0) } @Test fun single_modification() { // given val metric = RangeOfWeeksWithCommits() // when val date = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date)) // then assertThat(metric.value()).isEqualTo(1) } @Test fun additional_modification_in_same_calendar_week() { // given val metric = RangeOfWeeksWithCommits() // when val date1 = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date1)) val date2 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date2)) // then assertThat(metric.value()).isEqualTo(1) } @Test fun additional_modification_in_successive_calendar_week() { // given val metric = RangeOfWeeksWithCommits() // when val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date1)) val date2 = OffsetDateTime.of(2016, 4, 4, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date2)) // then assertThat(metric.value()).isEqualTo(2) } @Test fun additional_modification_in_non_successive_calendar_week() { // given val metric = RangeOfWeeksWithCommits() // when val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date1)) val date2 = OffsetDateTime.of(2016, 4, 11, 12, 0, 0, 0, zoneOffset) metric.registerCommit(Commit("author", emptyList(), date2)) // then assertThat(metric.value()).isEqualTo(3) } }
bsd-3-clause
d5d4220dcefd1c0c424c57332fb315fb
29.846154
75
0.630507
4.141136
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/Sponsor.kt
1
726
package net.perfectdreams.loritta.morenitta.utils import com.github.salomonbrys.kotson.array import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.string import com.google.gson.JsonElement import java.math.BigDecimal data class Sponsor( val name: String, val slug: String, val paid: BigDecimal, val link: String, val banners: JsonElement ) { fun getRectangularBannerUrl(): String { val bannerAsArray = banners.array return bannerAsArray.first { it["type"].string == "pc" }["url"].string } fun getSquareBannerUrl(): String { val bannerAsArray = banners.array return bannerAsArray.firstOrNull { it["type"].string == "mobile" }?.get("url")?.string ?: getRectangularBannerUrl() } }
agpl-3.0
3fcfa1156f19ab3ca04ba4b853e23458
28.08
117
0.752066
3.541463
false
false
false
false
AlmasB/GroupNet
src/main/kotlin/icurves/util/MultiToSimple.kt
1
1297
package icurves.util import java.util.* /** * * * @author Almas Baimagambetov ([email protected]) */ class MultiToSimple { companion object { @JvmStatic fun decompose(D0: String): List<String> { val tokens = D0.split(" +".toRegex()).toMutableList() val elements = ArrayDeque<Char>() val result = arrayListOf<String>() while (tokens.isNotEmpty()) { var D1 = "" elements.add(tokens[0][0]) var usedElements = "" + elements.first while (elements.isNotEmpty()) { val e = elements.pop() val iter = tokens.iterator() while (iter.hasNext()) { val token = iter.next() if (token.contains(e)) { D1 += token + " " token.filter { !usedElements.contains(it) }.forEach { elements.add(it) usedElements += it } iter.remove() } } } result.add(D1.trim()) } return result } } }
apache-2.0
311639e56b48eee2e7ecbfe9dcc1da78
23.490566
81
0.402467
5.315574
false
false
false
false