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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/collections/Grouping.kt | 2 | 12870 | /*
* 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 kotlin.collections
/**
* Represents a source of elements with a [keyOf] function, which can be applied to each element to get its key.
*
* A [Grouping] structure serves as an intermediate step in group-and-fold operations:
* they group elements by their keys and then fold each group with some aggregating operation.
*
* It is created by attaching `keySelector: (T) -> K` function to a source of elements.
* To get an instance of [Grouping] use one of `groupingBy` extension functions:
* - [Iterable.groupingBy]
* - [Sequence.groupingBy]
* - [Array.groupingBy]
* - [CharSequence.groupingBy]
*
* For the list of group-and-fold operations available, see the [extension functions](#extension-functions) for `Grouping`.
*/
@SinceKotlin("1.1")
public interface Grouping<T, out K> {
/** Returns an [Iterator] over the elements of the source of this grouping. */
fun sourceIterator(): Iterator<T>
/** Extracts the key of an [element]. */
fun keyOf(element: T): K
}
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
*
* The key for each element is provided by the [Grouping.keyOf] function.
*
* @param operation function is invoked on each element with the following parameters:
* - `key`: the key of the group this element belongs to;
* - `accumulator`: the current value of the accumulator of the group, can be `null` if it's the first `element` encountered in the group;
* - `element`: the element from the source being aggregated;
* - `first`: indicates whether it's the first `element` encountered in the group.
*
* @return a [Map] associating the key of each group with the result of aggregation of the group elements.
*/
@SinceKotlin("1.1")
public inline fun <T, K, R> Grouping<T, K>.aggregate(
operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R
): Map<K, R> {
return aggregateTo(mutableMapOf<K, R>(), operation)
}
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments,
* and stores the results in the given [destination] map.
*
* The key for each element is provided by the [Grouping.keyOf] function.
*
* @param operation a function that is invoked on each element with the following parameters:
* - `key`: the key of the group this element belongs to;
* - `accumulator`: the current value of the accumulator of the group, can be `null` if it's the first `element` encountered in the group;
* - `element`: the element from the source being aggregated;
* - `first`: indicates whether it's the first `element` encountered in the group.
*
* If the [destination] map already has a value corresponding to some key,
* then the elements being aggregated for that key are never considered as `first`.
*
* @return the [destination] map associating the key of each group with the result of aggregation of the group elements.
*/
@SinceKotlin("1.1")
public inline fun <T, K, R, M : MutableMap<in K, R>> Grouping<T, K>.aggregateTo(
destination: M,
operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R
): M {
for (e in this.sourceIterator()) {
val key = keyOf(e)
val accumulator = destination[key]
destination[key] = operation(key, accumulator, e, accumulator == null && !destination.containsKey(key))
}
return destination
}
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
* An initial value of accumulator is provided by [initialValueSelector] function.
*
* @param initialValueSelector a function that provides an initial value of accumulator for each group.
* It's invoked with parameters:
* - `key`: the key of the group;
* - `element`: the first element being encountered in that group.
*
* @param operation a function that is invoked on each element with the following parameters:
* - `key`: the key of the group this element belongs to;
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being accumulated.
*
* @return a [Map] associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <T, K, R> Grouping<T, K>.fold(
initialValueSelector: (key: K, element: T) -> R,
operation: (key: K, accumulator: R, element: T) -> R
): Map<K, R> =
aggregate { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) }
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments,
* and stores the results in the given [destination] map.
* An initial value of accumulator is provided by [initialValueSelector] function.
*
* @param initialValueSelector a function that provides an initial value of accumulator for each group.
* It's invoked with parameters:
* - `key`: the key of the group;
* - `element`: the first element being encountered in that group.
*
* If the [destination] map already has a value corresponding to some key, that value is used as an initial value of
* the accumulator for that group and the [initialValueSelector] function is not called for that group.
*
* @param operation a function that is invoked on each element with the following parameters:
* - `key`: the key of the group this element belongs to;
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being accumulated.
*
* @return the [destination] map associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <T, K, R, M : MutableMap<in K, R>> Grouping<T, K>.foldTo(
destination: M,
initialValueSelector: (key: K, element: T) -> R,
operation: (key: K, accumulator: R, element: T) -> R
): M =
aggregateTo(destination) { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) }
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
* An initial value of accumulator is the same [initialValue] for each group.
*
* @param operation a function that is invoked on each element with the following parameters:
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being accumulated.
*
* @return a [Map] associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <T, K, R> Grouping<T, K>.fold(
initialValue: R,
operation: (accumulator: R, element: T) -> R
): Map<K, R> =
aggregate { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) }
/**
* Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments,
* and stores the results in the given [destination] map.
* An initial value of accumulator is the same [initialValue] for each group.
*
* If the [destination] map already has a value corresponding to the key of some group,
* that value is used as an initial value of the accumulator for that group.
*
* @param operation a function that is invoked on each element with the following parameters:
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being accumulated.
*
* @return the [destination] map associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <T, K, R, M : MutableMap<in K, R>> Grouping<T, K>.foldTo(
destination: M,
initialValue: R,
operation: (accumulator: R, element: T) -> R
): M =
aggregateTo(destination) { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) }
/**
* Groups elements from the [Grouping] source by key and applies the reducing [operation] to the elements of each group
* sequentially starting from the second element of the group,
* passing the previously accumulated value and the current element as arguments,
* and stores the results in a new map.
* An initial value of accumulator is the first element of the group.
*
* @param operation a function that is invoked on each subsequent element of the group with the following parameters:
* - `key`: the key of the group this element belongs to;
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being accumulated.
*
* @return a [Map] associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <S, T : S, K> Grouping<T, K>.reduce(
operation: (key: K, accumulator: S, element: T) -> S
): Map<K, S> =
aggregate { key, acc, e, first ->
if (first) e else operation(key, acc as S, e)
}
/**
* Groups elements from the [Grouping] source by key and applies the reducing [operation] to the elements of each group
* sequentially starting from the second element of the group,
* passing the previously accumulated value and the current element as arguments,
* and stores the results in the given [destination] map.
* An initial value of accumulator is the first element of the group.
*
* If the [destination] map already has a value corresponding to the key of some group,
* that value is used as an initial value of the accumulator for that group and the first element of that group is also
* subjected to the [operation].
* @param operation a function that is invoked on each subsequent element of the group with the following parameters:
* - `accumulator`: the current value of the accumulator of the group;
* - `element`: the element from the source being folded;
*
* @return the [destination] map associating the key of each group with the result of accumulating the group elements.
*/
@SinceKotlin("1.1")
@Suppress("UNCHECKED_CAST")
public inline fun <S, T : S, K, M : MutableMap<in K, S>> Grouping<T, K>.reduceTo(
destination: M,
operation: (key: K, accumulator: S, element: T) -> S
): M =
aggregateTo(destination) { key, acc, e, first ->
if (first) e else operation(key, acc as S, e)
}
/**
* Groups elements from the [Grouping] source by key and counts elements in each group.
*
* @return a [Map] associating the key of each group with the count of elements in the group.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
public fun <T, K> Grouping<T, K>.eachCount(): Map<K, Int> = eachCountTo(mutableMapOf<K, Int>())
/**
* Groups elements from the [Grouping] source by key and counts elements in each group to the given [destination] map.
*
* If the [destination] map already has a value corresponding to the key of some group,
* that value is used as an initial value of the counter for that group.
*
* @return the [destination] map associating the key of each group with the count of elements in the group.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
public fun <T, K, M : MutableMap<in K, Int>> Grouping<T, K>.eachCountTo(destination: M): M =
foldTo(destination, 0) { acc, _ -> acc + 1 }
| apache-2.0 | 75c7ae03a879ae2a1b0c33a0039fe7aa | 47.202247 | 139 | 0.712898 | 3.999378 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/types/subtyping/simpleSubtypeSupertype.kt | 2 | 1940 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KCallable
import kotlin.reflect.full.*
import kotlin.test.assertTrue
import kotlin.test.assertFalse
fun check(subCallable: KCallable<*>, superCallable: KCallable<*>, shouldBeSubtype: Boolean) {
val subtype = subCallable.returnType
val supertype = superCallable.returnType
if (shouldBeSubtype) {
assertTrue(subtype.isSubtypeOf(supertype))
assertTrue(supertype.isSupertypeOf(subtype))
} else {
assertFalse(subtype.isSubtypeOf(supertype))
assertFalse(supertype.isSupertypeOf(subtype))
}
}
open class O
class X : O()
fun any(): Any = null!!
fun string(): String = null!!
fun nullableString(): String? = null!!
fun int(): Int = null!!
fun nothing(): Nothing = null!!
fun nullableNothing(): Nothing? = null!!
fun function2(): (Any, Any) -> Any = null!!
fun function3(): (Any, Any, Any) -> Any = null!!
fun box(): String {
check(::any, ::any, true)
check(::int, ::int, true)
check(::nothing, ::nothing, true)
check(::nullableNothing, ::nullableNothing, true)
check(::string, ::any, true)
check(::nullableString, ::any, false)
check(::int, ::any, true)
check(::O, ::any, true)
check(::X, ::any, true)
check(::nothing, ::any, true)
check(::nothing, ::string, true)
check(::nothing, ::nullableString, true)
check(::nullableNothing, ::nullableString, true)
check(::nullableNothing, ::string, false)
check(::string, ::nullableString, true)
check(::nullableString, ::string, false)
check(::X, ::O, true)
check(::O, ::X, false)
check(::int, ::string, false)
check(::string, ::int, false)
check(::any, ::string, false)
check(::any, ::nullableString, false)
check(::function2, ::function3, false)
check(::function3, ::function2, false)
return "OK"
}
| apache-2.0 | e762b6e47db16f4094f341646da7a4c1 | 27.529412 | 93 | 0.647938 | 3.833992 | false | false | false | false |
exponent/exponent | packages/expo-sensors/android/src/main/java/expo/modules/sensors/services/SensorServiceSubscription.kt | 2 | 1333 | // Copyright 2015-present 650 Industries. All rights reserved.
package expo.modules.sensors.services
import android.hardware.SensorEventListener2
import expo.modules.interfaces.sensors.SensorServiceSubscriptionInterface
class SensorServiceSubscription internal constructor(private val mSubscribableSensorService: SubscribableSensorService, val sensorEventListener: SensorEventListener2) : SensorServiceSubscriptionInterface {
private var mIsEnabled = false
private var mUpdateInterval: Long = 100L
private var mHasBeenReleased = false
override fun start() {
if (mHasBeenReleased) {
return
}
if (!mIsEnabled) {
mIsEnabled = true
mSubscribableSensorService.onSubscriptionEnabledChanged(this)
}
}
override fun isEnabled(): Boolean {
return mIsEnabled
}
override fun getUpdateInterval(): Long {
return mUpdateInterval
}
override fun setUpdateInterval(updateInterval: Long) {
if (mHasBeenReleased) {
return
}
mUpdateInterval = updateInterval
}
override fun stop() {
if (mIsEnabled) {
mIsEnabled = false
mSubscribableSensorService.onSubscriptionEnabledChanged(this)
}
}
override fun release() {
if (!mHasBeenReleased) {
mSubscribableSensorService.removeSubscription(this)
mHasBeenReleased = true
}
}
}
| bsd-3-clause | 4cb6e32cb25bd917fc3259cdd399bbd4 | 26.204082 | 205 | 0.742686 | 4.794964 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/notifications/schedulers/IntervalSchedulerModel.kt | 2 | 2939 | package host.exp.exponent.notifications.schedulers
import host.exp.exponent.notifications.managers.SchedulersDatabase
import host.exp.exponent.notifications.managers.SchedulersManagerProxy
import host.exp.exponent.kernel.ExperienceKey
import android.content.Intent
import android.os.SystemClock
import com.raizlabs.android.dbflow.annotation.Column
import com.raizlabs.android.dbflow.annotation.PrimaryKey
import com.raizlabs.android.dbflow.annotation.Table
import com.raizlabs.android.dbflow.structure.BaseModel
import org.joda.time.DateTime
import org.json.JSONException
import java.util.*
@Table(database = SchedulersDatabase::class)
class IntervalSchedulerModel : BaseModel(), SchedulerModel {
@Column @PrimaryKey(autoincrement = true) var id = 0
@Column override var notificationId = 0
@Column(name = "experienceId") var experienceScopeKey: String? = null
@Column var isRepeat = false
@Column var serializedDetails: String? = null
@Column var scheduledTime: Long = 0
@Column var interval: Long = 0
override fun canBeRescheduled(): Boolean {
return isRepeat || DateTime.now().toDate().time < scheduledTime
}
override fun saveAndGetId(): String {
save() // get id from database
val details = getDetailsMap()
details!![SchedulersManagerProxy.SCHEDULER_ID] = idAsString
setDetailsFromMap(details)
save()
return idAsString
}
override val ownerExperienceKey: ExperienceKey
get() = ExperienceKey(experienceScopeKey!!)
override val idAsString: String
get() = Integer.valueOf(id).toString() + this.javaClass.simpleName
override fun remove() {
delete()
}
// elapsedTime
// time when notification should be presented can be represented as (interval * t + scheduledTime)
override val nextAppearanceTime: Long
get() {
var now = DateTime.now().toDate().time
val whenShouldAppear: Long
if (now <= scheduledTime) {
whenShouldAppear = scheduledTime
} else {
require(interval > 0)
now = DateTime.now().toDate().time
val elapsedTime = now - scheduledTime
val t = elapsedTime / interval + 1
whenShouldAppear = interval * t + scheduledTime
}
val bootTime = DateTime.now().toDate().time - SystemClock.elapsedRealtime()
return whenShouldAppear - bootTime
}
override fun shouldBeTriggeredByAction(action: String?): Boolean {
return triggeringActions.contains(action)
}
override fun getDetailsMap(): HashMap<String, Any>? {
return try {
HashMapSerializer.deserialize(serializedDetails)
} catch (e: JSONException) {
e.printStackTrace()
null
}
}
override fun setDetailsFromMap(detailsMap: HashMap<String, Any>) {
serializedDetails = HashMapSerializer.serialize(detailsMap)
}
companion object {
private val triggeringActions = listOf(
null,
Intent.ACTION_REBOOT,
Intent.ACTION_BOOT_COMPLETED
)
}
}
| bsd-3-clause | 1c77e534d136f87087eb1a13fd481789 | 31.296703 | 100 | 0.724396 | 4.535494 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/LiveStatsViewers.kt | 1 | 486 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Live stats viewers data.
*
* @param current The current amount of people watching this video.
* @param peak The peak amount of people watching this video at any time in the provided date range.
*/
@JsonClass(generateAdapter = true)
data class LiveStatsViewers(
@Json(name = "current")
val current: Long? = null,
@Json(name = "peak")
val peak: Long? = null
)
| mit | 57c594abf54a8997ae8f742c6866a184 | 23.3 | 100 | 0.713992 | 3.767442 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt | 4 | 1327 | // 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.core.util
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.kotlin.idea.util.application.isDispatchThread
fun <T : Any> runInReadActionWithWriteActionPriorityWithPCE(f: () -> T): T =
runInReadActionWithWriteActionPriority(f) ?: throw ProcessCanceledException()
fun <T : Any> runInReadActionWithWriteActionPriority(f: () -> T): T? {
if (isDispatchThread()) {
return f()
}
var r: T? = null
val complete = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority {
r = f()
}
if (!complete) return null
return r!!
}
fun <T : Any> Project.runSynchronouslyWithProgress(@NlsContexts.ProgressTitle progressTitle: String, canBeCanceled: Boolean, action: () -> T): T? {
var result: T? = null
ProgressManager.getInstance().runProcessWithProgressSynchronously({ result = action() }, progressTitle, canBeCanceled, this)
return result
} | apache-2.0 | c202fc8aa27c5165e51b1876630b94af | 39.242424 | 158 | 0.756594 | 4.35082 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/ClosureParameterAugmenter.kt | 5 | 5828 | // 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.intentions.style.inference
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.psi.*
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter.Companion.createInferenceResult
import org.jetbrains.plugins.groovy.intentions.style.inference.driver.closure.compose
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeAugmenter
import org.jetbrains.plugins.groovy.lang.psi.impl.stringValue
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.SignatureHintProcessor
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.GroovyInferenceSessionBuilder
class ClosureParameterAugmenter : TypeAugmenter() {
override fun inferType(variable: GrVariable): PsiType? {
if (variable !is GrParameter || variable.typeElement != null) {
return null
}
val (index, closure) = variable.getIndexAndClosure() ?: return null
val call = closure.parentOfType<GrCall>()?.takeIf { (it.expressionArguments + it.closureArguments).contains(closure) } ?: return null
val method = (call.resolveMethod() as? GrMethod)?.takeIf { it.parameters.any(GrParameter::eligibleForExtendedInference) }
?: return null
val signatures = computeSignatures(call, closure, method) ?: return null
val parameters = closure.allParameters
return signatures.singleOrNull { it.size == parameters.size }?.getOrNull(index)?.unwrapBound()
}
private fun GrParameter.getIndexAndClosure(): Pair<Int, GrFunctionalExpression>? {
if (this is ClosureSyntheticParameter) {
val closure = this.closure ?: return null
return 0 to closure
}
else {
val closure = this.parent?.parent as? GrFunctionalExpression ?: return null
val index = closure.parameterList.getParameterNumber(this)
return index to closure
}
}
private fun PsiType.unwrapBound(): PsiType? = if (this is PsiWildcardType && isSuper) bound else this
private val closureParamsShort = GroovyCommonClassNames.GROOVY_TRANSFORM_STC_CLOSURE_PARAMS.substringAfterLast('.')
private fun computeAnnotationBasedSubstitutor(call: GrCall,
builder: GroovyInferenceSessionBuilder): PsiSubstitutor {
return builder.skipClosureIn(call).resolveMode(false).build().inferSubst()
}
private fun computeSignatures(methodCall: GrCall,
closureBlock: GrFunctionalExpression,
method: GrMethod): List<Array<out PsiType>>? {
val (virtualMethod, virtualToActualSubstitutor) = createInferenceResult(method) ?: return null
virtualMethod ?: return null
val resolveResult = methodCall.advancedResolve() as? GroovyMethodResult ?: return null
val methodCandidate = resolveResult.candidate ?: return null
val sessionBuilder = CollectingGroovyInferenceSessionBuilder(methodCall, methodCandidate, virtualMethod,
resolveResult.contextSubstitutor).addProxyMethod(method)
val annotationBasedSubstitutor = computeAnnotationBasedSubstitutor(methodCall, sessionBuilder)
val completeContextSubstitutor = virtualToActualSubstitutor.putAll(annotationBasedSubstitutor) compose resolveResult.substitutor
val annotatedClosureParameter = findAnnotatedClosureParameter(resolveResult, closureBlock, virtualMethod) ?: return null
val anno = annotatedClosureParameter.modifierList.annotations.find { it.shortName == closureParamsShort } ?: return null
return getSignatures(anno, completeContextSubstitutor, virtualMethod) ?: return null
}
private fun findAnnotatedClosureParameter(resolveResult: GroovyMethodResult,
closureBlock: GrFunctionalExpression,
virtualMethod: GrMethod): GrParameter? {
val method = resolveResult.candidate?.method ?: return null
val methodParameter = (resolveResult.candidate?.argumentMapping?.targetParameter(
ExpressionArgument(closureBlock))?.psi as? GrParameter)?.takeIf { it.eligibleForExtendedInference() } ?: return null
return virtualMethod.parameters.getOrNull(method.parameterList.getParameterIndex(methodParameter)) ?: return null
}
private fun getSignatures(anno: PsiAnnotation, substitutor: PsiSubstitutor, virtualMethod: GrMethod): List<Array<out PsiType>>? {
val className = (anno.findAttributeValue("value") as? GrReferenceExpression)?.qualifiedReferenceName ?: return null
val processor = SignatureHintProcessor.getHintProcessor(className) ?: return null
val options = AnnotationUtil.arrayAttributeValues(anno.findAttributeValue("options")).mapNotNull { (it as? PsiLiteral)?.stringValue() }
return processor.inferExpectedSignatures(virtualMethod, substitutor, options.toTypedArray())
}
} | apache-2.0 | 0b26753be559adb2dac7b1900eba0318 | 60.357895 | 140 | 0.763727 | 5.015491 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/GroupMembership.kt | 1 | 627 | package com.habitrpg.android.habitica.models.social
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class GroupMembership : RealmObject {
@PrimaryKey
var combinedID: String = ""
var userID: String = ""
set(value) {
field = value
combinedID = userID + groupID
}
var groupID: String = ""
set(value) {
field = value
combinedID = userID + groupID
}
constructor(userID: String, groupID: String) : super() {
this.userID = userID
this.groupID = groupID
}
constructor() : super()
}
| gpl-3.0 | 1e9942bb4bea75cd50785305f6a9b7b0 | 22.222222 | 60 | 0.591707 | 4.543478 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/ColorNodes.kt | 1 | 4340 | package de.fabmax.kool.pipeline.shadermodel
import de.fabmax.kool.util.Color
class ColorAlphaNode(graph: ShaderGraph) : ShaderNode("colorAlphaNode_${graph.nextNodeId}", graph) {
var inColor = ShaderNodeIoVar(ModelVar4fConst(Color.MAGENTA), null)
var inAlpha = ShaderNodeIoVar(ModelVar1fConst(1f), null)
val outAlphaColor = ShaderNodeIoVar(ModelVar4f("${name}_outColor"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inColor, inAlpha)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("""
${outAlphaColor.declare()} = vec4(${inColor.ref3f()}, ${inColor.ref4f()}.a * ${inAlpha.ref1f()});
""")
}
}
class PremultiplyColorNode(graph: ShaderGraph) : ShaderNode("colorPreMult_${graph.nextNodeId}", graph) {
var inColor = ShaderNodeIoVar(ModelVar4fConst(Color.MAGENTA))
val outColor = ShaderNodeIoVar(ModelVar4f("${name}_outColor"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inColor)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${outColor.declare()} = vec4(${inColor.ref3f()} * ${inColor.ref4f()}.a, ${inColor.ref4f()}.a);")
}
}
class GammaNode(graph: ShaderGraph) : ShaderNode("gamma_${graph.nextNodeId}", graph) {
var inColor = ShaderNodeIoVar(ModelVar4fConst(Color.MAGENTA))
var inGamma = ShaderNodeIoVar(ModelVar1fConst(1f / 2.2f))
val outColor = ShaderNodeIoVar(ModelVar4f("${name}_outColor"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inColor, inGamma)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${outColor.declare()} = vec4(pow(${inColor.ref3f()}, vec3(1.0/${inGamma.ref1f()})), ${inColor.ref4f()}.a);")
}
}
class HdrToLdrNode(graph: ShaderGraph) : ShaderNode("hdrToLdr_${graph.nextNodeId}", graph) {
var inColor = ShaderNodeIoVar(ModelVar4fConst(Color.MAGENTA))
var inGamma = ShaderNodeIoVar(ModelVar1fConst(2.2f))
val outColor = ShaderNodeIoVar(ModelVar4f("${name}_outColor"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inColor, inGamma)
}
private fun generateUncharted2(generator: CodeGenerator) {
generator.appendFunction("uncharted2", """
vec3 uncharted2Tonemap_func(vec3 x) {
float A = 0.15; // shoulder strength
float B = 0.50; // linear strength
float C = 0.10; // linear angle
float D = 0.20; // toe strength
float E = 0.02; // toe numerator
float F = 0.30; // toe denominator --> E/F = toe angle
return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}
vec3 uncharted2Tonemap(vec3 rgbLinear) {
float W = 11.2; // linear white point value
float ExposureBias = 2.0;
vec3 curr = uncharted2Tonemap_func(ExposureBias * rgbLinear);
vec3 whiteScale = 1.0 / uncharted2Tonemap_func(vec3(W));
return curr * whiteScale;
}
""")
generator.appendMain("""
vec3 ${name}_color = uncharted2Tonemap(${inColor.ref3f()});
${outColor.declare()} = vec4(pow(${name}_color, vec3(1.0/${inGamma.ref1f()})), ${inColor.ref4f()}.a);
""")
}
private fun generateReinhard(generator: CodeGenerator) {
generator.appendMain("""
vec3 ${name}_color = ${inColor.ref3f()} / (${inColor.ref3f()} + vec3(1.0));
${outColor.declare()} = vec4(pow(${name}_color, vec3(1.0/${inGamma.ref1f()})), ${inColor.ref4f()}.a);
""")
}
private fun generateJimHejlRichardBurgessDawson(generator: CodeGenerator) {
generator.appendMain("""
vec3 ${name}_color = max(vec3(0), ${inColor.ref3f()} - 0.004);
${outColor.declare()} = vec4((${name}_color * (6.2 * ${name}_color + 0.5)) / (${name}_color * (6.2 * ${name}_color + 1.7) + 0.06), 1.0);
""")
}
override fun generateCode(generator: CodeGenerator) {
generateUncharted2(generator)
}
}
| apache-2.0 | 0cd58e4b6b2248292d20c544559a249b | 39.560748 | 148 | 0.609908 | 3.706234 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt | 1 | 4362 | // 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.intentions
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.jsonUtils.getNullableString
import org.jetbrains.kotlin.idea.jsonUtils.getString
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.junit.Assert
import java.io.File
abstract class AbstractMultiFileIntentionTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor {
val testFile = File(testDataPath, fileName())
val config = JsonParser().parse(FileUtil.loadFile(testFile, true)) as JsonObject
val withRuntime = config["withRuntime"]?.asBoolean ?: false
return if (withRuntime)
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
else
KotlinLightProjectDescriptor.INSTANCE
}
protected fun doTest(path: String) {
val testFile = File(path)
val config = JsonParser().parse(FileUtil.loadFile(testFile, true)) as JsonObject
val mainFilePath = config.getString("mainFile")
val intentionAction = Class.forName(config.getString("intentionClass")).newInstance() as IntentionAction
val isApplicableExpected = config["isApplicable"]?.asBoolean ?: true
doTest(path) { rootDir ->
val mainFile = myFixture.configureFromTempProjectFile(mainFilePath)
val conflictFile = rootDir.findFileByRelativePath("$mainFilePath.conflicts")
try {
Assert.assertTrue(
"isAvailable() for ${intentionAction::class.java} should return $isApplicableExpected",
isApplicableExpected == intentionAction.isAvailable(project, editor, mainFile)
)
config.getNullableString("intentionText")?.let {
TestCase.assertEquals("Intention text mismatch", it, intentionAction.text)
}
if (isApplicableExpected) {
project.executeWriteCommand(intentionAction.text) {
intentionAction.invoke(project, editor, mainFile)
}
}
assert(conflictFile == null) { "Conflict file $conflictFile should not exist" }
} catch (e: CommonRefactoringUtil.RefactoringErrorHintException) {
val expectedConflicts = LoadTextUtil.loadText(conflictFile!!).toString().trim()
assertEquals(expectedConflicts, e.message)
}
}
}
protected fun doTest(path: String, action: (VirtualFile) -> Unit) {
val beforeDir = path.removePrefix(testDataPath).substringBeforeLast('/') + "/before"
val beforeVFile = myFixture.copyDirectoryToProject(beforeDir, "")
PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments()
val afterDir = beforeDir.substringBeforeLast("/") + "/after"
val afterDirIOFile = File(testDataPath, afterDir)
val afterVFile = LocalFileSystem.getInstance().findFileByIoFile(afterDirIOFile)!!
UsefulTestCase.refreshRecursively(afterVFile)
action(beforeVFile)
PsiDocumentManager.getInstance(project).commitAllDocuments()
FileDocumentManager.getInstance().saveAllDocuments()
PlatformTestUtil.assertDirectoriesEqual(afterVFile, beforeVFile)
}
} | apache-2.0 | 91ba79d64c4000bde950a9b1c134bb94 | 48.022472 | 158 | 0.725585 | 5.507576 | false | true | false | false |
HughG/yested | src/main/docsite/effects/bidirectional.kt | 2 | 2974 | package effects
import net.yested.*
import net.yested.bootstrap.*
fun createPanel(n:Int) =
Panel() with {
heading { +"Sample component $n" }
content {
+"Sample Text of component $n"
}
}
fun createBidirectionalEffectsSection(): Div {
var index = 0
val panels = arrayOf(createPanel(0), createPanel(1))
val container = Div()
var effect: BiDirectionEffect = Fade()
fun selectEffect(effectCode:String) {
effect =
when(effectCode) {
"fade" -> Fade()
"slide" -> Slide()
else -> throw Exception("Unknown effect.")
}
}
fun toggleContent() =
container.setChild(panels[index++ % panels.size], effect)
toggleContent()
return div {
row {
col(Medium(12)) {
pageHeader { h3 { +"BiDirectional Effects" } }
}
}
row {
col(Medium(6)) {
+"BiDirectonalEffects can be used to swap content of parent component like Div or Span"
code(lang="kotlin", content ="divOrSpan.setChild(anotherComponent, Fade())")
h4 { +"Demo" }
row {
col(ExtraSmall(4)) {
btsButton(look = ButtonLook.PRIMARY, label = { +"Toggle it" }, onclick = { toggleContent() })
}
col(ExtraSmall(8)) {
aligned(align = TextAlign.RIGHT) {
buttonGroup(onSelect = ::selectEffect) {
button(value = "fade") { +"Fade Effect" }
button(value = "slide") { +"Slide Effect" }
select("fade")
}
}
}
}
+container
}
col(Medium(6)) {
h4 { +"Source code"}
code(lang = "kotlin", content =
"""var index = 0
val panels = array(createPanel(0), createPanel(1))
val container = Div()
var effect: BiDirectionEffect = Fade()
fun selectEffect(effectCode:String) {
effect =
when(effectCode) {
"fade" -> Fade()
"slide" -> Slide()
else -> throw Exception("Unknown effect.")
}
}
fun toogleContent() =
container.setChild(panels.get(index++ % panels.size()), effect)
toogleContent()
...
row {
col(ExtraSmall(4)) {
btsButton(look = ButtonLook.PRIMARY, label = { +"Toogle it" }, onclick = ::toogleContent)
}
col(ExtraSmall(8)) {
aligned(align = TextAlign.RIGHT) {
buttonGroup(onSelect = ::selectEffect) {
button(value = "fade") { +"Fade Effect" }
button(value = "slide") { +"Slide Effect" }
select("fade")
}
}
}
}
+container""")
}
}
}
} | mit | cff930d5925c69c9efa524eb57295476 | 27.333333 | 117 | 0.469401 | 4.512898 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ModuleTestEntityImpl.kt | 2 | 12763 | // 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.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.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
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.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ModuleTestEntityImpl(val dataSource: ModuleTestEntityData) : ModuleTestEntity, WorkspaceEntityBase() {
companion object {
internal val CONTENTROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleTestEntity::class.java,
ContentRootTestEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val FACETS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleTestEntity::class.java, FacetTestEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CONTENTROOTS_CONNECTION_ID,
FACETS_CONNECTION_ID,
)
}
override val name: String
get() = dataSource.name
override val contentRoots: List<ContentRootTestEntity>
get() = snapshot.extractOneToManyChildren<ContentRootTestEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList()
override val facets: List<FacetTestEntity>
get() = snapshot.extractOneToManyChildren<FacetTestEntity>(FACETS_CONNECTION_ID, this)!!.toList()
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ModuleTestEntityData?) : ModifiableWorkspaceEntityBase<ModuleTestEntity, ModuleTestEntityData>(
result), ModuleTestEntity.Builder {
constructor() : this(ModuleTestEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ModuleTestEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// 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().isNameInitialized()) {
error("Field ModuleTestEntity#name should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CONTENTROOTS_CONNECTION_ID, this) == null) {
error("Field ModuleTestEntity#contentRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] == null) {
error("Field ModuleTestEntity#contentRoots should be initialized")
}
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(FACETS_CONNECTION_ID, this) == null) {
error("Field ModuleTestEntity#facets should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] == null) {
error("Field ModuleTestEntity#facets 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 ModuleTestEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.name != dataSource.name) this.name = dataSource.name
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData(true).name = value
changedProperty.add("name")
}
// List of non-abstract referenced types
var _contentRoots: List<ContentRootTestEntity>? = emptyList()
override var contentRoots: List<ContentRootTestEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ContentRootTestEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootTestEntity> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootTestEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CONTENTROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CONTENTROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CONTENTROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] = value
}
changedProperty.add("contentRoots")
}
// List of non-abstract referenced types
var _facets: List<FacetTestEntity>? = emptyList()
override var facets: List<FacetTestEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<FacetTestEntity>(FACETS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
FACETS_CONNECTION_ID)] as? List<FacetTestEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] as? List<FacetTestEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, FACETS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(FACETS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, FACETS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] = value
}
changedProperty.add("facets")
}
override fun getEntityClass(): Class<ModuleTestEntity> = ModuleTestEntity::class.java
}
}
class ModuleTestEntityData : WorkspaceEntityData.WithCalculableSymbolicId<ModuleTestEntity>() {
lateinit var name: String
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ModuleTestEntity> {
val modifiable = ModuleTestEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ModuleTestEntity {
return getCached(snapshot) {
val entity = ModuleTestEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return ModuleTestEntitySymbolicId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ModuleTestEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ModuleTestEntity(name, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ModuleTestEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ModuleTestEntityData
if (this.name != other.name) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | c2a1d88702a8f58695607d956c45a615 | 38.030581 | 176 | 0.665204 | 5.300249 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/InjectionInfo.kt | 2 | 1279 | // 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.injection
import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
internal class InjectionInfo(private val languageId: String?, val prefix: String?, val suffix: String?) {
fun toBaseInjection(injectionSupport: LanguageInjectionSupport): BaseInjection? {
if (languageId == null) return null
val baseInjection = BaseInjection(injectionSupport.id)
baseInjection.injectedLanguageId = languageId
if (prefix != null) {
baseInjection.prefix = prefix
}
if (suffix != null) {
baseInjection.suffix = suffix
}
return baseInjection
}
companion object {
fun fromBaseInjection(baseInjection: BaseInjection?): InjectionInfo? {
if (baseInjection == null) {
return null
}
return InjectionInfo(
baseInjection.injectedLanguageId,
baseInjection.prefix,
baseInjection.suffix
)
}
}
} | apache-2.0 | f0752a0f4107dc1e7449d3159c2e7645 | 31.820513 | 158 | 0.654418 | 5.178138 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeImpl.kt | 1 | 7990 | // 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.workspaceModel.ide.impl.legacyBridge.module
import com.intellij.configurationStore.RenameableStateStorageManager
import com.intellij.facet.Facet
import com.intellij.facet.FacetManager
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.impl.ModulePathMacroManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.impl.ModuleImpl
import com.intellij.openapi.project.Project
import com.intellij.serviceContainer.PrecomputedExtensionModel
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.VirtualFileUrlBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.ide.toPath
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.bridgeEntities.addModuleCustomImlDataEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnStorage
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
@Suppress("OVERRIDE_DEPRECATION")
internal class ModuleBridgeImpl(
override var moduleEntityId: ModuleId,
name: String,
project: Project,
virtualFileUrl: VirtualFileUrl?,
override var entityStorage: VersionedEntityStorage,
override var diff: MutableEntityStorage?
) : ModuleImpl(name, project, virtualFileUrl as? VirtualFileUrlBridge), ModuleBridge {
init {
// default project doesn't have modules
if (!project.isDefault && !project.isDisposed) {
project.messageBus.connect(this).subscribe(WorkspaceModelTopics.CHANGED, object : WorkspaceModelChangeListener {
override fun beforeChanged(event: VersionedStorageChange) {
event.getChanges(ModuleEntity::class.java).filterIsInstance<EntityChange.Removed<ModuleEntity>>().forEach {
if (it.entity.symbolicId != moduleEntityId) return@forEach
if (event.storageBefore.moduleMap.getDataByEntity(it.entity) != this@ModuleBridgeImpl) return@forEach
val currentStore = entityStorage.current
val storage = if (currentStore is MutableEntityStorage) currentStore.toSnapshot() else currentStore
entityStorage = VersionedEntityStorageOnStorage(storage)
assert(moduleEntityId in entityStorage.current) {
// If we ever get this assertion, replace use `event.storeBefore` instead of current
// As it made in ArtifactBridge
"Cannot resolve module $moduleEntityId. Current store: $currentStore"
}
}
}
})
}
}
override fun rename(newName: String, newModuleFileUrl: VirtualFileUrl?, notifyStorage: Boolean) {
myImlFilePointer = newModuleFileUrl as VirtualFileUrlBridge
rename(newName, notifyStorage)
}
override fun rename(newName: String, notifyStorage: Boolean) {
moduleEntityId = moduleEntityId.copy(name = newName)
super<ModuleImpl>.rename(newName, notifyStorage)
}
override fun onImlFileMoved(newModuleFileUrl: VirtualFileUrl) {
myImlFilePointer = newModuleFileUrl as VirtualFileUrlBridge
val imlPath = newModuleFileUrl.toPath()
(store.storageManager as RenameableStateStorageManager).pathRenamed(imlPath, null)
store.setPath(imlPath)
(PathMacroManager.getInstance(this) as? ModulePathMacroManager)?.onImlFileMoved()
}
override fun registerComponents(modules: List<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel?,
listenerCallbacks: MutableList<in Runnable>?) {
registerComponents(modules.find { it.pluginId == PluginManagerCore.CORE_ID }, modules, precomputedExtensionModel, app, listenerCallbacks)
}
override fun callCreateComponents() {
@Suppress("DEPRECATION")
createComponents()
}
override suspend fun callCreateComponentsNonBlocking() {
createComponentsNonBlocking()
}
override fun initFacets() {
FacetManager.getInstance(this).allFacets.forEach(Facet<*>::initFacet)
}
override fun registerComponents(corePlugin: IdeaPluginDescriptor?,
modules: List<IdeaPluginDescriptorImpl>,
precomputedExtensionModel: PrecomputedExtensionModel?,
app: Application?,
listenerCallbacks: MutableList<in Runnable>?) {
super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks)
if (corePlugin == null) {
return
}
unregisterComponent(DeprecatedModuleOptionManager::class.java)
try {
//todo improve
val classLoader = javaClass.classLoader
val apiClass = classLoader.loadClass("com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager")
val implClass = classLoader.loadClass("com.intellij.openapi.externalSystem.service.project.ExternalSystemModulePropertyManagerBridge")
registerService(serviceInterface = apiClass, implementation = implClass, pluginDescriptor = corePlugin, override = true)
}
catch (ignored: Throwable) {
}
}
override fun getOptionValue(key: String): String? {
val moduleEntity = this.findModuleEntity(entityStorage.current)
if (key == Module.ELEMENT_TYPE) {
return moduleEntity?.type
}
return moduleEntity?.customImlData?.customModuleOptions?.get(key)
}
override fun setOption(key: String, value: String?) {
fun updateOptionInEntity(diff: MutableEntityStorage, entity: ModuleEntity) {
if (key == Module.ELEMENT_TYPE) {
diff.modifyEntity(entity) { type = value }
}
else {
val customImlData = entity.customImlData
if (customImlData == null) {
if (value != null) {
diff.addModuleCustomImlDataEntity(null, mapOf(key to value), entity, entity.entitySource)
}
}
else {
diff.modifyEntity(customImlData) {
if (value != null) {
customModuleOptions = customModuleOptions.toMutableMap().also { it[key] = value }
}
else {
customModuleOptions = customModuleOptions.toMutableMap().also { it.remove(key) }
}
}
}
}
}
val diff = diff
if (diff != null) {
val entity = this.findModuleEntity(entityStorage.current)
if (entity != null) {
updateOptionInEntity(diff, entity)
}
}
else {
@Suppress("DEPRECATION")
if (getOptionValue(key) != value) {
WriteAction.runAndWait<RuntimeException> {
WorkspaceModel.getInstance(project).updateProjectModel("Set option in module entity") { builder ->
val entity = this.findModuleEntity(builder)
if (entity != null) {
updateOptionInEntity(builder, entity)
}
}
}
}
}
return
}
} | apache-2.0 | f1c5e3f76742504f4569a8638528de77 | 42.194595 | 141 | 0.725282 | 5.424304 | false | false | false | false |
Bluexin/mek-re | src/main/java/be/bluexin/mekre/crafting/MachineOps.kt | 1 | 1889 | package be.bluexin.mekre.crafting
import com.teamwizardry.librarianlib.common.util.saving.Savable
import com.teamwizardry.librarianlib.common.util.saving.SavableConstructorOrder
import com.teamwizardry.librarianlib.common.util.saving.Save
import net.minecraft.item.ItemStack
import java.util.*
/**
* Part of mek_re by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
@Savable
data class MachineRecipe
@SavableConstructorOrder("input", "output", "energyNet", "time") constructor(
@Save
val input: ArrayList<ItemStack>,
@Save
val output: ArrayList<ItemStack>,
/**
* Energy result from this operation.
* Can be positive (energy gain, aka generation) or negative (energy loss, aka consumption).
*/
@Save
val energyNet: Int,
/**
* Amount of ticks required for this operation.
*/
@Save
val time: Int
) // TODO: remove either energyNet or time? Kinda redundant. Instead, use machine-based consumption per tick.
@Savable
class Operation(@Save val recipe: MachineRecipe) {
@SavableConstructorOrder("currentProgress", "recipe")
@Deprecated(message = "Never to be called manually. Needed for auto save.")
constructor(currentProgress: Float, recipe: MachineRecipe) : this(recipe) {
this.currentProgress = currentProgress
}
@Save
private var currentProgress = 0.0f
private val energyPerDelta by lazy { recipe.energyNet / recipe.time.toFloat() }
fun tick(delta: Float): Int {
currentProgress += delta
return (energyPerDelta * delta - Math.max(0.0f, currentProgress - recipe.time)).toInt()
}
val done: Boolean
get() = currentProgress >= recipe.time
fun canProgress(energy: Int) = energy >= energyPerDelta
val progress: Float
get() = currentProgress / recipe.time
}
| gpl-3.0 | 172e9f1c69eadd0c7df35066b58dfdc0 | 28.984127 | 109 | 0.678137 | 4.244944 | false | false | false | false |
android/compose-samples | Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/theme/Typography.kt | 1 | 4968 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.jetsurvey.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.compose.jetsurvey.R
val MontserratFontFamily = FontFamily(
listOf(
Font(R.font.montserrat_regular),
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_semibold, FontWeight.SemiBold)
)
)
val Typography = Typography(
// Display Large - Montserrat 57/64 . -0.25px
displayLarge = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 57.sp,
lineHeight = 64.sp,
letterSpacing = (-0.25).sp,
),
// Display Medium - Montserrat 45/52 . 0px
displayMedium = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 45.sp,
lineHeight = 52.sp,
letterSpacing = 0.sp,
),
// Display Small - Montserrat 36/44 . 0px
displaySmall = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 36.sp,
lineHeight = 44.sp,
letterSpacing = 0.sp,
),
// Headline Large - Montserrat 32/40 . 0px
headlineLarge = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 32.sp,
lineHeight = 40.sp,
letterSpacing = 0.sp,
),
// Headline Medium - Montserrat 28/36 . 0px
headlineMedium = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 28.sp,
lineHeight = 36.sp,
letterSpacing = 0.sp,
),
// Headline Small - Montserrat 24/32 . 0px
headlineSmall = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.sp,
),
// Title Large - Montserrat 22/28 . 0px
titleLarge = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp,
),
// Title Medium - Montserrat 16/24 . 0.15px
titleMedium = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W500,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.15.sp,
),
// Title Small - Montserrat 14/20 . 0.1px
titleSmall = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W500,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp,
),
// Label Large - Montserrat 14/20 . 0.1px
labelLarge = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W500,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp,
),
// Label Medium - Montserrat 12/16 . 0.5px
labelMedium = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W500,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp,
),
// Label Small - Montserrat 11/16 . 0.5px
labelSmall = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W500,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp,
),
// Body Large - Montserrat 16/24 . 0.5px
bodyLarge = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp,
),
// Body Medium - Montserrat 14/20 . 0.25px
bodyMedium = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.25.sp,
),
// Body Small - Montserrat 12/16 . 0.4px
bodySmall = TextStyle(
fontFamily = MontserratFontFamily,
fontWeight = FontWeight.W400,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.4.sp,
),
)
| apache-2.0 | 786ffaac898cca38acc275b152d0dd36 | 28.39645 | 75 | 0.626409 | 4.003223 | false | false | false | false |
extendedmind/extendedmind | ui/android/app/src/main/java/org/extendedmind/android/ui/focus/Focus.kt | 1 | 1545 | package org.extendedmind.android.ui.focus
import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.extendedmind.android.ui.data.AppContainer
import org.extendedmind.android.ui.theme.ExtendedMindTheme
@Composable
fun Focus(
appContainer: AppContainer,
) {
Log.v("Focus", "called")
val focusViewModel: FocusViewModel = viewModel(
factory = FocusViewModel.provideFactory(appContainer.contentRepository)
)
val uiState by focusViewModel.uiState.collectAsState()
ExtendedMindTheme {
Column(modifier = Modifier.padding(horizontal = 15.dp)) {
Surface {
Text(
text = "Hub url: ${appContainer.contentRepository.getHubUrl()}",
fontSize = 25.sp,
)
}
Surface {
Text(
text = "Hub public key: ${appContainer.contentRepository.getHubPublicKey()}",
fontSize = 25.sp,
)
}
Surface {
Text(
text = "Version: ${uiState.version ?: "...loading..."}",
fontSize = 25.sp,
)
}
}
}
}
| agpl-3.0 | 7ecfb926909ba74bd3c55c887977c847 | 31.87234 | 97 | 0.614887 | 4.625749 | false | false | false | false |
alilotfi/VirusTotalClient | app/src/main/kotlin/ir/alilo/virustotalclient/features/applist/AppListInteractor.kt | 1 | 1668 | package ir.alilo.virustotalclient.features.applist
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import ir.alilo.virustotalclient.datasources.db.App
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.onComplete
import org.jetbrains.anko.uiThread
import javax.inject.Inject
interface AppListInteractor {
var listener: AppListListener
fun fetchApps(system: Boolean, requestCode: Int)
}
interface AppListListener {
fun onAppsRetrieved(apps: List<App>, requestCode: Int)
}
class AppListInteractorImpl @Inject constructor(val pm: PackageManager) : AppListInteractor {
override lateinit var listener: AppListListener
override fun fetchApps(system: Boolean, requestCode: Int) {
var flag = PackageManager.GET_META_DATA
if (system) {
flag = flag or PackageManager.MATCH_SYSTEM_ONLY
}
doAsync(exceptionHandler = Throwable::printStackTrace) {
val apps = pm.getInstalledApplications(flag)
.filter { isSystemApp(it) == system }
.map { toApp(it) }
.sortedBy { it.name?.toUpperCase() }
// TODO: Replace with case insensitive string comparison
onComplete { listener.onAppsRetrieved(apps, requestCode) }
}
}
private fun isSystemApp(appInfo: ApplicationInfo): Boolean = with(appInfo) {
flags and ApplicationInfo.FLAG_SYSTEM != 0
}
private fun toApp(appInfo: ApplicationInfo) = with(appInfo) {
App(packageName, pm.getApplicationLabel(appInfo).toString(), pm.getApplicationIcon(appInfo),
isSystemApp(appInfo))
}
} | apache-2.0 | 0c9cc191dc8b1f5111cf811897245c99 | 33.770833 | 100 | 0.694245 | 4.685393 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/string/lines.kt | 1 | 1321 | package io.kotest.matchers.string
import io.kotest.assertions.show.show
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.neverNullMatcher
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
fun <A : CharSequence> A?.shouldBeSingleLine(): A {
this should haveLineCount(1)
return this!!
}
fun <A : CharSequence> A?.shouldNotBeSingleLine(): A {
this shouldNot haveLineCount(1)
return this!!
}
infix fun <A : CharSequence> A?.shouldHaveLineCount(count: Int): A {
this should haveLineCount(count)
return this!!
}
infix fun <A : CharSequence> A?.shouldNotHaveLineCount(count: Int): A {
this shouldNot haveLineCount(count)
return this!!
}
/**
* Match on the number of newlines in a string.
*
* This will count both "\n" and "\r\n", and so is not dependant on the system line separator.
*/
fun haveLineCount(count: Int): Matcher<CharSequence?> = neverNullMatcher<CharSequence> { value ->
// plus one because we always have one more line than the new line character
val lines = if (value.isEmpty()) 0 else value.count { it == '\n' } + 1
MatcherResult(
lines == count,
{ "${value.show().value} should have $count lines but had $lines" },
{ "${value.show().value} should not have $count lines" }
)
}
| mit | 06c418c5612ef4e81634bb114f2b6d3a | 29.72093 | 97 | 0.706283 | 3.795977 | false | true | false | false |
sksamuel/ktest | kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/funspec/FunSpecNestedBeforeAfterEachTest.kt | 1 | 1223 | package com.sksamuel.kotest.specs.funspec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class FunSpecNestedBeforeAfterEachTest : FunSpec({
var a = ""
beforeSpec {
a shouldBe ""
a = "beforeSpec"
}
beforeEach {
a = "beforeEachRoot"
}
afterEach {
a = "afterEachRoot"
}
context("foo") {
a shouldBe "beforeSpec"
beforeEach {
a shouldBe "beforeEachRoot"
a = "beforeEachFoo"
}
afterEach {
a = "afterEachFoo"
}
test("b") {
a shouldBe "beforeEachFoo"
a = "testB"
}
test("e") {
a shouldBe "beforeEachFoo"
a = "testE"
}
context("bar") {
a shouldBe "afterEachFoo"
test("f") {
a shouldBe "beforeEachFoo"
a = "testF"
}
test("g") {
a shouldBe "beforeEachFoo"
a = "testG"
}
}
test("h") {
a shouldBe "beforeEachFoo"
a = "testH"
}
}
afterSpec {
a shouldBe "afterEachFoo"
}
})
| mit | 19bb1fe9d88e0066c17cb7c6750da340 | 17.253731 | 50 | 0.449714 | 4.367857 | false | true | false | false |
sksamuel/ktest | kotest-extensions/src/jvmMain/kotlin/io/kotest/extensions/system/NoSystemOutExtensions.kt | 1 | 2029 | package io.kotest.extensions.system
import io.kotest.core.listeners.TestListener
import io.kotest.core.spec.Spec
import java.io.ByteArrayOutputStream
import java.io.PrintStream
class SystemOutWriteException(val str: String?) : RuntimeException()
class SystemErrWriteException(val str: String?) : RuntimeException()
/**
* A [TestListener] that throws an error if anything is written to standard out.
*/
object NoSystemOutListener : TestListener {
private fun setup() {
val out = ByteArrayOutputStream()
System.setOut(object : PrintStream(out) {
private fun error(a: Any?): Nothing = throw SystemOutWriteException(a?.toString())
override fun print(b: Boolean) = error(b)
override fun print(c: Char) = error(c)
override fun print(i: Int) = error(i)
override fun print(l: Long) = error(l)
override fun print(s: String) = error(s)
override fun print(o: Any) = error(o)
override fun print(c: CharArray) = error(c)
override fun print(d: Double) = error(d)
override fun print(f: Float) = error(f)
})
}
override suspend fun beforeSpec(spec: Spec) = setup()
}
/**
* A [TestListener] that throws an error if anything is written to standard err.
*/
object NoSystemErrListener : TestListener {
private fun setup() {
val out = ByteArrayOutputStream()
System.setErr(object : PrintStream(out) {
private fun error(a: Any?): Nothing = throw SystemErrWriteException(a?.toString())
override fun print(b: Boolean) = error(b)
override fun print(c: Char) = error(c)
override fun print(i: Int) = error(i)
override fun print(l: Long) = error(l)
override fun print(s: String) = error(s)
override fun print(o: Any) = error(o)
override fun print(c: CharArray) = error(c)
override fun print(d: Double) = error(d)
override fun print(f: Float) = error(f)
})
}
override suspend fun beforeSpec(spec: Spec) = setup()
}
| mit | a19cde32c88c6c6a1dab5b71ff69d89e | 35.890909 | 91 | 0.653524 | 3.924565 | false | true | false | false |
mapzen/eraser-map | app/src/main/kotlin/com/mapzen/erasermap/presenter/MainPresenterImpl.kt | 1 | 31998 | package com.mapzen.erasermap.presenter
import android.location.Location
import android.util.Log
import com.mapzen.android.lost.api.LocationServices
import com.mapzen.android.lost.api.Status
import com.mapzen.erasermap.R
import com.mapzen.erasermap.controller.MainViewController
import com.mapzen.erasermap.model.AndroidAppSettings
import com.mapzen.erasermap.model.AppSettings
import com.mapzen.erasermap.model.ConfidenceHandler
import com.mapzen.erasermap.model.IntentQuery
import com.mapzen.erasermap.model.IntentQueryParser
import com.mapzen.erasermap.model.LocationClientManager
import com.mapzen.erasermap.model.LocationConverter
import com.mapzen.erasermap.model.LocationSettingsChecker
import com.mapzen.erasermap.model.MapzenLocation
import com.mapzen.erasermap.model.PermissionManager
import com.mapzen.erasermap.model.RouteManager
import com.mapzen.erasermap.model.event.LocationChangeEvent
import com.mapzen.erasermap.model.event.RouteCancelEvent
import com.mapzen.erasermap.model.event.RoutePreviewEvent
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.DEFAULT
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.ROUTE_DIRECTION_LIST
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.ROUTE_PREVIEW
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.ROUTE_PREVIEW_LIST
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.ROUTING
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.SEARCH
import com.mapzen.erasermap.presenter.ViewStateManager.ViewState.SEARCH_RESULTS
import com.mapzen.erasermap.view.RouteViewController
import com.mapzen.model.ValhallaLocation
import com.mapzen.pelias.PeliasLocationProvider
import com.mapzen.pelias.SimpleFeature
import com.mapzen.pelias.gson.Feature
import com.mapzen.pelias.gson.Geometry
import com.mapzen.pelias.gson.Properties
import com.mapzen.pelias.gson.Result
import com.mapzen.tangram.LngLat
import com.mapzen.valhalla.Route
import com.mapzen.valhalla.RouteCallback
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.ArrayList
open class MainPresenterImpl(val mapzenLocation: MapzenLocation, val bus: Bus,
val routeManager: RouteManager, val settings: AppSettings, val vsm: ViewStateManager,
val intentQueryParser: IntentQueryParser, val converter: LocationConverter,
val locationClientManager: LocationClientManager,
val locationSettingsChecker: LocationSettingsChecker, val permissionManager: PermissionManager,
val confidenceHandler: ConfidenceHandler) : MainPresenter, RouteCallback {
companion object {
private val TAG = MainPresenterImpl::class.java.simpleName
@JvmStatic val MAP_DATA_PROP_NAME = "name"
@JvmStatic val MAP_DATA_PROP_SEARCHINDEX = "searchIndex"
}
override var currentFeature: Feature? = null
override var routingEnabled: Boolean = false
override var mainViewController: MainViewController? = null
override var routeViewController: RouteViewController? = null
override var currentSearchTerm: String? = null
override var resultListVisible = false
override var reverseGeo = false
override var reverseGeoLngLat: LngLat?
get() = confidenceHandler.reverseGeoLngLat
set(value) {
confidenceHandler.reverseGeoLngLat = value
}
override var currentSearchIndex: Int = 0
override var mapPosition: LngLat? = null
override var mapZoom: Float? = null
override var poiTapPoint: FloatArray? = null
override var poiTapName: String? = null
override var poiCoordinates: LngLat? = null
override var willPauseImmediately: Boolean? = false
private var searchResults: Result? = null
private var destination: Feature? = null
private var initialized = false
private var restoreReverseGeoOnBack = false
/**
* We will migrate to Retrofit2 where we will have ability to cancel requests. Before then,
* we want to ignore all {@link RouteManager#fetchRoute} requests until we receive a
* result for existing request. Flag indicates we have already issued request for new route and
* are awaiting response
*/
private var waitingForRoute = false
init {
bus.register(this)
}
override fun onSearchResultsAvailable(result: Result?) {
this.currentSearchIndex = 0
mainViewController?.hideProgress()
if (currentSearchTerm != AndroidAppSettings.SHOW_DEBUG_SETTINGS_QUERY) {
if (result != null && featuresExist(result.features)) {
handleValidSearchResults(result)
} else {
handleEmptySearchResults()
}
}
}
private fun handleValidSearchResults(result: Result) {
vsm.viewState = SEARCH_RESULTS
reverseGeo = false
searchResults = result
prepareAndShowSearchResultsViews(result.features)
mainViewController?.deactivateFindMeTracking()
updateViewAllAction(result)
}
private fun handleEmptySearchResults() {
mainViewController?.toastify(R.string.no_results_found)
mainViewController?.focusSearchView()
}
private fun updateViewAllAction(result: Result?) {
val featureCount = result?.features?.size
if (featureCount != null && featureCount > 1) {
mainViewController?.showActionViewAll()
} else {
mainViewController?.hideActionViewAll()
}
}
override fun onReverseGeocodeResultsAvailable(searchResults: Result?) {
vsm.viewState = ViewStateManager.ViewState.SEARCH_RESULTS
var features = ArrayList<Feature>()
this.searchResults = searchResults
val feature: Feature?
if (searchResults?.features?.isEmpty() as Boolean) {
feature = currentFeature
} else {
feature = searchResults?.features?.get(0)
}
if (feature is Feature) {
features.add(feature)
}
showReverseGeocodeFeature(features)
searchResults?.features = features
}
override fun onPlaceSearchResultsAvailable(searchResults: Result?) {
vsm.viewState = ViewStateManager.ViewState.SEARCH_RESULTS
var features = ArrayList<Feature>()
this.searchResults = searchResults
if (searchResults?.features?.isEmpty() as Boolean) {
emptyPlaceSearch()
} else {
val current = searchResults?.features?.get(0)
if (current is Feature) {
features.add(current)
overridePlaceFeature(features[0])
}
searchResults?.features = features
mainViewController?.showPlaceSearchFeature(features)
}
}
override fun onMapPressed(x: Float, y: Float) {
val coords = mainViewController?.screenPositionToLngLat(x, y)
reverseGeoLngLat = coords
poiTapPoint = floatArrayOf(x, y)
}
override fun onMapDoubleTapped(x: Float, y: Float) {
val tappedPos = mainViewController?.screenPositionToLngLat(x, y)
val currentPos = mainViewController?.getMapPosition()
if (tappedPos != null && currentPos != null) {
val zoom = mainViewController?.getMapZoom() as Float + 1.0f
mainViewController?.setMapZoom(zoom, 500)
val lngLat = LngLat(0.5f * (tappedPos.longitude + currentPos.longitude),
0.5f * (tappedPos.latitude + currentPos.latitude))
mainViewController?.setMapPosition(lngLat, 500)
}
}
private fun emptyPlaceSearch() {
if (poiTapPoint != null) {
onReverseGeoRequested(poiTapPoint?.get(0), poiTapPoint?.get(1))
}
}
override fun onRestoreViewState() {
when (vsm.viewState) {
DEFAULT, SEARCH, SEARCH_RESULTS -> {}
ROUTE_PREVIEW -> onRestoreViewStateRoutePreview()
ROUTE_PREVIEW_LIST -> onRestoreViewStateRoutePreviewList()
ROUTING -> onRestoreViewStateRouting()
ROUTE_DIRECTION_LIST -> onRestoreViewStateRouteDirectionList()
}
}
private fun onRestoreViewStateRoutePreview() {
mainViewController?.showRoutePreviewView()
mainViewController?.showRoutePreviewDistanceTimeLayout()
generateRoutePreview(false)
mainViewController?.restoreRoutePreviewButtons()
}
private fun onRestoreViewStateRoutePreviewList() {
generateRoutePreview(false)
onClickViewList()
}
private fun onRestoreViewStateRouting() {
resumeRoutingMode()
}
private fun onRestoreViewStateRouteDirectionList() {
resumeRoutingMode()
routeViewController?.showRouteDirectionList()
}
override fun onRestoreOptionsMenu() {
when (vsm.viewState) {
DEFAULT, SEARCH -> {}
SEARCH_RESULTS -> onRestoreOptionsMenuStateSearchResults()
ROUTE_PREVIEW -> {
mainViewController?.hideActionBar()
mainViewController?.hideSettingsBtn()
}
ROUTE_PREVIEW_LIST, ROUTING, ROUTE_DIRECTION_LIST -> {
mainViewController?.hideSettingsBtn()
}
}
}
private fun onRestoreOptionsMenuStateSearchResults() {
mainViewController?.hideSettingsBtn()
mainViewController?.setOptionsMenuIconToList()
updateViewAllAction(searchResults)
if (resultListVisible && searchResults?.features != null) {
val features = searchResults?.features as List<Feature>
mainViewController?.onShowAllSearchResultsList(features)
}
}
override fun onRestoreMapState() {
when (vsm.viewState) {
DEFAULT, SEARCH -> {}
SEARCH_RESULTS -> onRestoreMapStateSearchResults()
ROUTE_PREVIEW, ROUTE_PREVIEW_LIST -> adjustLayoutAndRoute()
ROUTING, ROUTE_DIRECTION_LIST -> mainViewController?.resumeRoutingModeForMap()
}
}
private fun onRestoreMapStateSearchResults() {
if (searchResults?.features != null) {
if (!reverseGeo) {
prepareAndShowSearchResultsViews(searchResults?.features, currentSearchIndex)
} else {
showReverseGeocodeFeature(searchResults?.features)
centerOnCurrentFeature(searchResults?.features)
}
}
}
private fun showReverseGeocodeFeature(features: List<Feature>?) {
if (features == null) {
return
}
mainViewController?.hideSearchResults()
mainViewController?.layoutAttributionAboveSearchResults(features)
mainViewController?.layoutFindMeAboveSearchResults(features)
val lngLat: LngLat?
if (poiCoordinates != null) {
lngLat = poiCoordinates
overridePlaceFeature(features[0])
} else if (poiTapPoint != null) {
val x = poiTapPoint!![0].toFloat()
val y = poiTapPoint!![1].toFloat()
lngLat = mainViewController?.screenPositionToLngLat(x, y)
// Fallback for a failed Pelias Place Callback
overridePlaceFeature(features[0])
} else {
lngLat = reverseGeoLngLat
}
mainViewController?.showPlaceSearchFeature(features)
mainViewController?.hideReverseGeolocateResult()
mainViewController?.showReverseGeoResult(lngLat)
}
private fun overridePlaceFeature(feature: Feature) {
val geometry = Geometry()
val coordinates = ArrayList<Double>()
if (poiCoordinates != null) {
coordinates.add(poiCoordinates?.longitude as Double)
coordinates.add(poiCoordinates?.latitude as Double)
geometry.coordinates = coordinates
feature.geometry = geometry
} else if (poiTapPoint != null) {
val pointX = poiTapPoint?.get(0)?.toFloat()
val pointY = poiTapPoint?.get(1)?.toFloat()
if (pointX != null && pointY != null) {
val coords = mainViewController?.screenPositionToLngLat(pointX, pointY)
val lng = coords?.longitude
val lat = coords?.latitude
if (lng != null && lat!= null) {
coordinates.add(lng)
coordinates.add(lat)
geometry.coordinates = coordinates
feature.geometry = geometry
}
}
}
if (poiTapName != null) {
feature.properties.name = poiTapName
}
poiTapName = null
poiTapPoint = null
poiCoordinates = null
}
private fun adjustLayoutAndRoute() {
mainViewController?.layoutAttributionAboveOptions()
mainViewController?.layoutFindMeAboveOptions()
mainViewController?.route()
}
override fun onExpandSearchView() {
if (vsm.viewState != ViewStateManager.ViewState.SEARCH_RESULTS) {
vsm.viewState = ViewStateManager.ViewState.SEARCH
}
mainViewController?.hideSettingsBtn()
}
override fun onCollapseSearchView() {
if (vsm.viewState != ViewStateManager.ViewState.ROUTE_PREVIEW) {
vsm.viewState = ViewStateManager.ViewState.DEFAULT
}
mainViewController?.hideSearchResults()
mainViewController?.hideActionViewAll()
if (vsm.viewState != ViewStateManager.ViewState.ROUTE_PREVIEW) {
mainViewController?.clearQuery()
mainViewController?.showSettingsBtn()
}
}
override fun onQuerySubmit(query: String) {
mainViewController?.showProgress()
if (AndroidAppSettings.SHOW_DEBUG_SETTINGS_QUERY == query) {
mainViewController?.toggleShowDebugSettings()
}
}
override fun onSearchResultSelected(position: Int) {
currentSearchIndex = position
if (searchResults != null) {
addSearchResultsToMap(searchResults?.features, position)
centerOnCurrentFeature(searchResults?.features)
}
}
override fun onSearchResultTapped(position: Int) {
if (searchResults != null) {
addSearchResultsToMap(searchResults?.features, position)
centerOnFeature(searchResults?.features, position)
}
}
override fun onViewAllSearchResultsList() {
mainViewController?.toggleShowAllSearchResultsList(searchResults?.features)
}
private fun connectAndPostRunnable(run: () -> Unit) {
locationClientManager.connect()
locationClientManager.addRunnableToRunOnConnect(Runnable { run() })
}
@Subscribe fun onRoutePreviewEvent(event: RoutePreviewEvent) {
if (!locationClientManager.getClient().isConnected) {
connectAndPostRunnable { onRoutePreviewEvent(event) }
return
}
val locationStatusCode = locationSettingsChecker.getLocationStatusCode(mapzenLocation,
locationClientManager)
if (locationStatusCode == Status.RESOLUTION_REQUIRED) {
val locationStatus = locationSettingsChecker.getLocationStatus(mapzenLocation,
locationClientManager)
mainViewController?.handleLocationResolutionRequired(locationStatus)
return
}
vsm.viewState = ViewStateManager.ViewState.ROUTE_PREVIEW
if (reverseGeo) {
restoreReverseGeoOnBack = true
}
reverseGeo = false
destination = event.destination
mapPosition = mainViewController?.getMapPosition()
mapZoom = mainViewController?.getMapZoom()
mainViewController?.collapseSearchView()
mainViewController?.hideSearchResults()
mainViewController?.hideReverseGeolocateResult()
mainViewController?.deactivateFindMeTracking()
generateRoutePreview()
}
@Subscribe fun onRouteCancelEvent(event: RouteCancelEvent) {
mainViewController?.onBackPressed()
}
override fun updateLocation() {
if (!locationClientManager.getClient().isConnected) {
connectAndPostRunnable { updateLocation() }
return
}
val location = mapzenLocation.getLastLocation()
if (location != null) {
routeViewController?.onLocationChanged(location)
}
}
override fun onBackPressed() {
if (vsm.viewState == SEARCH || vsm.viewState == SEARCH_RESULTS) {
currentSearchTerm = null
}
when (vsm.viewState) {
DEFAULT -> onBackPressedStateDefault()
SEARCH -> onBackPressedStateSearch()
SEARCH_RESULTS -> onBackPressedStateSearchResults()
ROUTE_PREVIEW -> onBackPressedStateRoutePreview()
ROUTE_PREVIEW_LIST -> onBackPressedStateRoutePreviewList()
ROUTING -> onBackPressedStateRouting()
ROUTE_DIRECTION_LIST -> onBackPressedStateRouteDirectionList()
}
resultListVisible = false
}
private fun onBackPressedStateDefault() {
mainViewController?.shutDown()
}
private fun onBackPressedStateSearch() {
vsm.viewState = ViewStateManager.ViewState.DEFAULT
searchResults = null
mainViewController?.collapseSearchView()
}
private fun onBackPressedStateSearchResults() {
vsm.viewState = ViewStateManager.ViewState.DEFAULT
mainViewController?.collapseSearchView()
mainViewController?.hideReverseGeolocateResult()
mainViewController?.hideSearchResults()
}
private fun onBackPressedStateRoutePreview() {
vsm.viewState = ViewStateManager.ViewState.SEARCH_RESULTS
if (restoreReverseGeoOnBack) {
restoreReverseGeoOnBack = false
reverseGeo = true
}
mainViewController?.hideProgress()
mainViewController?.cancelRouteRequest()
mainViewController?.showActionBar()
routeManager.reverse = false
mainViewController?.hideRoutePreviewView()
mainViewController?.hideMapRoutePins()
val features = arrayListOf(currentFeature) as List<Feature>
mainViewController?.layoutAttributionAboveSearchResults(features)
mainViewController?.layoutFindMeAboveSearchResults(features)
mainViewController?.clearRoute()
if (searchResults != null) {
if (reverseGeo) {
showReverseGeocodeFeature(searchResults?.features)
if (mapPosition != null) {
mainViewController?.setMapPosition(mapPosition as LngLat, 0)
}
if (mapZoom != null) {
mainViewController?.setMapZoom(mapZoom as Float)
}
} else {
prepareAndShowSearchResultsViews(searchResults?.features, currentSearchIndex)
var numFeatures = 0
numFeatures = (searchResults?.features?.size as Int)
if (numFeatures > 1) {
mainViewController?.showActionViewAll()
}
}
}
}
private fun prepareAndShowSearchResultsViews(features: List<Feature>?) {
prepareAndShowSearchResultsViews(features, 0)
}
/**
* When search results are selected this method handles adjusting all the views on the screen
* needed to properly display results. It makes the search results view visible, adjusts the
* attribution & find me btn as well as adds the search result pins to the map.
*/
private fun prepareAndShowSearchResultsViews(features: List<Feature>?, activeIndex: Int) {
if (features == null) {
return
}
mainViewController?.hideReverseGeolocateResult()
mainViewController?.showSearchResultsView(features)
addSearchResultsToMap(features, activeIndex)
mainViewController?.layoutAttributionAboveSearchResults(features)
mainViewController?.layoutFindMeAboveSearchResults(features)
}
/**
* Handles updating the map for given search results. This method adjusts the map's pins,
* position, and zoom. It is called when search results are initially selected as well as when the
* search results pager is paged.
*/
private fun addSearchResultsToMap(features: List<Feature>?, activeIndex: Int) {
if (features == null || features.size == 0) {
return
}
mainViewController?.setCurrentSearchItem(activeIndex)
val feature = SimpleFeature.fromFeature(features[activeIndex])
mainViewController?.setMapPosition(LngLat(feature.lng(), feature.lat()), 1000)
mainViewController?.setMapZoom(MainPresenter.DEFAULT_ZOOM)
mainViewController?.clearSearchResults()
val points: ArrayList<LngLat> = ArrayList()
for (feature in features) {
val simpleFeature = SimpleFeature.fromFeature(feature)
val lngLat = LngLat(simpleFeature.lng(), simpleFeature.lat())
points.add(lngLat)
}
mainViewController?.drawSearchResults(points, activeIndex)
}
private fun onBackPressedStateRoutePreviewList() {
vsm.viewState = ViewStateManager.ViewState.ROUTE_PREVIEW
mainViewController?.hideDirectionsList()
}
private fun onBackPressedStateRouting() {
vsm.viewState = ViewStateManager.ViewState.ROUTE_PREVIEW
routingEnabled = false
mapzenLocation.stopLocationUpdates() //must call before calling mainViewController?.hideRoutingMode()
mainViewController?.hideRoutingMode()
mainViewController?.stopSpeaker()
val location = routeManager.origin
val feature = routeManager.destination
if (location is ValhallaLocation && feature is Feature) {
showRoutePreview(location, feature)
}
}
private fun onBackPressedStateRouteDirectionList() {
vsm.viewState = ViewStateManager.ViewState.ROUTING
routeViewController?.hideRouteDirectionList()
}
override fun onClickViewList() {
vsm.viewState = ViewStateManager.ViewState.ROUTE_PREVIEW_LIST
mainViewController?.showDirectionsList()
}
override fun onClickStartNavigation() {
if (!locationClientManager.getClient().isConnected) {
connectAndPostRunnable { onClickStartNavigation() }
return
}
mainViewController?.resetMute() //must call before generateRoutingMode()
generateRoutingMode(true)
vsm.viewState = ViewStateManager.ViewState.ROUTING
routeViewController?.hideResumeButton()
mapzenLocation.startLocationUpdates()
}
@Subscribe fun onLocationChangeEvent(event: LocationChangeEvent) {
if (routingEnabled) {
routeViewController?.onLocationChanged(event.location)
}
}
override fun onResume() {
if (!isRouting() && !isRoutingDirectionList() && !willPauseImmediately()) {
mainViewController?.checkPermissionAndEnableLocation()
}
}
private fun isRouting(): Boolean {
return vsm.viewState == ViewStateManager.ViewState.ROUTING
}
private fun willPauseImmediately(): Boolean {
val willPause = willPauseImmediately?.let { it } ?: return false
return willPause
}
private fun isRoutingDirectionList(): Boolean {
return vsm.viewState == ViewStateManager.ViewState.ROUTE_DIRECTION_LIST
}
override fun onMuteClick() {
mainViewController?.toggleMute()
}
override fun onCompassClick() {
mainViewController?.setMapRotation(0f)
}
override fun getPeliasLocationProvider(): PeliasLocationProvider {
return mapzenLocation
}
override fun onReroute(location: ValhallaLocation) {
if (waitingForRoute) {
return
}
waitingForRoute = true
mainViewController?.showProgress()
fetchNewRoute(location)
}
private fun fetchNewRoute(location: ValhallaLocation) {
routeManager.origin = location
routeManager.destination = destination
routeManager.reverse = false
if (location.hasBearing()) {
routeManager.bearing = location.bearing
} else {
routeManager.bearing = null
}
routeManager.fetchRoute(this)
}
override fun failure(statusCode: Int) {
mainViewController?.hideProgress()
Log.e(TAG, "Error fetching new route: " + statusCode)
waitingForRoute = false
}
override fun success(route: Route) {
handleRouteRetrieved(route)
generateRoutingMode(false)
waitingForRoute = false
}
private fun generateRoutePreview() {
generateRoutePreview(true)
}
private fun generateRoutePreview(updateMap: Boolean) {
if (!locationClientManager.getClient().isConnected) {
connectAndPostRunnable { generateRoutePreview(updateMap) }
return
}
val location = mapzenLocation.getLastLocation()
val feature = destination
if (location is Location && feature is Feature) {
val mapzenLocation = converter.mapzenLocation(location)
showRoutePreview(mapzenLocation, feature, updateMap)
}
}
private fun generateRoutingMode(isNew: Boolean) {
routingEnabled = true
val feature = destination
if (feature is Feature) {
mainViewController?.startRoutingMode(feature, isNew)
}
}
private fun resumeRoutingMode() {
routingEnabled = true
val feature = destination
if (feature is Feature) {
mainViewController?.resumeRoutingMode(feature)
}
}
override fun onExitNavigation(visible: Boolean) {
vsm.viewState = ViewStateManager.ViewState.DEFAULT
routingEnabled = false
routeManager.reverse = false
val currentLocation = mapzenLocation.getLastLocation()
mapzenLocation.stopLocationUpdates()
mainViewController?.stopSpeaker()
if (visible) {
checkPermissionAndEnableLocation()
}
mainViewController?.stopVoiceNavigationController()
mainViewController?.clearRoute()
mainViewController?.hideRouteIcon()
mainViewController?.hideRouteModeView()
mainViewController?.showActionBar()
mainViewController?.hideRoutePreviewView()
mainViewController?.resetMapPanResponder()
mainViewController?.setDefaultCamera()
mainViewController?.layoutFindMeAlignBottom()
mainViewController?.setMapTilt(0f)
if (currentLocation is Location) {
mainViewController?.centerMapOnLocation(LngLat(currentLocation.longitude,
currentLocation.latitude), MainPresenter.DEFAULT_ZOOM)
}
}
override fun onMapRotateEvent(): Boolean {
mainViewController?.showCompass()
mainViewController?.rotateCompass()
return false
}
override fun onReverseGeoRequested(screenX: Float?, screenY: Float?): Boolean {
if (screenX != null && screenY != null) {
if (reverseGeo || vsm.viewState == ViewStateManager.ViewState.DEFAULT) {
mainViewController?.reverseGeolocate(screenX, screenY)
reverseGeo = true
return true
}
}
return false
}
override fun onPlaceSearchRequested(gid: String): Boolean {
if (reverseGeo || vsm.viewState == ViewStateManager.ViewState.DEFAULT) {
drawTappedPoiPin()
mainViewController?.placeSearch(gid)
reverseGeo = true
return true
}
return false
}
private fun drawTappedPoiPin() {
mainViewController?.hideSearchResultsView()
mainViewController?.layoutAttributionAlignBottom()
mainViewController?.layoutFindMeAlignBottom()
var lngLat: LngLat? = null
val pointX = poiTapPoint?.get(0)?.toFloat()
val pointY = poiTapPoint?.get(1)?.toFloat()
if (pointX != null && pointY != null) {
lngLat = mainViewController?.screenPositionToLngLat(pointX, pointY)
}
mainViewController?.hideReverseGeolocateResult()
mainViewController?.showReverseGeoResult(lngLat)
}
override fun configureMapzenMap() {
if (!locationClientManager.getClient().isConnected) {
connectAndPostRunnable { configureMapzenMap() }
return
}
val currentLocation = mapzenLocation.getLastLocation()
if (currentLocation is Location) {
if (!initialized) {
// Show location puck and center map
mainViewController?.centerMapOnLocation(LngLat(currentLocation.longitude,
currentLocation.latitude), MainPresenter.DEFAULT_ZOOM)
initialized = true
}
}
}
override fun onIntentQueryReceived(query: String?) {
if (query != null && !query.isEmpty()) {
val result = intentQueryParser.parse(query)
if (result != null) {
updateQueryMapPosition(result)
updateQuerySearchTerm(result)
}
}
}
private fun updateQueryMapPosition(result: IntentQuery) {
val focusPoint = result.focusPoint
if (focusPoint.latitude != 0.0 && focusPoint.longitude != 0.0) {
mainViewController?.centerMapOnLocation(focusPoint, MainPresenter.DEFAULT_ZOOM)
}
}
private fun updateQuerySearchTerm(result: IntentQuery) {
val queryString = result.queryString
currentSearchTerm = queryString
mainViewController?.hideSettingsBtn()
mainViewController?.hideSearchResults()
mainViewController?.executeSearch(queryString)
}
override fun onRouteRequest(callback: RouteCallback) {
mainViewController?.showProgress()
mainViewController?.cancelRouteRequest()
routeManager.fetchRoute(callback)
}
override fun onRouteSuccess(route: Route) {
handleRouteRetrieved(route)
mainViewController?.setRoutePreviewViewRoute(route)
mainViewController?.hideActionBar()
mainViewController?.showRoutePreviewView()
mainViewController?.showRoutePreviewDistanceTimeLayout()
mainViewController?.showRoutePinsOnMap(route.getGeometry().toTypedArray())
mainViewController?.updateRoutePreviewStartNavigation()
}
private fun showRoutePreview(location: ValhallaLocation, feature: Feature) {
showRoutePreview(location, feature, true)
}
private fun showRoutePreview(location: ValhallaLocation, feature: Feature,
updateMap: Boolean) {
if (updateMap) {
mainViewController?.layoutAttributionAboveOptions()
mainViewController?.layoutFindMeAboveOptions()
}
routeManager.origin = location
if (location.hasBearing()) {
routeManager.bearing = location.bearing
} else {
routeManager.bearing = null
}
if (!confidenceHandler.useRawLatLng(feature.properties.confidence)) {
mainViewController?.showRoutePreviewDestination(SimpleFeature.fromFeature(feature))
routeManager.destination = feature
} else {
val rawFeature = generateRawFeature()
mainViewController?.showRoutePreviewDestination(SimpleFeature.fromFeature(rawFeature))
routeManager.destination = rawFeature
}
if (updateMap) {
mainViewController?.route()
}
}
override fun generateRawFeature(): Feature {
val rawFeature: Feature = Feature()
rawFeature.geometry = Geometry()
val coords = ArrayList<Double>()
coords.add(reverseGeoLngLat?.longitude as Double)
coords.add(reverseGeoLngLat?.latitude as Double)
rawFeature.geometry.coordinates = coords
val properties = Properties()
val formatter = DecimalFormat(".####")
formatter.roundingMode = RoundingMode.HALF_UP
val lng = formatter.format(reverseGeoLngLat?.longitude as Double)
val lat = formatter.format(reverseGeoLngLat?.latitude as Double)
properties.name = "$lng, $lat"
rawFeature.properties = properties
return rawFeature
}
override fun onFeaturePicked(properties: Map<String, String>?, coords: LngLat?, x: Float,
y: Float) {
// Reassign tapPoint to center of the feature tapped
// Also used in placing the pin
poiCoordinates = coords
// if the labelPickResult is null, x & y will be 0,0 so ignore setting poiTapPoint
if (properties != null) {
poiTapPoint = floatArrayOf(x, y)
if (properties?.contains(MAP_DATA_PROP_NAME)) {
poiTapName = properties?.get(MAP_DATA_PROP_NAME)
}
}
if (properties != null && properties?.contains(MAP_DATA_PROP_SEARCHINDEX)) {
val searchIndex = properties[MAP_DATA_PROP_SEARCHINDEX]!!.toInt()
onSearchResultTapped(searchIndex)
} else {
onReverseGeoRequested(poiTapPoint?.get(0), poiTapPoint?.get(1))
}
}
override fun checkPermissionAndEnableLocation() {
if (permissionManager.granted && !routingEnabled) {
mainViewController?.setMyLocationEnabled(true)
if (!locationClientManager.getClient().isConnected) {
locationClientManager.connect()
locationClientManager.addRunnableToRunOnConnect(Runnable { initMockMode() })
} else {
initMockMode()
}
}
}
override fun onClickFindMe() {
mainViewController?.setMapTilt(0f)
}
private fun initMockMode() {
if (settings.isMockLocationEnabled) {
val client = locationClientManager.getClient()
LocationServices.FusedLocationApi?.setMockMode(client, true)
LocationServices.FusedLocationApi?.setMockLocation(client, settings.mockLocation)
}
}
private fun handleRouteRetrieved(route: Route) {
routeManager.route = route
mainViewController?.drawRoute(route)
mainViewController?.hideProgress()
}
private fun featuresExist(features: List<Feature>?): Boolean {
return features != null && features.isNotEmpty()
}
private fun centerOnCurrentFeature(features: List<Feature>?) {
if (!featuresExist(features)) {
return
}
val position = mainViewController?.getCurrentSearchPosition()
centerOnFeature(features, position as Int)
}
private fun centerOnFeature(features: List<Feature>?, position: Int) {
if (!featuresExist(features)) {
return
}
mainViewController?.setCurrentSearchItem(position)
val feature = SimpleFeature.fromFeature(features!![position])
mainViewController?.setMapPosition(LngLat(feature.lng(), feature.lat()), 1000)
mainViewController?.setMapZoom(MainPresenter.DEFAULT_ZOOM)
}
}
| gpl-3.0 | 71b32df371a30c68c6bc6e41ae7a72a1 | 32.932131 | 105 | 0.729546 | 4.598735 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/test/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/MSTTest.kt | 1 | 3324 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.uuddlrlrba.ktalgs.graphs.undirected.weighted
import org.junit.Assert
import org.junit.Test
import java.net.URL
import java.util.*
abstract class MSTTest(val strategy: (UWGraph) -> (MST)) {
@Test
fun test1() {
val graph = UWGraph(4)
graph.addEdge(0, 1, 4.0)
graph.addEdge(1, 2, 1.0)
graph.addEdge(2, 3, 2.0)
graph.addEdge(0, 3, 5.0)
graph.addEdge(0, 1, 4.0)
graph.addEdge(1, 3, 3.0)
val mst = strategy(graph)
Assert.assertEquals(7.0, mst.weight(), 1e-12)
}
@Test
fun test2() {
val graph = UWGraph(5)
graph.addEdge(0, 1, 4.0)
graph.addEdge(1, 2, 1.0)
graph.addEdge(2, 3, 7.0)
graph.addEdge(3, 4, 6.0)
graph.addEdge(0, 4, 2.0)
graph.addEdge(1, 4, 3.0)
graph.addEdge(1, 3, 5.0)
val mst = strategy(graph)
Assert.assertEquals(11.0, mst.weight(), 1e-12)
}
@Test
fun test3() {
val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/tinyEWG.txt"))
val mst = strategy(graph)
Assert.assertEquals(1.81, mst.weight(), 1e-12)
}
@Test
fun test4() {
val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/mediumEWG.txt"))
val mst = strategy(graph)
Assert.assertEquals(10.46351, mst.weight(), 1e-12)
}
@Test
fun test5() {
val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/1000EWG.txt"))
val mst = strategy(graph)
Assert.assertEquals(20.77320, mst.weight(), 1e-12)
}
@Test
fun test6() {
val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/10000EWG.txt"))
val mst = strategy(graph)
Assert.assertEquals(65.24072, mst.weight(), 1e-12)
}
fun readFromURL(url: URL): UWGraph {
Scanner(url.openStream()).useLocale(Locale.US).use { scanner ->
val graph = UWGraph(scanner.nextInt())
for (i in 0 until scanner.nextInt()) {
graph.addEdge(scanner.nextInt(), scanner.nextInt(), scanner.nextDouble())
}
scanner.close()
return graph
}
}
}
| mit | 1a59db5532b4d7e974c10b723489f4cb | 33.625 | 90 | 0.635981 | 3.498947 | false | true | false | false |
tingtingths/jukebot | app/src/main/java/com/jukebot/jukebot/telegram/Bot.kt | 1 | 9937 | package com.jukebot.jukebot.telegram
import android.app.Notification
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.os.IBinder
import com.google.gson.Gson
import com.jukebot.jukebot.Constant
import com.jukebot.jukebot.Jukebot
import com.jukebot.jukebot.R
import com.jukebot.jukebot.logging.Logger
import com.jukebot.jukebot.manager.MessageManager
import com.jukebot.jukebot.manager.PlaylistManager
import com.jukebot.jukebot.message.AuthFilter
import com.jukebot.jukebot.message.CommandUpdateHandler
import com.jukebot.jukebot.message.UpdateHandler
import com.jukebot.jukebot.message.UrlUpdateHandler
import com.jukebot.jukebot.storage.VolatileStorage
import com.jukebot.jukebot.util.Util
import com.pengrad.telegrambot.TelegramBot
import com.pengrad.telegrambot.UpdatesListener
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.model.Update
import com.pengrad.telegrambot.request.BaseRequest
import com.pengrad.telegrambot.request.SendMessage
import com.pengrad.telegrambot.response.BaseResponse
import java.lang.RuntimeException
import java.util.*
import java.util.concurrent.Executors
import kotlin.collections.ArrayList
/**
* Created by Ting.
*/
class Bot : Service() {
private lateinit var _this: Bot
private var id: Int = -1
private lateinit var bot: TelegramBot
private lateinit var token: String
private lateinit var updateListener: UpdatesListener
private var updateFilter: ArrayList<UpdateHandler> = ArrayList()
private var updateHandlers: ArrayList<UpdateHandler> = ArrayList()
private val executor = Executors.newFixedThreadPool(4)
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
_this = this
addFilter(AuthFilter())
addHandler(CommandUpdateHandler())
addHandler(UrlUpdateHandler())
MessageManager.onEnqueue {
val msg = MessageManager.dequeue()
if (msg != null)
say(msg)
}
PlaylistManager.onEnqueue { track ->
say(Pair(
SendMessage(track.message.chat().id(), "+ ${track.title}")
.replyToMessageId(track.message.messageId())
, null)
)
}
PlaylistManager.onPlay { track ->
val chatId: Long? = VolatileStorage.get(Constant.KEY_VERIFIED_CHAT_ID) as Long?
if (chatId != null) {
say(Pair(SendMessage(chatId, Util.buildNowPlaying(track)), null))
}
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.notify(id, buildMediaNoti(track.title ?: ""))
}
PlaylistManager.onFinish { track ->
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.notify(id, buildNoti("Howdy human~"))
}
// foreground service
id = Random().nextInt()
startForeground(id, buildNoti("Howdy human~"))
}
private fun buildNoti(msg: String): Notification
= Notification.Builder(Jukebot.ctx)
.setSmallIcon(R.mipmap.ic_noti)
.setWhen(System.currentTimeMillis())
.setContentText(msg)
.build()
private fun buildMediaNoti(title: String): Notification
= Notification.Builder(Jukebot.ctx)
.setSmallIcon(R.mipmap.ic_noti)
.setContentTitle("Now Playing")
.setContentText(title)
.setStyle(Notification.MediaStyle())
.build()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.getStringExtra("token") != null) {
token = intent.getStringExtra("token")
Logger.log(this.javaClass.simpleName, "token=$token")
bot = TelegramBot(token)
bot.setUpdatesListener(object : UpdatesListener {
override fun process(updates: MutableList<Update>?): Int {
if (updates != null)
HandlerTask().execute(Pair(Pair(updateFilter, updateHandlers), updates))
return UpdatesListener.CONFIRMED_UPDATES_ALL
}
})
} else {
Logger.log(this.javaClass.simpleName, "no token")
}
return START_STICKY
}
override fun onDestroy() {
PlaylistManager.releasePlayer()
super.onDestroy()
bot.removeGetUpdatesListener()
}
fun addFilter(filter: UpdateHandler) {
updateFilter.add(filter)
Logger.log(this.javaClass.simpleName, "addHandler(${filter.javaClass.simpleName})")
}
fun addHandler(handler: UpdateHandler) {
// register new operator
updateHandlers.add(handler)
Logger.log(this.javaClass.simpleName, "addHandler(${handler.javaClass.simpleName})")
}
fun removeHandler(handler: UpdateHandler) =
updateHandlers
.filter { it::class == handler::class }
.forEach { updateHandlers.remove(it) }
fun getChained(): List<UpdateHandler> = updateHandlers
fun say(msg: Pair<BaseRequest<*, *>, ((BaseResponse?) -> Unit)?>) {
if (msg.second != null)
RequestResponseExecuteTask().execute(Pair(msg.second!!, msg.first))
else
RequestExecuteTask().execute(msg.first)
}
inner class RequestExecuteTask : AsyncTask<BaseRequest<*, *>, Unit, Unit>() {
override fun doInBackground(vararg params: BaseRequest<*, *>?) {
for (req in params) {
var attempt = 0
while (attempt < 5) {
try {
bot.execute(req)
break
} catch (e: RuntimeException) {
attempt += 1
if (attempt < 5) {
Logger.log(this.javaClass.name, "Retry telegram execute, req=${req.toString()}")
Thread.sleep(1000)
}
}
}
}
}
}
inner class RequestResponseExecuteTask : AsyncTask<
Pair<(BaseResponse?) -> Unit, BaseRequest<*, *>>,
Unit,
List<Pair<(BaseResponse?) -> Unit, BaseResponse>>
>() {
override fun doInBackground(vararg params: Pair<(BaseResponse?) -> Unit, BaseRequest<*, *>>): List<Pair<(BaseResponse?) -> Unit, BaseResponse>> {
val results: ArrayList<Pair<(BaseResponse?) -> Unit, BaseResponse>> = ArrayList()
for ((callback, req) in params)
results.add(Pair(callback, bot.execute(req)))
return results
}
override fun onPostExecute(results: List<Pair<(BaseResponse?) -> Unit, BaseResponse>>) {
super.onPostExecute(results)
for ((callback, resp) in results) {
Logger.log(this.javaClass.simpleName, "resp=$resp")
callback(resp)
}
}
}
inner class HandlerTask : AsyncTask<Pair<Pair<List<UpdateHandler>, List<UpdateHandler>>, MutableList<Update>>, Unit, Unit>() {
override fun doInBackground(vararg args: Pair<Pair<List<UpdateHandler>, List<UpdateHandler>>, MutableList<Update>>) {
for (pair in args) {
val updateFilters: List<UpdateHandler> = pair.first.first
val updateHandlers: List<UpdateHandler> = pair.first.second
val updates: MutableList<Update> = pair.second
for (update in updates) {
Logger.log(this.javaClass.simpleName, "recv=${Gson().toJson(update)}")
// filters
var pass: Boolean = true
for (filter in updateFilters) {
if (filter.responsible(update) != true) {
Logger.log(this.javaClass.simpleName, "Filter failed...")
pass = false
break
}
}
// invoke callback when someone is expecting to be notified upon the message reply
val replyMsgId = update.message()?.replyToMessage()?.messageId()
if (replyMsgId != null) {
val respCallback = MessageManager.unregisterReplyCallback(update.message().chat().id(), replyMsgId)
if (respCallback != null)
respCallback(update.message())
}
if (pass) {
for (handler in updateHandlers) {
val result: Any? = handler.responsible(update)
if (result != null) {
Logger.log(this.javaClass.simpleName
, "${handler::javaClass.get().simpleName}.handle(${Gson().toJson(result)})")
val task = UpdateHandlerHandlerTask()
task.executeOnExecutor(executor, HandlerTaskParam(handler, Pair(update.message(), result)))
break
}
}
}
}
}
}
}
inner class UpdateHandlerHandlerTask : AsyncTask<HandlerTaskParam, Unit, Unit>() {
override fun doInBackground(vararg params: HandlerTaskParam?) {
if (params != null) {
for (param in params)
param?.updateHandler?.handle(param.handlerParam)
}
}
}
inner class HandlerTaskParam(val updateHandler: UpdateHandler, val handlerParam: Pair<Message, Any>)
}
| mit | 3e5b53762752beab5fbb2462d9b08faa | 36.78327 | 153 | 0.579752 | 5.041603 | false | false | false | false |
jayrave/falkon | sample-android/src/main/kotlin/com/jayrave/falkon/sample_android/tables/MessagesTable.kt | 1 | 2843 | package com.jayrave.falkon.sample_android.tables
import com.jayrave.falkon.dao.Dao
import com.jayrave.falkon.dao.DaoImpl
import com.jayrave.falkon.engine.Type
import com.jayrave.falkon.mapper.*
import com.jayrave.falkon.mapper.lib.SimpleIdExtractFromHelper
import com.jayrave.falkon.sample_android.models.Message
import com.jayrave.falkon.sample_android.SqlBuilders
import java.text.SimpleDateFormat
import java.util.*
/**
* [Table]s inform Falkon about how a model maps to a table. [BaseEnhancedTable] provides
* a lot of defaults & is a good class to extend for you table mappings
*
* This class explains some of the features. For more, check out [UsersTable]
*/
class MessagesTable(
configuration: TableConfiguration, sqlBuilders: SqlBuilders, usersTable: UsersTable) :
BaseEnhancedTable<Message, UUID, Dao<Message, UUID>>(
"messages", configuration, sqlBuilders.createTableSqlBuilder) {
val id = col(Message::id, isId = true)
val content = col(Message::content)
val sentAt = col(Message::sentAt)
/**
* If special handling is required for just one field, a custom converter can be
* directly assigned to this column
*/
val receivedAt = col(Message::receivedAt, converter = StringDateConverter())
/**
* Foreign references can be established using [foreignCol]
*/
val fromUserId = foreignCol(Message::fromUserId, foreignColumn = usersTable.id)
val toUserId = foreignCol(Message::toUserId, foreignColumn = usersTable.id)
override val dao: Dao<Message, UUID> = DaoImpl(
this, sqlBuilders.insertSqlBuilder, sqlBuilders.updateSqlBuilder,
sqlBuilders.deleteSqlBuilder, sqlBuilders.insertOrReplaceSqlBuilder,
sqlBuilders.querySqlBuilder
)
private val extractFromHelper = SimpleIdExtractFromHelper(id)
override fun <C> extractFrom(id: UUID, column: Column<Message, C>): C {
return extractFromHelper.extractFrom(id, column)
}
override fun create(value: Value<Message>): Message {
return Message(
value of id, value of content, value of sentAt, value of receivedAt,
value of fromUserId, value of toUserId
)
}
companion object {
/**
* To stringify [Date] & save, restore from the database
*/
private class StringDateConverter : Converter<Date> {
override val dbType: Type = Type.STRING
private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
override fun from(dataProducer: DataProducer): Date {
return dateFormat.parse(dataProducer.getString())
}
override fun to(value: Date, dataConsumer: DataConsumer) {
dataConsumer.put(dateFormat.format(value))
}
}
}
} | apache-2.0 | 54c7ba4ed38f58df37608eefb746f2bd | 34.55 | 94 | 0.683433 | 4.407752 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/search/SearchBoxView.kt | 1 | 2835 | package io.github.manamiproject.manami.gui.search
import impl.org.controlsfx.autocompletion.SuggestionProvider
import io.github.manamiproject.manami.gui.events.AddAnimeListEntryGuiEvent
import io.github.manamiproject.manami.gui.events.AddIgnoreListEntryGuiEvent
import io.github.manamiproject.manami.gui.events.AddWatchListEntryGuiEvent
import io.github.manamiproject.manami.gui.ManamiAccess
import io.github.manamiproject.manami.gui.search.file.ShowFileSearchTabRequest
import io.github.manamiproject.modb.core.extensions.EMPTY
import io.github.manamiproject.modb.core.models.Title
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Pos.CENTER_RIGHT
import tornadofx.*
import tornadofx.controlsfx.bindAutoCompletion
class SearchBoxView: View() {
private val controller: SearchBoxController by inject()
private val searchStringProperty = SimpleStringProperty()
private val suggestedEntries = mutableSetOf<String>()
private val autoCompleteProvider: SuggestionProvider<String> = SuggestionProvider.create(emptyList())
init {
subscribe<AddAnimeListEntryGuiEvent> { event ->
addTitlesToSuggestions(event.entries.map { it.title })
}
subscribe<AddWatchListEntryGuiEvent> { event ->
addTitlesToSuggestions(event.entries.map { it.title })
}
subscribe<AddIgnoreListEntryGuiEvent> { event ->
addTitlesToSuggestions(event.entries.map { it.title })
}
subscribe<ClearAutoCompleteSuggestionsGuiEvent> {
autoCompleteProvider.clearSuggestions()
suggestedEntries.clear()
}
}
override val root = hbox {
alignment = CENTER_RIGHT
spacing = 5.0
textfield {
promptText = "Title"
textProperty().bindBidirectional(searchStringProperty)
bindAutoCompletion(autoCompleteProvider)
minWidth = 250.0
}
button("Search") {
isDefaultButton = true
isDisable = true
searchStringProperty.onChange { e -> isDisable = e?.isBlank() ?: true }
action {
controller.search(searchStringProperty.get())
searchStringProperty.set(EMPTY)
}
}
}
private fun addTitlesToSuggestions(titles: Collection<Title>) {
val suggestionsToAdd = titles.map { it }.distinct().filterNot { suggestedEntries.contains(it) }
autoCompleteProvider.addPossibleSuggestions(suggestionsToAdd)
suggestedEntries.addAll(suggestionsToAdd)
}
}
class SearchBoxController: Controller() {
private val manamiAccess: ManamiAccess by inject()
fun search(searchString: String) {
runAsync {
manamiAccess.findInLists(searchString)
}
fire(ShowFileSearchTabRequest)
}
} | agpl-3.0 | efaa5898baf4520dacbcd3ac4d4a45f6 | 35.831169 | 105 | 0.702293 | 4.879518 | false | false | false | false |
shchurov/gitter-kotlin-client | app/src/main/kotlin/com/github/shchurov/gitterclient/data/network/model/MessageResponse.kt | 1 | 613 | package com.github.shchurov.gitterclient.data.network.model
import com.google.gson.annotations.SerializedName
class MessageResponse {
constructor()
constructor(id: String, text: String, timeIso: String, user: UserResponse, unread: Boolean) {
this.id = id
this.text = text
this.timeIso = timeIso
this.user = user
this.unread = unread
}
lateinit var id: String
lateinit var text: String
@SerializedName("sent")
lateinit var timeIso: String
@SerializedName("fromUser")
lateinit var user: UserResponse
var unread: Boolean = false
} | apache-2.0 | 7fc1b6bd1f44541d58948650f111c8ab | 23.56 | 97 | 0.67863 | 4.286713 | false | false | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/Tokens.kt | 1 | 4830 | package org.luxons.sevenwonders.ui.components.game
import kotlinx.css.*
import kotlinx.html.DIV
import kotlinx.html.IMG
import kotlinx.html.title
import org.luxons.sevenwonders.model.resources.ResourceType
import org.luxons.sevenwonders.ui.components.GlobalStyles
import react.RBuilder
import styled.*
private fun getResourceTokenName(resourceType: ResourceType) = "resources/${resourceType.toString().toLowerCase()}"
private fun getTokenImagePath(tokenName: String) = "/images/tokens/$tokenName.png"
enum class TokenCountPosition {
LEFT,
RIGHT,
OVER,
}
fun RBuilder.goldIndicator(
amount: Int,
amountPosition: TokenCountPosition = TokenCountPosition.OVER,
imgSize: LinearDimension = 3.rem,
customCountStyle: CSSBuilder.() -> Unit = {},
block: StyledDOMBuilder<DIV>.() -> Unit = {},
) {
tokenWithCount(
tokenName = "coin",
title = "$amount gold coins",
imgSize = imgSize,
count = amount,
countPosition = amountPosition,
customCountStyle = customCountStyle,
block = block,
)
}
fun RBuilder.resourceWithCount(
resourceType: ResourceType,
count: Int,
title: String = resourceType.toString(),
imgSize: LinearDimension? = null,
countPosition: TokenCountPosition = TokenCountPosition.RIGHT,
brightText: Boolean = false,
customCountStyle: CSSBuilder.() -> Unit = {},
block: StyledDOMBuilder<DIV>.() -> Unit = {},
) {
tokenWithCount(
tokenName = getResourceTokenName(resourceType),
count = count,
title = title,
imgSize = imgSize,
countPosition = countPosition,
brightText = brightText,
customCountStyle = customCountStyle,
block = block
)
}
fun RBuilder.resourceImage(
resourceType: ResourceType,
title: String = resourceType.toString(),
size: LinearDimension?,
block: StyledDOMBuilder<IMG>.() -> Unit = {},
) {
tokenImage(getResourceTokenName(resourceType), title, size, block)
}
fun RBuilder.tokenWithCount(
tokenName: String,
count: Int,
title: String = tokenName,
imgSize: LinearDimension? = null,
countPosition: TokenCountPosition = TokenCountPosition.RIGHT,
brightText: Boolean = false,
customCountStyle: CSSBuilder.() -> Unit = {},
block: StyledDOMBuilder<DIV>.() -> Unit = {},
) {
styledDiv {
block()
val tokenCountSize = if (imgSize != null) imgSize * 0.6 else 1.5.rem
when (countPosition) {
TokenCountPosition.RIGHT -> {
tokenImage(tokenName, title = title, size = imgSize)
styledSpan {
css {
tokenCountStyle(tokenCountSize, brightText, customCountStyle)
marginLeft = 0.2.rem
}
+"× $count"
}
}
TokenCountPosition.LEFT -> {
styledSpan {
css {
tokenCountStyle(tokenCountSize, brightText, customCountStyle)
marginRight = 0.2.rem
}
+"$count ×"
}
tokenImage(tokenName, title = title, size = imgSize)
}
TokenCountPosition.OVER -> {
styledDiv {
css {
position = Position.relative
// if container becomes large, this one stays small so that children stay on top of each other
width = LinearDimension.fitContent
}
tokenImage(tokenName, title = title, size = imgSize)
styledSpan {
css {
+GlobalStyles.centerInParent
tokenCountStyle(tokenCountSize, brightText, customCountStyle)
}
+"$count"
}
}
}
}
}
}
fun RBuilder.tokenImage(
tokenName: String,
title: String = tokenName,
size: LinearDimension?,
block: StyledDOMBuilder<IMG>.() -> Unit = {},
) {
styledImg(src = getTokenImagePath(tokenName)) {
css {
height = size ?: 100.pct
if (size != null) {
width = size
}
verticalAlign = VerticalAlign.middle
}
attrs {
this.title = title
this.alt = tokenName
}
block()
}
}
private fun CSSBuilder.tokenCountStyle(
size: LinearDimension,
brightText: Boolean,
customStyle: CSSBuilder.() -> Unit = {},
) {
fontFamily = "Acme"
fontSize = size
verticalAlign = VerticalAlign.middle
color = if (brightText) Color.white else Color.black
customStyle()
}
| mit | ee2e6c6e86f0a2dacfee5a9cdb078b22 | 29.556962 | 118 | 0.568766 | 4.678295 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/metrics/JFRExports.kt | 1 | 16609 | package net.perfectdreams.loritta.cinnamon.discord.utils.metrics
import io.prometheus.client.Collector
import io.prometheus.client.Counter
import io.prometheus.client.Gauge
import io.prometheus.client.Histogram
import jdk.jfr.EventSettings
import jdk.jfr.consumer.RecordedEvent
import jdk.jfr.consumer.RecordedObject
import jdk.jfr.consumer.RecordingStream
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.time.Instant
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Consumer
/**
* Exports values from Java Flight Recorder (JFR) to Prometheus
*
* From Mantaro: https://github.com/Mantaro/MantaroBot/blob/master/src/main/java/net/kodehawa/mantarobot/utils/exporters/JFRExports.java
*/
object JFRExports {
private val log: Logger = LoggerFactory.getLogger(JFRExports::class.java)
private val REGISTERED: AtomicBoolean = AtomicBoolean(false)
private const val NANOSECONDS_PER_SECOND = 1E9
//jdk.SafepointBegin, jdk.SafepointStateSynchronization, jdk.SafepointEnd
private val SAFEPOINTS: Histogram = Histogram.build()
.name("jvm_safepoint_pauses_seconds")
.help("Safepoint pauses by buckets")
.labelNames("type") // ttsp, operation
.buckets(0.005, 0.010, 0.025, 0.050, 0.100, 0.200, 0.400, 0.800, 1.600, 3.0, 5.0, 10.0)
.create()
private val SAFEPOINTS_TTSP: Histogram.Child = SAFEPOINTS.labels("ttsp")
private val SAFEPOINTS_OPERATION: Histogram.Child = SAFEPOINTS.labels("operation")
//jdk.GarbageCollection
private val GC_PAUSES: Histogram = Histogram.build()
.name("jvm_gc_pauses_seconds")
.help("Longest garbage collection pause per collection")
.labelNames("name", "cause")
.buckets(0.005, 0.010, 0.025, 0.050, 0.100, 0.200, 0.400, 0.800, 1.600, 3.0, 5.0, 10.0)
.create()
//jdk.GarbageCollection
private val GC_PAUSES_SUM: Histogram = Histogram.build()
.name("jvm_gc_sum_of_pauses_seconds")
.help("Sum of garbage collection pauses per collection")
.labelNames("name", "cause")
.buckets(0.005, 0.010, 0.025, 0.050, 0.100, 0.200, 0.400, 0.800, 1.600, 3.0, 5.0, 10.0)
.create()
//jdk.GCReferenceStatistics
private val REFERENCE_STATISTICS: Counter = Counter.build()
.name("jvm_reference_statistics")
.help("Number of java.lang.ref references by type")
.labelNames("type")
.create()
//jdk.ExecuteVMOperation
private val VM_OPERATIONS: Counter = Counter.build()
.name("jvm_vm_operations")
.help("Executed VM operations")
.labelNames("operation", "safepoint")
.create()
//jdk.NetworkUtilization
private val NETWORK_READ = Gauge.build()
.name("jvm_network_read")
.help("Bits read from the network per second")
.labelNames("interface")
.create()
//jdk.NetworkUtilization
private val NETWORK_WRITE = Gauge.build()
.name("jvm_network_write")
.help("Bits written to the network per second")
.labelNames("interface")
.create()
//jdk.JavaThreadStatistics
private val THREADS_CURRENT = Gauge.build()
.name("jvm_threads_current")
.help("Current thread count of the JVM")
.create()
//jdk.JavaThreadStatistics
private val THREADS_DAEMON = Gauge.build()
.name("jvm_threads_daemon")
.help("Daemon thread count of the JVM")
.create()
//jdk.CPULoad
private val CPU_USER = Gauge.build()
.name("jvm_cpu_user")
.help("User CPU usage of the JVM")
.create()
//jdk.CPULoad
private val CPU_SYSTEM = Gauge.build()
.name("jvm_cpu_system")
.help("System CPU usage of the JVM")
.create()
//jdk.CPULoad
private val CPU_MACHINE = Gauge.build()
.name("jvm_cpu_machine")
.help("CPU usage of the machine the JVM is running on")
.create()
//jdk.GCHeapSummary, jdk.MetaspaceSummary
private val MEMORY_USAGE = Gauge.build() // remove _jfr suffix if we remove the standard exports
.name("jvm_memory_bytes_used_jfr")
.help("Bytes of memory used by the JVM")
.labelNames("area") //heap, nonheap
.create()
private val MEMORY_USAGE_HEAP = MEMORY_USAGE.labels("heap")
private val MEMORY_USAGE_NONHEAP = MEMORY_USAGE.labels("nonheap")
fun register() {
if (!REGISTERED.compareAndSet(false, true)) return
SAFEPOINTS.register<Histogram>()
GC_PAUSES.register<Histogram>()
GC_PAUSES_SUM.register<Histogram>()
REFERENCE_STATISTICS.register<Counter>()
VM_OPERATIONS.register<Counter>()
NETWORK_READ.register<Collector>()
NETWORK_WRITE.register<Collector>()
THREADS_CURRENT.register<Collector>()
THREADS_DAEMON.register<Collector>()
CPU_USER.register<Collector>()
CPU_SYSTEM.register<Collector>()
CPU_MACHINE.register<Collector>()
MEMORY_USAGE.register<Collector>()
val rs = RecordingStream()
rs.setReuse(true)
rs.setOrdered(true)
//////////////////////// HOTSPOT INTERNALS ////////////////////////
/*
* https://github.com/openjdk/jdk/blob/6fd44901ec8b10e30dd7e25fb7024eb75d1e6042/src/hotspot/share/runtime/safepoint.cpp
*
* void SafepointSynchronize::begin() {
* EventSafepointBegin begin_event;
* SafepointTracing::begin(VMThread::vm_op_type());
* Universe::heap()->safepoint_synchronize_begin();
* Threads_lock->lock();
* int nof_threads = Threads::number_of_threads();
* <snip>
* EventSafepointStateSynchronization sync_event;
* arm_safepoint();
* int iterations = synchronize_threads(...);
* <snip>
* post_safepoint_synchronize_event(...);
* <snip>
* post_safepoint_begin_event(...);
* <snip>
* }
*
* void SafepointSynchronize::end() {
* EventSafepointEnd event;
*
* disarm_safepoint();
*
* Universe::heap()->safepoint_synchronize_end();
*
* SafepointTracing::end();
*
* post_safepoint_end_event(event, safepoint_id());
* }
*
* https://github.com/openjdk/jdk/blob/9f334a16401a0a4ae0a06d342f19750f694487cb/src/hotspot/share/gc/shared/collectedHeap.hpp#L202
*
* // Stop and resume concurrent GC threads interfering with safepoint operations
* virtual void safepoint_synchronize_begin() {}
* virtual void safepoint_synchronize_end() {}
*/
/*
* EventSafepointStateSynchronization starts at roughly the same time java threads
* start getting paused (by arm_safepoint()), while EventSafepointBegin also includes
* time to stop concurrent gc threads and acquire Threads_lock.
*
* EventSafepointEnd start is roughly the time java threads *start* getting resumed,
* but it's end is after java threads are done being resumed.
*/
// time to safepoint
val ttsp = LongLongRingBuffer(16)
val safepointDuration = LongLongRingBuffer(16)
/*
* jdk.SafepointBegin {
* startTime = 23:18:00.149
* duration = 53,3 ms
* safepointId = 32
* totalThreadCount = 16
* jniCriticalThreadCount = 0
* }
*/event(rs, "jdk.SafepointBegin", Consumer<RecordedEvent> { e -> logTTSP(ttsp, e) })
/*
* jdk.SafepointStateSynchronization {
* startTime = 16:11:44.439
* duration = 0,0155 ms
* safepointId = 6
* initialThreadCount = 0
* runningThreadCount = 0
* iterations = 1
* }
*/
//jdk.SafepointStateSynchronization starts after jdk.SafepointBegin,
//but gets posted before, so add to the buffer here and flip the order
//of the subtraction when calculating the time diff
event(rs, "jdk.SafepointStateSynchronization", Consumer<RecordedEvent> { e ->
ttsp.add(e.getLong("safepointId"), nanoTime(e.getStartTime()))
safepointDuration.add(e.getLong("safepointId"), nanoTime(e.getStartTime()))
})
/*
* jdk.SafepointEnd {
* startTime = 16:05:45.797
* duration = 0,00428 ms
* safepointId = 21
* }
*/
event(rs, "jdk.SafepointEnd", Consumer<RecordedEvent> { e -> logSafepointOperation(safepointDuration, e) })
/*
* jdk.GarbageCollection {
* startTime = 23:28:04.913
* duration = 7,65 ms
* gcId = 1
* name = "G1New"
* cause = "G1 Evacuation Pause"
* sumOfPauses = 7,65 ms
* longestPause = 7,65 ms
* }
*/
event(rs, "jdk.GarbageCollection", Consumer<RecordedEvent> { e ->
GC_PAUSES.labels(e.getString("name"), e.getString("cause"))
.observe(e.getDuration("longestPause").toNanos() / NANOSECONDS_PER_SECOND)
GC_PAUSES_SUM.labels(e.getString("name"), e.getString("cause"))
.observe(e.getDuration("sumOfPauses").toNanos() / NANOSECONDS_PER_SECOND)
})
/*
* jdk.GCReferenceStatistics {
* startTime = 23:36:09.323
* gcId = 1
* type = "Weak reference"
* count = 91
* }
*/
event(rs, "jdk.GCReferenceStatistics", Consumer<RecordedEvent> { e -> REFERENCE_STATISTICS.labels(e.getString("type")).inc(e.getLong("count").toDouble()) })
/*
* jdk.ExecuteVMOperation {
* startTime = 01:03:41.642
* duration = 13,4 ms
* operation = "G1CollectFull"
* safepoint = true
* blocking = true
* caller = "main" (javaThreadId = 1)
* safepointId = 18
* }
*/
event(rs, "jdk.ExecuteVMOperation", Consumer<RecordedEvent> { e -> VM_OPERATIONS.labels(e.getString("operation"), java.lang.String.valueOf(e.getBoolean("safepoint"))).inc() })
/*
* jdk.NetworkUtilization {
* startTime = 23:28:03.716
* networkInterface = N/A
* readRate = 4,4 kbps
* writeRate = 3,3 kbps
* }
*/
event(rs, "jdk.NetworkUtilization", Consumer<RecordedEvent> { e ->
var itf = e.getString("networkInterface")
if (itf == null) itf = "N/A"
NETWORK_READ.labels(itf).set(e.getLong("readRate").toDouble())
NETWORK_WRITE.labels(itf).set(e.getLong("writeRate").toDouble())
}).withPeriod(InteractionsMetrics.UPDATE_PERIOD)
/*
* jdk.JavaThreadStatistics {
* startTime = 01:13:57.686
* activeCount = 12
* daemonCount = 10
* accumulatedCount = 13
* peakCount = 13
* }
*/
event(rs, "jdk.JavaThreadStatistics", Consumer<RecordedEvent> { e ->
val count = e.getLong("activeCount").toDouble()
THREADS_CURRENT.set(count)
THREADS_DAEMON.set(e.getLong("daemonCount").toDouble())
}).withPeriod(InteractionsMetrics.UPDATE_PERIOD)
/*
* jdk.CPULoad {
* startTime = 23:22:50.114
* jvmUser = 31,88%
* jvmSystem = 8,73%
* machineTotal = 40,60%
* }
*/
event(rs, "jdk.CPULoad", Consumer<RecordedEvent> { e ->
val user = e.getFloat("jvmUser").toDouble()
val system = e.getFloat("jvmSystem").toDouble()
val machine = e.getFloat("machineTotal").toDouble()
CPU_USER.set(user)
CPU_SYSTEM.set(system)
CPU_MACHINE.set(machine)
}).withPeriod(InteractionsMetrics.UPDATE_PERIOD)
/*
* jdk.GCHeapSummary {
* startTime = 01:35:46.792
* gcId = 19
* when = "After GC"
* heapSpace = {
* start = 0x701600000
* committedEnd = 0x702400000
* committedSize = 14,0 MB
* reservedEnd = 0x800000000
* reservedSize = 4,0 GB
* }
* heapUsed = 6,3 MB
* }
*/
event(rs, "jdk.GCHeapSummary", Consumer<RecordedEvent> { e -> MEMORY_USAGE_HEAP.set(e.getLong("heapUsed").toDouble()) })
/*
* jdk.MetaspaceSummary {
* startTime = 01:49:47.867
* gcId = 37
* when = "After GC"
* gcThreshold = 20,8 MB
* metaspace = {
* committed = 6,3 MB
* used = 5,6 MB
* reserved = 1,0 GB
* }
* dataSpace = {
* committed = 5,5 MB
* used = 5,0 MB
* reserved = 8,0 MB
* }
* classSpace = {
* committed = 768,0 kB
* used = 579,4 kB
* reserved = 1,0 GB
* }
* }
*/
event(rs, "jdk.MetaspaceSummaryX", Consumer<RecordedEvent> { e ->
val amt = (getNestedUsed(e, "metaspace")
+ getNestedUsed(e, "dataSpace")
+ getNestedUsed(e, "classSpace"))
MEMORY_USAGE_NONHEAP.set(amt.toDouble())
}).withPeriod(InteractionsMetrics.UPDATE_PERIOD)
// start AsyncInfoMonitor data collection
rs.startAsync()
}
private fun event(rs: RecordingStream, name: String, c: Consumer<RecordedEvent>): EventSettings {
//default to no stacktrace
val s = rs.enable(name).withoutStackTrace()
rs.onEvent(name, c)
return s
}
private fun nanoTime(instant: Instant): Long {
return instant.toEpochMilli() * 1000000L + instant.getNano()
}
private fun getNestedUsed(event: RecordedEvent, field: String): Long {
return event.getValue<RecordedObject>(field).getLong("used")
}
private fun logTTSP(buffer: LongLongRingBuffer, event: RecordedEvent) {
val id = event.getLong("safepointId")
val time = buffer.remove(id)
if (time == -1L) {
//safepoint lost, buffer overwrote it
//this shouldn't happen unless we get a
//massive amount of safepoints at once
log.error("Safepoint with id {} lost", id)
} else {
//the buffer contains the time of the synchronize event,
//because that's what gets posted first, but the start event
//stats before
val elapsed = time - nanoTime(event.startTime)
SAFEPOINTS_TTSP.observe(elapsed / NANOSECONDS_PER_SECOND)
}
}
private fun logSafepointOperation(buffer: LongLongRingBuffer, event: RecordedEvent) {
val id = event.getLong("safepointId")
val time = buffer.remove(id)
if (time == -1L) {
//safepoint lost, buffer overwrote it
//this shouldn't happen unless we get a
//massive amount of safepoints at once
log.error("Safepoint with id {} lost", id)
} else {
val elapsed = nanoTime(event.endTime) - time
SAFEPOINTS_OPERATION.observe(elapsed / NANOSECONDS_PER_SECOND)
}
}
private class LongLongRingBuffer internal constructor(size: Int) {
private val table: LongArray
private val size: Int
private var index = -1
fun add(id: Long, value: Long) {
val idx = inc(index, size).also { index = it } * 2
table[idx] = id
table[idx + 1] = value
}
fun remove(id: Long): Long {
for (i in 0 until size) {
val idx = i * 2
if (table[idx] == id) {
table[idx] = -1
return table[idx + 1]
}
}
return -1
}
companion object {
private fun inc(i: Int, modulus: Int): Int {
var i = i
if (++i >= modulus) i = 0
return i
}
}
init {
table = LongArray(size * 2)
this.size = size
Arrays.fill(table, -1)
}
}
} | agpl-3.0 | 3788e128df5a6ae8a67afe20df19a027 | 35.993318 | 183 | 0.561683 | 3.954524 | false | false | false | false |
Mlieou/lXXtcode | leetcode/kotlin/ex_617.kt | 3 | 458 | /**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun mergeTrees(t1: TreeNode?, t2: TreeNode?): TreeNode? {
if (t1 == null) return t2
if (t2 == null) return t1
t1.`val` += t2.`val`
t1.left = mergeTrees(t1.left, t2.left)
t1.right = mergeTrees(t1.right, t2.right)
return t1
}
} | mit | d39a68879af50285451ddd32af563840 | 26 | 61 | 0.552402 | 3.033113 | false | false | false | false |
JayNewstrom/Concrete | concrete-testing/src/androidTest/java/com/jaynewstrom/concretetesting/ConcreteWallTest.kt | 1 | 1418 | package com.jaynewstrom.concretetesting
import android.view.LayoutInflater
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.jaynewstrom.concrete.Concrete
import org.fest.assertions.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ConcreteWallTest {
@Test fun ensureContextCreatedFromWallCanBeUsedToInject() {
val wall = Concrete.pourFoundation(DaggerContextTestComponent.create())
val context = wall.createContext(ApplicationProvider.getApplicationContext())
val target = ContextTestTarget()
Concrete.getComponent<ContextTestComponent>(context).inject(target)
assertThat(target.injectedString).isSameAs("Context test string")
}
@Test fun whenViewIsCreatedWithLayoutInflaterFromChildContextEnsureItCanBeInjectedWithContext() {
val wall = Concrete.pourFoundation(DaggerContextTestComponent.create())
val child = wall.stack(ContextChildTestBlock(wall.component))
val context = child.createContext(ApplicationProvider.getApplicationContext())
val exampleView = LayoutInflater.from(context).inflate(R.layout.example, null) as ExampleView
assertThat(exampleView.injectedChildString).isSameAs("I'm the child")
assertThat(exampleView.injectedString).isSameAs("Context test string")
}
}
| apache-2.0 | b2a383d27b42623d857eb1b615aa6b1f | 47.896552 | 101 | 0.786319 | 4.726667 | false | true | false | false |
cketti/okhttp | okhttp/src/main/kotlin/okhttp3/internal/connection/RealCall.kt | 1 | 17785 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import java.io.InterruptedIOException
import java.lang.ref.WeakReference
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import okhttp3.Address
import okhttp3.Call
import okhttp3.Callback
import okhttp3.CertificatePinner
import okhttp3.EventListener
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.assertThreadDoesntHoldLock
import okhttp3.internal.assertThreadHoldsLock
import okhttp3.internal.cache.CacheInterceptor
import okhttp3.internal.closeQuietly
import okhttp3.internal.http.BridgeInterceptor
import okhttp3.internal.http.CallServerInterceptor
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http.RetryAndFollowUpInterceptor
import okhttp3.internal.platform.Platform
import okhttp3.internal.threadName
import okio.AsyncTimeout
/**
* Bridge between OkHttp's application and network layers. This class exposes high-level application
* layer primitives: connections, requests, responses, and streams.
*
* This class supports [asynchronous canceling][cancel]. This is intended to have the smallest
* blast radius possible. If an HTTP/2 stream is active, canceling will cancel that stream but not
* the other streams sharing its connection. But if the TLS handshake is still in progress then
* canceling may break the entire connection.
*/
class RealCall(
val client: OkHttpClient,
/** The application's original request unadulterated by redirects or auth headers. */
val originalRequest: Request,
val forWebSocket: Boolean
) : Call {
private val connectionPool: RealConnectionPool = client.connectionPool.delegate
internal val eventListener: EventListener = client.eventListenerFactory.create(this)
private val timeout = object : AsyncTimeout() {
override fun timedOut() {
cancel()
}
}.apply {
timeout(client.callTimeoutMillis.toLong(), MILLISECONDS)
}
private val executed = AtomicBoolean()
// These properties are only accessed by the thread executing the call.
/** Initialized in [callStart]. */
private var callStackTrace: Any? = null
/** Finds an exchange to send the next request and receive the next response. */
private var exchangeFinder: ExchangeFinder? = null
var connection: RealConnection? = null
private set
private var timeoutEarlyExit = false
/**
* This is the same value as [exchange], but scoped to the execution of the network interceptors.
* The [exchange] field is assigned to null when its streams end, which may be before or after the
* network interceptors return.
*/
internal var interceptorScopedExchange: Exchange? = null
private set
// These properties are guarded by this. They are typically only accessed by the thread executing
// the call, but they may be accessed by other threads for duplex requests.
/** True if this call still has a request body open. */
private var requestBodyOpen = false
/** True if this call still has a response body open. */
private var responseBodyOpen = false
/** True if there are more exchanges expected for this call. */
private var expectMoreExchanges = true
// These properties are accessed by canceling threads. Any thread can cancel a call, and once it's
// canceled it's canceled forever.
@Volatile private var canceled = false
@Volatile private var exchange: Exchange? = null
@Volatile var connectionToCancel: RealConnection? = null
override fun timeout() = timeout
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
override fun clone() = RealCall(client, originalRequest, forWebSocket)
override fun request(): Request = originalRequest
/**
* Immediately closes the socket connection if it's currently held. Use this to interrupt an
* in-flight request from any thread. It's the caller's responsibility to close the request body
* and response body streams; otherwise resources may be leaked.
*
* This method is safe to be called concurrently, but provides limited guarantees. If a transport
* layer connection has been established (such as a HTTP/2 stream) that is terminated. Otherwise
* if a socket connection is being established, that is terminated.
*/
override fun cancel() {
if (canceled) return // Already canceled.
canceled = true
exchange?.cancel()
connectionToCancel?.cancel()
eventListener.canceled(this)
}
override fun isCanceled() = canceled
override fun execute(): Response {
check(executed.compareAndSet(false, true)) { "Already Executed" }
timeout.enter()
callStart()
try {
client.dispatcher.executed(this)
return getResponseWithInterceptorChain()
} finally {
client.dispatcher.finished(this)
}
}
override fun enqueue(responseCallback: Callback) {
check(executed.compareAndSet(false, true)) { "Already Executed" }
callStart()
client.dispatcher.enqueue(AsyncCall(responseCallback))
}
override fun isExecuted(): Boolean = executed.get()
private fun callStart() {
this.callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()")
eventListener.callStart(this)
}
@Throws(IOException::class)
internal fun getResponseWithInterceptorChain(): Response {
// Build a full stack of interceptors.
val interceptors = mutableListOf<Interceptor>()
interceptors += client.interceptors
interceptors += RetryAndFollowUpInterceptor(client)
interceptors += BridgeInterceptor(client.cookieJar)
interceptors += CacheInterceptor(client.cache)
interceptors += ConnectInterceptor
if (!forWebSocket) {
interceptors += client.networkInterceptors
}
interceptors += CallServerInterceptor(forWebSocket)
val chain = RealInterceptorChain(
call = this,
interceptors = interceptors,
index = 0,
exchange = null,
request = originalRequest,
connectTimeoutMillis = client.connectTimeoutMillis,
readTimeoutMillis = client.readTimeoutMillis,
writeTimeoutMillis = client.writeTimeoutMillis
)
var calledNoMoreExchanges = false
try {
val response = chain.proceed(originalRequest)
if (isCanceled()) {
response.closeQuietly()
throw IOException("Canceled")
}
return response
} catch (e: IOException) {
calledNoMoreExchanges = true
throw noMoreExchanges(e) as Throwable
} finally {
if (!calledNoMoreExchanges) {
noMoreExchanges(null)
}
}
}
/**
* Prepare for a potential trip through all of this call's network interceptors. This prepares to
* find an exchange to carry the request.
*
* Note that an exchange will not be needed if the request is satisfied by the cache.
*
* @param newExchangeFinder true if this is not a retry and new routing can be performed.
*/
fun enterNetworkInterceptorExchange(request: Request, newExchangeFinder: Boolean) {
check(interceptorScopedExchange == null)
synchronized(this) {
check(!responseBodyOpen) {
"cannot make a new request because the previous response is still open: " +
"please call response.close()"
}
check(!requestBodyOpen)
}
if (newExchangeFinder) {
this.exchangeFinder = ExchangeFinder(
connectionPool,
createAddress(request.url),
this,
eventListener
)
}
}
/** Finds a new or pooled connection to carry a forthcoming request and response. */
internal fun initExchange(chain: RealInterceptorChain): Exchange {
synchronized(this) {
check(expectMoreExchanges) { "released" }
check(!responseBodyOpen)
check(!requestBodyOpen)
}
val exchangeFinder = this.exchangeFinder!!
val codec = exchangeFinder.find(client, chain)
val result = Exchange(this, eventListener, exchangeFinder, codec)
this.interceptorScopedExchange = result
this.exchange = result
synchronized(this) {
this.requestBodyOpen = true
this.responseBodyOpen = true
}
if (canceled) throw IOException("Canceled")
return result
}
fun acquireConnectionNoEvents(connection: RealConnection) {
connection.assertThreadHoldsLock()
check(this.connection == null)
this.connection = connection
connection.calls.add(CallReference(this, callStackTrace))
}
/**
* Releases resources held with the request or response of [exchange]. This should be called when
* the request completes normally or when it fails due to an exception, in which case [e] should
* be non-null.
*
* If the exchange was canceled or timed out, this will wrap [e] in an exception that provides
* that additional context. Otherwise [e] is returned as-is.
*/
internal fun <E : IOException?> messageDone(
exchange: Exchange,
requestDone: Boolean,
responseDone: Boolean,
e: E
): E {
if (exchange != this.exchange) return e // This exchange was detached violently!
var bothStreamsDone = false
var callDone = false
synchronized(this) {
if (requestDone && requestBodyOpen || responseDone && responseBodyOpen) {
if (requestDone) requestBodyOpen = false
if (responseDone) responseBodyOpen = false
bothStreamsDone = !requestBodyOpen && !responseBodyOpen
callDone = !requestBodyOpen && !responseBodyOpen && !expectMoreExchanges
}
}
if (bothStreamsDone) {
this.exchange = null
this.connection?.incrementSuccessCount()
}
if (callDone) {
return callDone(e)
}
return e
}
internal fun noMoreExchanges(e: IOException?): IOException? {
var callDone = false
synchronized(this) {
if (expectMoreExchanges) {
expectMoreExchanges = false
callDone = !requestBodyOpen && !responseBodyOpen
}
}
if (callDone) {
return callDone(e)
}
return e
}
/**
* Complete this call. This should be called once these properties are all false:
* [requestBodyOpen], [responseBodyOpen], and [expectMoreExchanges].
*
* This will release the connection if it is still held.
*
* It will also notify the listener that the call completed; either successfully or
* unsuccessfully.
*
* If the call was canceled or timed out, this will wrap [e] in an exception that provides that
* additional context. Otherwise [e] is returned as-is.
*/
private fun <E : IOException?> callDone(e: E): E {
assertThreadDoesntHoldLock()
val connection = this.connection
if (connection != null) {
connection.assertThreadDoesntHoldLock()
val socket = synchronized(connection) {
releaseConnectionNoEvents() // Sets this.connection to null.
}
if (this.connection == null) {
socket?.closeQuietly()
eventListener.connectionReleased(this, connection)
} else {
check(socket == null) // If we still have a connection we shouldn't be closing any sockets.
}
}
val result = timeoutExit(e)
if (e != null) {
eventListener.callFailed(this, result!!)
} else {
eventListener.callEnd(this)
}
return result
}
/**
* Remove this call from the connection's list of allocations. Returns a socket that the caller
* should close.
*/
internal fun releaseConnectionNoEvents(): Socket? {
val connection = this.connection!!
connection.assertThreadHoldsLock()
val calls = connection.calls
val index = calls.indexOfFirst { it.get() == this@RealCall }
check(index != -1)
calls.removeAt(index)
this.connection = null
if (calls.isEmpty()) {
connection.idleAtNs = System.nanoTime()
if (connectionPool.connectionBecameIdle(connection)) {
return connection.socket()
}
}
return null
}
private fun <E : IOException?> timeoutExit(cause: E): E {
if (timeoutEarlyExit) return cause
if (!timeout.exit()) return cause
val e = InterruptedIOException("timeout")
if (cause != null) e.initCause(cause)
@Suppress("UNCHECKED_CAST") // E is either IOException or IOException?
return e as E
}
/**
* Stops applying the timeout before the call is entirely complete. This is used for WebSockets
* and duplex calls where the timeout only applies to the initial setup.
*/
fun timeoutEarlyExit() {
check(!timeoutEarlyExit)
timeoutEarlyExit = true
timeout.exit()
}
/**
* @param closeExchange true if the current exchange should be closed because it will not be used.
* This is usually due to either an exception or a retry.
*/
internal fun exitNetworkInterceptorExchange(closeExchange: Boolean) {
synchronized(this) {
check(expectMoreExchanges) { "released" }
}
if (closeExchange) {
exchange?.detachWithViolence()
}
interceptorScopedExchange = null
}
private fun createAddress(url: HttpUrl): Address {
var sslSocketFactory: SSLSocketFactory? = null
var hostnameVerifier: HostnameVerifier? = null
var certificatePinner: CertificatePinner? = null
if (url.isHttps) {
sslSocketFactory = client.sslSocketFactory
hostnameVerifier = client.hostnameVerifier
certificatePinner = client.certificatePinner
}
return Address(
uriHost = url.host,
uriPort = url.port,
dns = client.dns,
socketFactory = client.socketFactory,
sslSocketFactory = sslSocketFactory,
hostnameVerifier = hostnameVerifier,
certificatePinner = certificatePinner,
proxyAuthenticator = client.proxyAuthenticator,
proxy = client.proxy,
protocols = client.protocols,
connectionSpecs = client.connectionSpecs,
proxySelector = client.proxySelector
)
}
fun retryAfterFailure() = exchangeFinder!!.retryAfterFailure()
/**
* Returns a string that describes this call. Doesn't include a full URL as that might contain
* sensitive information.
*/
private fun toLoggableString(): String {
return ((if (isCanceled()) "canceled " else "") +
(if (forWebSocket) "web socket" else "call") +
" to " + redactedUrl())
}
internal fun redactedUrl(): String = originalRequest.url.redact()
internal inner class AsyncCall(
private val responseCallback: Callback
) : Runnable {
@Volatile var callsPerHost = AtomicInteger(0)
private set
fun reuseCallsPerHostFrom(other: AsyncCall) {
this.callsPerHost = other.callsPerHost
}
val host: String
get() = originalRequest.url.host
val request: Request
get() = originalRequest
val call: RealCall
get() = this@RealCall
/**
* Attempt to enqueue this async call on [executorService]. This will attempt to clean up
* if the executor has been shut down by reporting the call as failed.
*/
fun executeOn(executorService: ExecutorService) {
client.dispatcher.assertThreadDoesntHoldLock()
var success = false
try {
executorService.execute(this)
success = true
} catch (e: RejectedExecutionException) {
val ioException = InterruptedIOException("executor rejected")
ioException.initCause(e)
noMoreExchanges(ioException)
responseCallback.onFailure(this@RealCall, ioException)
} finally {
if (!success) {
client.dispatcher.finished(this) // This call is no longer running!
}
}
}
override fun run() {
threadName("OkHttp ${redactedUrl()}") {
var signalledCallback = false
timeout.enter()
try {
val response = getResponseWithInterceptorChain()
signalledCallback = true
responseCallback.onResponse(this@RealCall, response)
} catch (e: IOException) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log("Callback failure for ${toLoggableString()}", Platform.INFO, e)
} else {
responseCallback.onFailure(this@RealCall, e)
}
} catch (t: Throwable) {
cancel()
if (!signalledCallback) {
val canceledException = IOException("canceled due to $t")
canceledException.addSuppressed(t)
responseCallback.onFailure(this@RealCall, canceledException)
}
throw t
} finally {
client.dispatcher.finished(this)
}
}
}
}
internal class CallReference(
referent: RealCall,
/**
* Captures the stack trace at the time the Call is executed or enqueued. This is helpful for
* identifying the origin of connection leaks.
*/
val callStackTrace: Any?
) : WeakReference<RealCall>(referent)
}
| apache-2.0 | 9be949dfcd20dbadf99787911180f1d9 | 31.336364 | 100 | 0.695755 | 4.691374 | false | false | false | false |
eugeis/ee | ee-lang_item/src/main/kotlin/ee/lang/ItemEmpty.kt | 1 | 3553 | package ee.lang
import java.util.*
object ItemEmpty : ItemEmptyClass<ItemEmpty>()
open class ItemEmptyClass<B : ItemI<B>> : ItemI<B> {
override fun extendAdapt(adapt: B.() -> Unit): B = apply {}
override fun namespace(): String = ""
override fun namespace(value: String): B = apply {}
override fun name(): String = "@@EMPTY@@"
override fun name(value: String): B = apply {}
override fun doc(): CommentI<*> = CommentEmpty
override fun doc(value: CommentI<*>): B = apply {}
override fun parent(): ItemI<*> = ItemEmpty
override fun parent(value: ItemI<*>): B = apply {}
override fun onDerived(derived: ItemI<*>) {}
override fun derivedItems(): List<ItemI<*>> = emptyList()
override fun derivedFrom(): ItemI<*> = ItemEmpty
override fun derivedFrom(value: ItemI<*>): B = apply {}
override fun derivedAsType(): String = ""
override fun derivedAsType(value: String): B = apply {}
override fun derive(adapt: B.() -> Unit): B = apply {}
override fun deriveWithParent(adapt: B.() -> Unit): B = apply {}
@Suppress("UNCHECKED_CAST")
override fun <T : ItemI<*>> apply(code: T.() -> Unit): T = this as T
override fun <R> applyAndReturn(code: () -> R): R = code()
override fun deriveSubType(adapt: B.() -> Unit): B = apply {}
override fun toDsl(builder: StringBuilder, indent: String) {}
override fun toDsl(): String = ""
override fun isInitialized(): Boolean = true
override fun isInternal(): Boolean = true
override fun init(): B = apply {}
override fun copy(): B = apply {}
override fun copyWithParent(): B = apply {}
}
object MultiMapHolderEmpty : MapMultiHolderEmptyClass<Any, MultiMapHolderEmpty>()
open class MultiHolderEmptyClass<I, B : MultiHolderI<I, B>> : ItemEmptyClass<B>(), MultiHolderI<I, B> {
override fun items(): Collection<I> = emptyList()
override fun containsItem(item: I): Boolean = false
override fun <T : I> addItem(item: T): T = item
@Suppress("UNCHECKED_CAST")
override fun <T : I> addItems(items: Collection<T>): B = this as B
override fun <T> supportsItem(item: T): Boolean = false
override fun <T> supportsItemType(itemType: Class<T>): Boolean = false
override fun <T> fillSupportsItem(item: T): Boolean = false
override fun fillSupportsItems() {}
}
open class ListMultiHolderEmptyClass<I, B : ListMultiHolderI<I, B>>(private val items: MutableList<I> = ArrayList()) :
MultiHolderEmptyClass<I, B>(), ListMultiHolderI<I, B>, MutableList<I> by items
object CommentEmpty : CommentEmptyClass<CommentEmpty>()
open class CommentEmptyClass<B : CommentI<B>> : ListMultiHolderEmptyClass<String, B>(), CommentI<B>
fun <T : ItemI<*>> T?.isEMPTY(): Boolean =
(this == null || this == ItemEmpty || this.javaClass.toString().contains("Empty") ||
name() == ItemEmpty.name())
fun <T : ItemI<*>> T?.isNotEMPTY(): Boolean = !isEMPTY()
open class MapMultiHolderEmptyClass<I, B : MapMultiHolderI<I, B>> : MultiHolderEmptyClass<I, B>(),
MapMultiHolderI<I, B> {
override fun removeItem(childName: String) {}
override fun <T : I> addItem(childName: String, item: T): T = item
override fun itemsMap(): Map<String, I> = emptyMap()
}
object CompositeEmpty : CompositeEmptyClass<CompositeEmpty>()
open class CompositeEmptyClass<B : CompositeI<B>> : MapMultiHolderEmptyClass<ItemI<*>, B>(), CompositeI<B> {
override fun <T : Any> attr(name: String, attr: T?) = attr
override fun attributes(): MapMultiHolderI<*, *> = MultiMapHolderEmpty
} | apache-2.0 | f681587f0da8810fdac84432099362e6 | 40.811765 | 118 | 0.663665 | 3.787846 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/cfr/CfrMiddleware.kt | 1 | 3445 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.cfr
import android.content.Context
import androidx.core.net.toUri
import mozilla.components.browser.state.action.BrowserAction
import mozilla.components.browser.state.action.ContentAction
import mozilla.components.browser.state.action.TrackingProtectionAction
import mozilla.components.browser.state.selector.findTabOrCustomTabOrSelectedTab
import mozilla.components.browser.state.state.BrowserState
import mozilla.components.lib.state.Middleware
import mozilla.components.lib.state.MiddlewareContext
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.truncatedHost
import org.mozilla.focus.nimbus.FocusNimbus
import org.mozilla.focus.nimbus.Onboarding
import org.mozilla.focus.state.AppAction
/**
* Middleware used to intercept browser store actions in order to decide when should we display a specific CFR
*/
class CfrMiddleware(private val appContext: Context) : Middleware<BrowserState, BrowserAction> {
private val onboardingFeature = FocusNimbus.features.onboarding
private lateinit var onboardingConfig: Onboarding
private val components = appContext.components
private var isCurrentTabSecure = false
private var tpExposureAlreadyRecorded = false
override fun invoke(
context: MiddlewareContext<BrowserState, BrowserAction>,
next: (BrowserAction) -> Unit,
action: BrowserAction,
) {
onboardingConfig = onboardingFeature.value(context = appContext)
if (onboardingConfig.isCfrEnabled) {
if (action is ContentAction.UpdateSecurityInfoAction) {
isCurrentTabSecure = action.securityInfo.secure
}
next(action)
showTrackingProtectionCfr(action, context)
} else {
next(action)
}
}
private fun showTrackingProtectionCfr(
action: BrowserAction,
context: MiddlewareContext<BrowserState, BrowserAction>,
) {
if (shouldShowCfrForTrackingProtection(action = action, browserState = context.state)) {
if (!tpExposureAlreadyRecorded) {
FocusNimbus.features.onboarding.recordExposure()
tpExposureAlreadyRecorded = true
}
components.appStore.dispatch(
AppAction.ShowTrackingProtectionCfrChange(
mapOf((action as TrackingProtectionAction.TrackerBlockedAction).tabId to true),
),
)
}
}
private fun isMozillaUrl(browserState: BrowserState): Boolean {
return browserState.findTabOrCustomTabOrSelectedTab(
browserState.selectedTabId,
)?.content?.url?.toUri()?.truncatedHost()?.substringBefore(".") == ("mozilla")
}
private fun isActionSecure(action: BrowserAction) =
action is TrackingProtectionAction.TrackerBlockedAction && isCurrentTabSecure
private fun shouldShowCfrForTrackingProtection(
action: BrowserAction,
browserState: BrowserState,
) = (
isActionSecure(action = action) &&
!isMozillaUrl(browserState = browserState) &&
components.settings.shouldShowCfrForTrackingProtection &&
!components.appStore.state.showEraseTabsCfr
)
}
| mpl-2.0 | 925c979148029f77dc8bafd4e2eb6b06 | 39.05814 | 110 | 0.712627 | 4.845288 | false | false | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalImage.kt | 1 | 4520 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.kotlin.widget
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView.ScaleType
import com.facebook.litho.DrawableMatrix
import com.facebook.litho.MatrixDrawable
import com.facebook.litho.MeasureScope
import com.facebook.litho.MountableComponent
import com.facebook.litho.MountableComponentScope
import com.facebook.litho.MountableRenderResult
import com.facebook.litho.SimpleMountable
import com.facebook.litho.Size
import com.facebook.litho.SizeSpec
import com.facebook.litho.SizeSpec.UNSPECIFIED
import com.facebook.litho.Style
import com.facebook.litho.drawable.DrawableUtils
import com.facebook.rendercore.MeasureResult
/**
* A component to render a [Drawable].
*
* Tip: Use the same instance of the [drawable] to avoid remounting it in subsequent layouts to
* improve performance.
*
* @param drawable The [Drawable] to render.
* @param scaleType The [ScaleType] to scale or transform the [drawable].
*/
class ExperimentalImage(
val drawable: Drawable,
val scaleType: ScaleType? = ScaleType.FIT_XY,
val style: Style? = null,
) : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult =
MountableRenderResult(ImageMountable(drawable, scaleType ?: ScaleType.FIT_XY), style)
}
/**
* The [SimpleMountable] used by the [ExperimentalImage]. It uses a [MatrixDrawable], and
* [DrawableMatrix] to correctly render the actual [drawable] inside it.
*/
internal class ImageMountable(
val drawable: Drawable,
val scaleType: ScaleType,
) : SimpleMountable<MatrixDrawable<Drawable>>(RenderType.DRAWABLE) {
override fun createContent(context: Context): MatrixDrawable<Drawable> {
return MatrixDrawable()
}
override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult {
val size = Size()
val intrinsicWidth = drawable.intrinsicWidth
val intrinsicHeight = drawable.intrinsicHeight
if (SizeSpec.getMode(widthSpec) == UNSPECIFIED && SizeSpec.getMode(heightSpec) == UNSPECIFIED) {
size.width = intrinsicWidth
size.height = intrinsicHeight
} else {
val aspectRatio = intrinsicWidth.toFloat() / intrinsicHeight.toFloat()
// measureWithAspectRatio will appropriately set sizes on the size object
withAspectRatio(widthSpec, heightSpec, intrinsicWidth, intrinsicHeight, aspectRatio, size)
}
val matrix =
if (scaleType == ScaleType.FIT_XY || intrinsicWidth <= 0 || intrinsicHeight <= 0) {
null
} else {
DrawableMatrix.create(drawable, scaleType, size.width, size.height)
}
val useLayoutSize = ScaleType.FIT_XY == scaleType || intrinsicWidth <= 0 || intrinsicHeight <= 0
return MeasureResult(
size.width,
size.height,
ImageLayoutData(
if (useLayoutSize) size.width else intrinsicWidth,
if (useLayoutSize) size.height else intrinsicHeight,
matrix))
}
override fun mount(c: Context, content: MatrixDrawable<Drawable>, layoutData: Any?) {
layoutData as ImageLayoutData
content.mount(drawable, layoutData.matrix)
content.bind(layoutData.width, layoutData.height)
}
override fun unmount(c: Context, content: MatrixDrawable<Drawable>, layoutData: Any?) {
content.unmount()
}
override fun shouldUpdate(
newMountable: SimpleMountable<MatrixDrawable<Drawable>>,
currentLayoutData: Any?,
nextLayoutData: Any?
): Boolean {
newMountable as ImageMountable
return (newMountable.scaleType != scaleType ||
!DrawableUtils.isEquivalentTo(newMountable.drawable, drawable))
}
override fun poolSize(): Int = 30
}
/** The layout data required by the [ImageMountable] to mount, and bind the drawable in the host. */
class ImageLayoutData(val width: Int, val height: Int, val matrix: DrawableMatrix? = null)
| apache-2.0 | d616d177dcb450d373b606c77d9df816 | 34.873016 | 100 | 0.735619 | 4.409756 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/about/LawnchairLink.kt | 1 | 2629 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.about
import android.content.Intent
import android.net.Uri
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.material3.MaterialTheme as Material3Theme
@Composable
fun LawnchairLink(
@DrawableRes iconResId: Int,
label: String,
modifier: Modifier = Modifier,
url: String
) {
val context = LocalContext.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = modifier
.height(64.dp)
.clip(MaterialTheme.shapes.medium)
.clickable {
val webpage = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, webpage)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
) {
Image(
painterResource(id = iconResId),
contentDescription = null,
colorFilter = ColorFilter.tint(color = LocalContentColor.current),
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.requiredHeight(4.dp))
Text(
text = label,
style = Material3Theme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
} | gpl-3.0 | d0545dec458cdb7d0a245ac7a4f7d2f5 | 33.605263 | 78 | 0.702929 | 4.628521 | false | false | false | false |
exteso/alf.io-PI | backend/src/main/kotlin/alfio/pi/model/ScanModel.kt | 1 | 9260 | /*
* This file is part of alf.io.
*
* alf.io 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.
*
* alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.pi.model
import alfio.pi.manager.ConfigurableLabelContent
import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.springframework.context.ApplicationEvent
import org.springframework.stereotype.Component
import java.io.Serializable
import java.math.BigDecimal
import java.time.ZonedDateTime
enum class Role {ADMIN, OPERATOR}
data class Event(@Column("key") val key: String,
@Column("name") val name: String,
@Column("image_url") val imageUrl: String?,
@Column("begin_ts") val begin: ZonedDateTime,
@Column("end_ts") val end: ZonedDateTime,
@Column("location") val location: String?,
@Column("api_version") val apiVersion: Int,
@Column("active") val active: Boolean,
@Column("last_update") val lastUpdate: ZonedDateTime?,
@Column("timezone") val timezone: String?)
data class Printer(@Column("id") val id: Int, @Column("name") val name: String, @Column("description") val description: String?, @Column("active") val active: Boolean) : Comparable<Printer> {
override fun compareTo(other: Printer): Int = name.compareTo(other.name)
}
@Component
internal open class GsonContainer(gson: Gson) {
init {
GSON = gson
}
companion object {
var GSON: Gson? = null
}
}
data class ScanLog(val id: String,
val timestamp: ZonedDateTime,
val eventKey: String,
val ticketUuid: String,
val userId: Int,
val localResult: CheckInStatus,
val remoteResult: CheckInStatus,
val badgePrinted: Boolean,
val ticketData: String?) {
val ticket: Ticket? = if(!ticketData.isNullOrEmpty()) {
GsonContainer.GSON?.fromJson(ticketData, Ticket::class.java)
} else {
null
}
}
data class User(@Column("id") val id: Int, @Column("username") val username: String)
data class UserWithPassword(val id: Int, val username: String, val password: String)
data class Authority(@Column("username") val username: String, @Column("role") val role: Role)
data class UserPrinter(@Column("user_id_fk") val userId: Int, @Column("printer_id_fk") val printerId: Int)
data class UserAndPrinter(@Column("username") private val username: String,
@Column("user_id") private val userId: Int,
@Column("printer_id") private val printerId: Int,
@Column("printer_name") private val printerName: String,
@Column("printer_description") private val printerDescription: String?,
@Column("printer_active") private val printerActive: Boolean) {
val user = User(userId, username)
val printer = Printer(printerId, printerName, printerDescription, printerActive)
}
data class LabelConfiguration(@Column("event_key_fk") val eventKey: String,
@Column("json") val json: String?,
@Column("enabled") val enabled: Boolean) : Serializable {
val layout: LabelLayout? = GsonContainer.GSON?.fromJson(json, LabelLayout::class.java)
}
data class LabelConfigurationAndContent(val configuration: LabelConfiguration?, val content: ConfigurableLabelContent?)
class CheckInEvent(source: Any, val scanLog: ScanLog) : ApplicationEvent(source)
open class Ticket(val uuid: String,
val firstName: String,
val lastName: String,
val email: String?,
val additionalInfo: Map<String, String>?,
val fullName: String = "$firstName $lastName",
val hmac: String? = null,
val categoryName: String? = null,
val validCheckInFrom: String? = null,
val validCheckInTo: String? = null,
val additionalServicesInfo: List<AdditionalServiceInfo> = emptyList()) : Serializable
class TicketNotFound(uuid: String) : Ticket(uuid, "", "", "", emptyMap())
abstract class CheckInResponse(val result: CheckInResult, val ticket: Ticket?) : Serializable {
fun isSuccessful(): Boolean = result.status.successful
fun isSuccessfulOrRetry(): Boolean = result.status.successful || result.status == CheckInStatus.RETRY
}
class TicketAndCheckInResult(ticket: Ticket, result: CheckInResult) : CheckInResponse(result, ticket), Serializable
class EmptyTicketResult(result: CheckInResult = CheckInResult(boxColorClass = "danger")) : CheckInResponse(result, null), Serializable
class CheckInForbidden(result: CheckInResult = CheckInResult(status = CheckInStatus.INVALID_TICKET_STATE, boxColorClass = "danger")) : CheckInResponse(result, null), Serializable
class DuplicateScanResult(result: CheckInResult = CheckInResult(CheckInStatus.ALREADY_CHECK_IN, boxColorClass = "danger"), val originalScanLog: ScanLog) : CheckInResponse(result, originalScanLog.ticket), Serializable
data class CheckInResult(val status: CheckInStatus = CheckInStatus.TICKET_NOT_FOUND,
val message: String? = null,
val dueAmount: BigDecimal = BigDecimal.ZERO,
val currency: String = "",
val boxColorClass: String = ""): Serializable
enum class CheckInStatus(val successful: Boolean = false) {
RETRY(),
EVENT_NOT_FOUND(),
TICKET_NOT_FOUND(),
EMPTY_TICKET_CODE(),
INVALID_TICKET_CODE(),
INVALID_TICKET_STATE(),
ALREADY_CHECK_IN(),
MUST_PAY(),
OK_READY_TO_BE_CHECKED_IN(true),
SUCCESS(true),
INVALID_TICKET_CATEGORY_CHECK_IN_DATE();
}
data class TicketData(val firstName: String,
val lastName: String,
val email: String,
val category: String?,
private val status: String,
private val additionalInfoJson: String?,
val validCheckInFrom: String?,
val validCheckInTo: String?,
private val additionalServicesInfoJson: String?) {
val checkInStatus: CheckInStatus
get() = when(status) {
"ACQUIRED" -> CheckInStatus.SUCCESS
"CHECKED_IN" -> CheckInStatus.ALREADY_CHECK_IN
"TO_BE_PAID" -> CheckInStatus.MUST_PAY
else -> CheckInStatus.INVALID_TICKET_STATE
}
val additionalInfo: Map<String, String>
get() = GsonContainer.GSON?.fromJson(additionalInfoJson, object : TypeToken<Map<String, String>>() {}.type) ?: emptyMap()
val additionalServicesInfo: List<AdditionalServiceInfo>
get() = GsonContainer.GSON?.fromJson(additionalServicesInfoJson, object : TypeToken<List<AdditionalServiceInfo>>() {}.type) ?: emptyList()
}
class RemoteEvent {
var key: String? = null
var external: Boolean = false
var name: String? = null
var imageUrl: String? = null
var begin: String? = null
var end: String? = null
var oneDay: Boolean = false
var location: String? = null
var apiVersion: Int = 0
var timeZone: String? = null
}
class AdditionalServiceInfo {
var name: String? = null
var count: Int = 0
var fields: List<TicketFieldValueForAdditionalService>? = null
}
class TicketFieldValueForAdditionalService {
var fieldName: String? = null
var fieldValue: String? = null
var additionalServiceId: Int = 0
}
data class PrinterWithUsers(val printer: Printer, val users: List<User>): Comparable<PrinterWithUsers> {
override fun compareTo(other: PrinterWithUsers): Int = printer.id.compareTo(other.printer.id)
override fun equals(other: Any?): Boolean {
return if(other is PrinterWithUsers) {
printer.id == other.printer.id
} else {
false
}
}
override fun hashCode(): Int {
return printer.id.hashCode()
}
}
data class SystemPrinter(val name: String)
data class RemotePrinter(val name: String, val remoteHost: String)
data class LabelLayout(val qrCode: QRCode, val content: Content, val general: General) : Serializable
data class QRCode(val additionalInfo: List<String>, val infoSeparator: String) : Serializable
data class Content(val firstRow: String?, val secondRow: String?, val thirdRow: List<String>?, val additionalRows: List<String>?, val checkbox: Boolean?) : Serializable
data class General(val printPartialID: Boolean) : Serializable
| gpl-3.0 | ac7614ad0b613cd4d3025608dff119d5 | 41.672811 | 216 | 0.657559 | 4.401141 | false | false | false | false |
javecs/expr | src/test/kotlin/xyz/javecs/tools/expr/test/kotlin/CalculatorVariablesTest.kt | 1 | 496 | package xyz.javecs.tools.expr.test.kotlin
import kotlin.test.assertEquals
import org.junit.Test
import xyz.javecs.tools.expr.Calculator
class CalculatorVariablesTest {
@Test fun calcVariables1() {
val calc = Calculator()
calc.eval("x = 3")
calc.eval("y = 4")
calc.eval("z = x * y")
val variables = calc.variables()
assertEquals(variables["x"], 3.0)
assertEquals(variables["y"], 4.0)
assertEquals(variables["z"], 12.0)
}
}
| mit | bac33b63c42cc868dd09c5b75758879a | 26.555556 | 42 | 0.625 | 3.674074 | false | true | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/TrackAdapter.kt | 3 | 1274 | package eu.kanade.tachiyomi.ui.manga.track
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.inflate
class TrackAdapter(controller: TrackController) : RecyclerView.Adapter<TrackHolder>() {
var items = emptyList<TrackItem>()
set(value) {
if (field !== value) {
field = value
notifyDataSetChanged()
}
}
val rowClickListener: OnClickListener = controller
fun getItem(index: Int): TrackItem? {
return items.getOrNull(index)
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrackHolder {
val view = parent.inflate(R.layout.track_item)
return TrackHolder(view, this)
}
override fun onBindViewHolder(holder: TrackHolder, position: Int) {
holder.bind(items[position])
}
interface OnClickListener {
fun onLogoClick(position: Int)
fun onTitleClick(position: Int)
fun onStatusClick(position: Int)
fun onChaptersClick(position: Int)
fun onScoreClick(position: Int)
}
}
| apache-2.0 | 6056b3ecd0c398b8f6263e1934e60a2e | 26.311111 | 87 | 0.633438 | 4.55 | false | false | false | false |
julianhyde/calcite | buildSrc/subprojects/fmpp/src/main/kotlin/org/apache/calcite/buildtools/fmpp/FmppTask.kt | 5 | 3147 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.buildtools.fmpp
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.Configuration
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.kotlin.dsl.withGroovyBuilder
@CacheableTask
open class FmppTask @Inject constructor(
objectFactory: ObjectFactory
) : DefaultTask() {
@Classpath
val fmppClasspath = objectFactory.property<Configuration>()
.convention(project.configurations.named(FmppPlugin.FMPP_CLASSPATH_CONFIGURATION_NAME))
@InputFile
@PathSensitive(PathSensitivity.NONE)
val config = objectFactory.fileProperty()
@InputDirectory
@PathSensitive(PathSensitivity.RELATIVE)
val templates = objectFactory.directoryProperty()
@InputFile
@PathSensitive(PathSensitivity.NONE)
val defaultConfig = objectFactory.fileProperty()
.convention(templates.file("../default_config.fmpp"))
@OutputDirectory
val output = objectFactory.directoryProperty()
.convention(project.layout.buildDirectory.dir("fmpp/$name"))
/**
* Path might contain spaces and TDD special characters, so it needs to be quoted.
* See http://fmpp.sourceforge.net/tdd.html
*/
private fun String.tddString() =
"\"${toString().replace("\\", "\\\\").replace("\"", "\\\"")}\""
@TaskAction
fun run() {
project.delete(output.asFileTree)
ant.withGroovyBuilder {
"taskdef"(
"name" to "fmpp",
"classname" to "fmpp.tools.AntTask",
"classpath" to fmppClasspath.get().asPath
)
"fmpp"(
"configuration" to config.get(),
"sourceRoot" to templates.get().asFile,
"outputRoot" to output.get().asFile,
"data" to "tdd(${config.get().toString().tddString()}), " +
"default: tdd(${defaultConfig.get().toString().tddString()})"
)
}
}
}
| apache-2.0 | 1b7c6961cc6b94cc663be448f0a84d4e | 36.023529 | 95 | 0.694312 | 4.476529 | false | true | false | false |
RettyEng/redux-kt | sample/app/src/main/kotlin/me/retty/reduxkt/sample/redux/reducer/TodoReducerSet.kt | 1 | 1304 | package me.retty.reduxkt.sample.redux.reducer
import me.retty.reduxkt.sample.data.Todo
import me.retty.reduxkt.sample.redux.action.TodoAction
import me.retty.reduxkt.sample.redux.state.ApplicationState
/**
* Created by atsukofukui on 2017/08/23.
*/
class TodoReducerSet {
companion object {
fun aggregatedReducer(action: TodoAction, state: ApplicationState) = when (action) {
is TodoAction.OnCreateTodoAction -> onCreateTodoAction(action, state)
is TodoAction.OnToggleCompletedTodoAction -> onToggleCompletedTodoAction(action, state)
else -> state
}
private fun onCreateTodoAction(action: TodoAction.OnCreateTodoAction, state: ApplicationState) =
state.copy(todos = state.todos + Todo(state.todos.size.toLong(),
action.name, action.memo, false))
private fun onToggleCompletedTodoAction(action: TodoAction.OnToggleCompletedTodoAction,
state: ApplicationState) =
state.copy(todos= state.todos.map {
if (it.id == action.id) {
it.copy(isDone = !it.isDone)
} else {
it
}
})
}
} | mit | a01cb2f9b9c61d74bba9d62671a65e5b | 39.78125 | 104 | 0.592025 | 4.657143 | false | false | false | false |
msebire/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/LookupStateManager.kt | 2 | 2450 | /*
* Copyright 2000-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.impl.LookupImpl
class LookupStateManager {
private val elementToId = mutableMapOf<String, Int>()
private val idToEntryInfo = mutableMapOf<Int, LookupEntryInfo>()
fun update(lookup: LookupImpl): LookupState {
val ids = mutableListOf<Int>()
val newIds = mutableSetOf<Int>()
val items = lookup.items
val currentPosition = items.indexOf(lookup.currentItem)
for (item in items) {
var id = getElementId(item)
if (id == null) {
id = registerElement(item)
newIds.add(id)
}
ids.add(id)
}
val infos = items.toLookupInfos(lookup)
val newInfos = infos.filter { it.id in newIds }
val itemsDiff = infos.mapNotNull { idToEntryInfo[it.id]?.calculateDiff(it) }
infos.forEach { idToEntryInfo[it.id] = it }
return LookupState(ids, newInfos, itemsDiff, currentPosition)
}
fun getElementId(item: LookupElement): Int? {
val itemString = item.idString()
return elementToId[itemString]
}
private fun registerElement(item: LookupElement): Int {
val itemString = item.idString()
val newId = elementToId.size
elementToId[itemString] = newId
return newId
}
private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl): List<LookupEntryInfo> {
val relevanceObjects = lookup.getRelevanceObjects(this, false)
return this.map {
val id = getElementId(it)!!
val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap()
LookupEntryInfo(id, it.lookupString.length, relevanceMap)
}
}
} | apache-2.0 | 3a8be056807fd6b7e1faea9f481a6a1b | 32.121622 | 107 | 0.662857 | 4.478976 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/adapters/BeerAdapter.kt | 1 | 4708 | package nl.ecci.hamers.ui.adapters
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.Toast
import com.bumptech.glide.Glide
import com.google.gson.GsonBuilder
import kotlinx.android.synthetic.main.row_beer.view.*
import nl.ecci.hamers.R
import nl.ecci.hamers.models.Beer
import nl.ecci.hamers.ui.activities.SingleBeerActivity
import nl.ecci.hamers.ui.activities.SingleImageActivity
import nl.ecci.hamers.utils.Utils
import java.util.*
internal class BeerAdapter(private val dataSet: ArrayList<Beer>, private val context: Context) : RecyclerView.Adapter<BeerAdapter.ViewHolder>(), Filterable {
private var filteredDataSet: ArrayList<Beer> = dataSet
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.row_beer, parent, false)
val vh = ViewHolder(view)
view.setOnClickListener {
val activity = context as Activity
val imageTransitionName = context.getString(R.string.transition_single_image)
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, view.image, imageTransitionName)
val intent = Intent(context, SingleBeerActivity::class.java)
intent.putExtra(Beer.BEER, filteredDataSet[vh.adapterPosition].id)
ActivityCompat.startActivity(activity, intent, options.toBundle())
}
view.image.setOnClickListener {
val beer = filteredDataSet[vh.adapterPosition]
val activity = context as Activity
val transitionName = context.getString(R.string.transition_single_image)
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, view.image, transitionName)
if (beer.imageURL.isNotBlank()) {
val intent = Intent(context, SingleImageActivity::class.java)
intent.putExtra(Beer.BEER, GsonBuilder().create().toJson(beer, Beer::class.java))
ActivityCompat.startActivity(activity, intent, options.toBundle())
} else {
Utils.showToast(context, context.getString(R.string.no_image), Toast.LENGTH_SHORT)
}
}
return vh
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindBeer(filteredDataSet[position])
}
override fun getItemCount() = filteredDataSet.size
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(charSequence: CharSequence?): FilterResults {
val results = FilterResults()
//If there's nothing to filter on, return the original data for your list
if (charSequence == null || charSequence.isEmpty()) {
results.values = dataSet
results.count = dataSet.size
} else {
val filterResultsData = dataSet.filter {
it.name.toLowerCase().contains(charSequence)
|| it.brewer.toLowerCase().contains(charSequence)
|| it.brewer.toLowerCase().contains(charSequence)
|| it.percentage.toLowerCase().contains(charSequence)
|| it.kind.toLowerCase().contains(charSequence)
}
results.values = filterResultsData
results.count = filterResultsData.size
}
return results
}
override fun publishResults(charSequence: CharSequence, filterResults: FilterResults) {
filteredDataSet = filterResults.values as ArrayList<Beer>
notifyDataSetChanged()
}
}
}
internal inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bindBeer(beer: Beer) {
with(beer) {
itemView.name_textview.text = name
itemView.kind_textview.text = String.format("%s (%s)", kind, percentage)
itemView.brewer_textview.text = brewer
itemView.country_textview.text = country
itemView.rating_textview.text = rating
Glide.with(context).load(imageURL).into(itemView.image)
}
}
}
}
| gpl-3.0 | 1f32e92df4baa5738c942132a8310477 | 43 | 157 | 0.648471 | 5.145355 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/RedundantElseInWhenSpec.kt | 1 | 8853 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.test.KtTestCompiler
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object RedundantElseInWhenSpec : Spek({
val subject by memoized { RedundantElseInWhen() }
val wrapper by memoized(
factory = { KtTestCompiler.createEnvironment() },
destructor = { it.dispose() }
)
describe("RedundantElseInWhen rule") {
context("enum") {
it("reports when `when` expression used as statement contains `else` case when all cases already covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color) {
when (c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
else -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(actual).hasSize(1)
}
it("reports when `when` expression contains `else` case when all cases already covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color) {
val x = when (c) {
Color.BLUE -> 1
Color.GREEN -> 2
Color.RED -> 3
else -> 100
}
}
"""
val actual = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(actual).hasSize(1)
}
it("does not report when `when` expression contains `else` case when not all cases explicitly covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumPass(c: Color) {
when (c) {
Color.BLUE -> {}
Color.GREEN -> {}
else -> {}
}
val x = when (c) {
Color.BLUE -> 1
Color.GREEN -> 2
else -> 100
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
it("does not report when `when` expression does not contain else case") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumPassA(c: Color) {
when (c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
}
val x = when (c) {
Color.BLUE -> 1
Color.GREEN -> 2
Color.RED -> 3
}
}
fun whenOnEnumPassB(c: Color) {
when (c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
}
context("sealed classes") {
it("reports when `when` expression used as statement contains `else` case when all cases already covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant) {
when (v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
is Variant.VariantC -> {}
else -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(actual).hasSize(1)
}
it("reports when `when` expression contains `else` case when all cases already covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant) {
val x = when (v) {
is Variant.VariantA -> "a"
is Variant.VariantB -> "b"
is Variant.VariantC -> "c"
else -> "other"
}
}
"""
val actual = subject.compileAndLintWithContext(wrapper.env, code)
assertThat(actual).hasSize(1)
}
it("does not report when `when` expression contains `else` case when not all cases explicitly covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumPass(v: Variant) {
when (v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
else -> {}
}
val x = when (v) {
is Variant.VariantA -> "a"
is Variant.VariantB -> "b"
else -> "other"
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
it("does not report when `when` expression does not contain else case") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumPass(v: Variant) {
when (v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
}
context("standard when") {
it("does not report when `when` not checking for missing cases") {
val code = """
fun whenChecks() {
val x = 3
val s = "3"
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
Integer.parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
when (x) {
in 1..10 -> print("x is in the range")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
val y = when(s) {
is String -> s.startsWith("prefix")
else -> false
}
when {
x.equals(s) -> print("x equals s")
x.plus(3) == 4 -> print("x is 1")
else -> print("x is funny")
}
}
"""
assertThat(subject.compileAndLintWithContext(wrapper.env, code)).isEmpty()
}
}
}
})
| apache-2.0 | 8622bf058ad7a6eb990dd93d698b2aa8 | 35.432099 | 120 | 0.369931 | 6.080357 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/timetables/TimetableEditActivity.kt | 1 | 12430 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.timetables
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.EditText
import co.timetableapp.R
import co.timetableapp.TimetableApplication
import co.timetableapp.data.TimetableDbHelper
import co.timetableapp.data.handler.ClassTimeHandler
import co.timetableapp.data.handler.TermHandler
import co.timetableapp.data.handler.TimetableHandler
import co.timetableapp.data.query.Filters
import co.timetableapp.data.query.Query
import co.timetableapp.data.schema.ClassTimesSchema
import co.timetableapp.data.schema.TermsSchema
import co.timetableapp.model.ClassTime
import co.timetableapp.model.Term
import co.timetableapp.model.Timetable
import co.timetableapp.ui.base.ItemEditActivity
import co.timetableapp.ui.components.DateSelectorHelper
import co.timetableapp.util.UiUtils
import co.timetableapp.util.title
import com.satsuware.usefulviews.LabelledSpinner
import org.threeten.bp.LocalDate
/**
* An activity for the user to edit a [Timetable].
*
* @see TimetablesActivity
*/
class TimetableEditActivity : ItemEditActivity<Timetable>(), LabelledSpinner.OnItemChosenListener {
companion object {
private const val REQUEST_CODE_TERM_EDIT = 1
}
private var mIsFirst = false
private val mTimetableHandler = TimetableHandler(this)
private lateinit var mNameEditText: EditText
private lateinit var mStartDate: LocalDate
private lateinit var mStartDateHelper: DateSelectorHelper
private lateinit var mEndDate: LocalDate
private lateinit var mEndDateHelper: DateSelectorHelper
private var mWeekRotations = 0
private lateinit var mSchedulingSpinner: LabelledSpinner
private lateinit var mWeekRotationSpinner: LabelledSpinner
private lateinit var mTerms: ArrayList<Term>
private lateinit var mAdapter: TermsAdapter
override fun getLayoutResource() = R.layout.activity_timetable_edit
override fun handleExtras() {
super.handleExtras()
mIsFirst = (application as TimetableApplication).currentTimetable == null
}
override fun getTitleRes(isNewItem: Boolean) = if (isNewItem) {
R.string.title_activity_timetable_new
} else {
R.string.title_activity_timetable_edit
}
override fun setupLayout() {
mNameEditText = findViewById(R.id.editText_name) as EditText
if (!mIsNew) {
mNameEditText.setText(mItem!!.name)
}
setupDateTexts()
mSchedulingSpinner = findViewById(R.id.spinner_scheduling_type) as LabelledSpinner
mWeekRotationSpinner = findViewById(R.id.spinner_scheduling_detail) as LabelledSpinner
mSchedulingSpinner.onItemChosenListener = this
mWeekRotationSpinner.onItemChosenListener = this
mWeekRotations = if (mIsNew) 1 else mItem!!.weekRotations
updateSchedulingSpinners()
setupTermsList()
setupAddTermButton()
}
private fun setupDateTexts() {
mStartDate = mItem?.startDate ?: LocalDate.now()
mEndDate = mItem?.endDate ?: mStartDate.plusMonths(9)
mStartDateHelper = DateSelectorHelper(this, R.id.textView_start_date)
mStartDateHelper.setup(mStartDate) { _, date ->
mStartDate = date
mStartDateHelper.updateDate(mStartDate)
}
mEndDateHelper = DateSelectorHelper(this, R.id.textView_end_time)
mEndDateHelper.setup(mEndDate) { _, date ->
mEndDate = date
mEndDateHelper.updateDate(mEndDate)
}
}
private fun updateSchedulingSpinners() {
if (mWeekRotations == 1) {
mSchedulingSpinner.setSelection(0)
mWeekRotationSpinner.visibility = View.GONE
} else {
mSchedulingSpinner.setSelection(1)
mWeekRotationSpinner.visibility = View.VISIBLE
// e.g. weekRotations of 2 will be position 0 as in the string-array
mWeekRotationSpinner.setSelection(mWeekRotations - 2)
}
}
private fun setupTermsList() {
mTerms = getTermsForTimetable(findTimetableId())
mTerms.sort()
mAdapter = TermsAdapter(mTerms)
mAdapter.onItemClick { view, position ->
val intent = Intent(this, TermEditActivity::class.java)
intent.putExtra(ItemEditActivity.EXTRA_ITEM, mTerms[position])
intent.putExtra(TermEditActivity.EXTRA_TIMETABLE_ID, findTimetableId())
var bundle: Bundle? = null
if (UiUtils.isApi21()) {
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
view,
getString(R.string.transition_2))
bundle = options.toBundle()
}
ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_TERM_EDIT, bundle)
}
val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
with(recyclerView) {
setHasFixedSize(true)
layoutManager = object : LinearLayoutManager(this@TimetableEditActivity) {
override fun canScrollVertically() = false
}
adapter = mAdapter
}
}
private fun setupAddTermButton() {
val btnAddTerm = findViewById(R.id.button_add_term) as Button
btnAddTerm.setOnClickListener { view ->
val intent = Intent(this, TermEditActivity::class.java)
intent.putExtra(TermEditActivity.EXTRA_TIMETABLE_ID, findTimetableId())
var bundle: Bundle? = null
if (UiUtils.isApi21()) {
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
view,
getString(R.string.transition_2))
bundle = options.toBundle()
}
ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_TERM_EDIT, bundle)
}
}
override fun onItemChosen(labelledSpinner: View?, adapterView: AdapterView<*>?, itemView: View?,
position: Int, id: Long) {
when (labelledSpinner!!.id) {
R.id.spinner_scheduling_type -> {
val isFixedScheduling = position == 0
if (isFixedScheduling) {
mWeekRotations = 1
} else {
mWeekRotations = if (mIsNew || mItem!!.weekRotations == 1)
2
else
mItem!!.weekRotations
}
updateSchedulingSpinners()
}
R.id.spinner_scheduling_detail -> {
if (mWeekRotations != 1) { // only modify mWeekRotations if not fixed scheduling
mWeekRotations = position + 2 // as '2 weeks' is position 0
}
updateSchedulingSpinners()
}
}
}
override fun onNothingChosen(labelledSpinner: View?, adapterView: AdapterView<*>?) {}
private fun refreshList() {
mTerms.clear()
mTerms.addAll(getTermsForTimetable(findTimetableId()))
mTerms.sort()
mAdapter.notifyDataSetChanged()
}
private fun getTermsForTimetable(timetableId: Int): ArrayList<Term> {
val query = Query.Builder()
.addFilter(Filters.equal(TermsSchema.COL_TIMETABLE_ID, timetableId.toString()))
.build()
return TermHandler(this).getAllItems(query)
}
private fun findTimetableId() = mItem?.id ?: mTimetableHandler.getHighestItemId() + 1
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_TERM_EDIT) {
if (resultCode == Activity.RESULT_OK) {
refreshList()
}
}
}
override fun handleCloseAction() {
if (mIsFirst) {
Snackbar.make(
findViewById(R.id.rootView),
R.string.message_first_timetable_required,
Snackbar.LENGTH_SHORT
).show()
return
}
setResult(Activity.RESULT_CANCELED)
supportFinishAfterTransition()
}
override fun handleDoneAction() {
val name = mNameEditText.text.toString().title()
if (mStartDate == mEndDate) {
Snackbar.make(
findViewById(R.id.rootView),
R.string.message_start_time_equal_end,
Snackbar.LENGTH_SHORT
).show()
return
}
if (mStartDate.isAfter(mEndDate)) {
Snackbar.make(
findViewById(R.id.rootView),
R.string.message_start_time_after_end,
Snackbar.LENGTH_SHORT
).show()
return
}
if (!mIsNew) {
// Delete class times with an invalid week number
if (mWeekRotations < mItem!!.weekRotations) {
val helper = TimetableDbHelper.getInstance(this)
val cursor = helper.readableDatabase.query(
ClassTimesSchema.TABLE_NAME, null,
ClassTimesSchema.COL_WEEK_NUMBER + ">?",
arrayOf(mWeekRotations.toString()),
null, null, null
)
cursor.moveToFirst()
while (!cursor.isAfterLast) {
val classTime = ClassTime.from(cursor)
ClassTimeHandler(this).deleteItemWithReferences(classTime.id)
cursor.moveToNext()
}
cursor.close()
}
}
mItem = Timetable(findTimetableId(), name, mStartDate, mEndDate, mWeekRotations)
if (mIsNew) {
mTimetableHandler.addItem(mItem!!)
} else {
mTimetableHandler.replaceItem(mItem!!.id, mItem!!)
}
(application as TimetableApplication).setCurrentTimetable(this, mItem!!)
setResult(Activity.RESULT_OK)
supportFinishAfterTransition()
}
override fun handleDeleteAction() {
// There needs to be at least one timetable for the app to work
if (mTimetableHandler.getAllItems().size == 1) {
Snackbar.make(
findViewById(R.id.rootView),
R.string.message_first_timetable_required,
Snackbar.LENGTH_SHORT
).show()
return
}
AlertDialog.Builder(this)
.setTitle(R.string.delete_timetable)
.setMessage(R.string.delete_confirmation_timetable)
.setPositiveButton(R.string.action_delete) { _, _ ->
mTimetableHandler.deleteItemWithReferences(mItem!!.id)
// After the timetable has been deleted, change the current timetable
val newCurrentTimetable = mTimetableHandler.getAllItems()[0]
val timetableApp = application as TimetableApplication
timetableApp.setCurrentTimetable(baseContext, newCurrentTimetable)
setResult(Activity.RESULT_OK)
finish()
}
.setNegativeButton(R.string.action_cancel, null)
.show()
}
}
| apache-2.0 | ba65248e0a8b280f6c258890af86ff3f | 34.514286 | 100 | 0.624055 | 4.872599 | false | false | false | false |
rock3r/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Rule.kt | 1 | 2979 | package io.gitlab.arturbosch.detekt.api
import io.gitlab.arturbosch.detekt.api.internal.BaseRule
import io.gitlab.arturbosch.detekt.api.internal.PathFilters
import io.gitlab.arturbosch.detekt.api.internal.absolutePath
import io.gitlab.arturbosch.detekt.api.internal.createPathFilters
import io.gitlab.arturbosch.detekt.api.internal.isSuppressedBy
import org.jetbrains.kotlin.psi.KtFile
import java.nio.file.Paths
/**
* A rule defines how one specific code structure should look like. If code is found
* which does not meet this structure, it is considered as harmful regarding maintainability
* or readability.
*
* A rule is implemented using the visitor pattern and should be started using the visit(KtFile)
* function. If calculations must be done before or after the visiting process, here are
* two predefined (preVisit/postVisit) functions which can be overridden to setup/teardown additional data.
*/
abstract class Rule(
override val ruleSetConfig: Config = Config.empty,
ruleContext: Context = DefaultContext()
) : BaseRule(ruleContext), ConfigAware {
/**
* A rule is motivated to point out a specific issue in the code base.
*/
abstract val issue: Issue
/**
* An id this rule is identified with.
* Conventionally the rule id is derived from the issue id as these two classes have a coexistence.
*/
final override val ruleId: RuleId get() = issue.id
/**
* List of rule ids which can optionally be used in suppress annotations to refer to this rule.
*/
val aliases: Set<String> get() = valueOrDefault("aliases", defaultRuleIdAliases)
/**
* The default names which can be used instead of this #ruleId to refer to this rule in suppression's.
*
* When overriding this property make sure to meet following structure for detekt-generator to pick
* it up and generate documentation for aliases:
*
* override val defaultRuleIdAliases = setOf("Name1", "Name2")
*/
open val defaultRuleIdAliases: Set<String> = emptySet()
internal val ruleSetId: RuleId? get() = ruleSetConfig.parentPath
/**
* Rules are aware of the paths they should run on via configuration properties.
*/
open val filters: PathFilters? by lazy(LazyThreadSafetyMode.NONE) {
createPathFilters()
}
override fun visitCondition(root: KtFile): Boolean =
active &&
shouldRunOnGivenFile(root) &&
!root.isSuppressedBy(ruleId, aliases, ruleSetId)
private fun shouldRunOnGivenFile(root: KtFile) =
filters?.isIgnored(Paths.get(root.absolutePath()))?.not() ?: true
/**
* Simplified version of [Context.report] with rule defaults.
*/
fun report(finding: Finding) {
report(finding, aliases, ruleSetId)
}
/**
* Simplified version of [Context.report] with rule defaults.
*/
fun report(findings: List<Finding>) {
report(findings, aliases, ruleSetId)
}
}
| apache-2.0 | c5106841abb674c84b8caedbecdd3442 | 35.777778 | 107 | 0.706613 | 4.380882 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/SlippyMapMath.kt | 1 | 4547 | package de.westnordost.streetcomplete.util
import de.westnordost.streetcomplete.data.osm.mapdata.BoundingBox
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.data.osm.mapdata.splitAt180thMeridian
import kotlinx.serialization.Serializable
import kotlin.math.*
/** X and Y position of a tile */
@Serializable
data class TilePos(val x: Int, val y:Int) {
/** Returns this tile rect as a bounding box */
fun asBoundingBox(zoom: Int): BoundingBox {
return BoundingBox(
tile2lat(y + 1, zoom),
tile2lon(x, zoom),
tile2lat(y, zoom),
tile2lon(x + 1, zoom)
)
}
fun toTilesRect() = TilesRect(x,y,x,y)
}
/** Returns the minimum rectangle of tiles that encloses all the tiles */
fun Collection<TilePos>.minTileRect(): TilesRect? {
if (isEmpty()) return null
val right = maxByOrNull { it.x }!!.x
val left = minByOrNull { it.x }!!.x
val bottom = maxByOrNull { it.y }!!.y
val top = minByOrNull { it.y }!!.y
return TilesRect(left, top, right, bottom)
}
/** Returns the tile that encloses the position at the given zoom level */
fun LatLon.enclosingTilePos(zoom: Int): TilePos {
return TilePos(
lon2tile(((longitude + 180) % 360) - 180, zoom),
lat2tile(latitude, zoom)
)
}
/** A rectangle that represents containing all tiles from left bottom to top right */
@Serializable
data class TilesRect(val left: Int, val top: Int, val right: Int, val bottom: Int) {
init {
require(left <= right && top <= bottom)
}
/** size of the tiles rect */
val size: Int get() = (bottom - top + 1) * (right - left + 1)
/** Returns all the individual tiles contained in this tile rect as an iterable sequence */
fun asTilePosSequence(): Sequence<TilePos> = sequence {
for (y in top..bottom) {
for (x in left..right) {
yield(TilePos(x, y))
}
}
}
/** Returns this tile rect as a bounding box */
fun asBoundingBox(zoom: Int): BoundingBox {
return BoundingBox(
tile2lat(bottom + 1, zoom),
tile2lon(left, zoom),
tile2lat(top, zoom),
tile2lon(right + 1, zoom)
)
}
}
/** Returns the bounding box of the tile rect at the given zoom level that encloses this bounding box.
* In other words, it expands this bounding box to fit to the tile boundaries.
* If this bounding box crosses the 180th meridian, it'll take only the first half of the bounding
* box*/
fun BoundingBox.asBoundingBoxOfEnclosingTiles(zoom: Int): BoundingBox {
return enclosingTilesRect(zoom).asBoundingBox(zoom)
}
/** Returns the tile rect that enclose this bounding box at the given zoom level. If this bounding
* box crosses the 180th meridian, it'll take only the first half of the bounding box */
fun BoundingBox.enclosingTilesRect(zoom: Int): TilesRect {
return if (crosses180thMeridian) {
splitAt180thMeridian().first().enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom)
}
else {
enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom)
}
}
private fun BoundingBox.enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom: Int): TilesRect {
/* TilesRect.asBoundingBox returns a bounding box that intersects in line with the neighbouring
* tiles to ensure that there is no space between the tiles. So when converting a bounding box
* that exactly fits a tiles rect back to a tiles rect, it must be made smaller by the tiniest
* amount */
val notTheNextTile = 1e-7
val min = LatLon(min.latitude + notTheNextTile, min.longitude + notTheNextTile)
val max = LatLon(max.latitude - notTheNextTile, max.longitude - notTheNextTile)
val minTile = min.enclosingTilePos(zoom)
val maxTile = max.enclosingTilePos(zoom)
return TilesRect(minTile.x, maxTile.y, maxTile.x, minTile.y)
}
private fun tile2lon(x: Int, zoom: Int): Double =
x / numTiles(zoom).toDouble() * 360.0 - 180.0
private fun tile2lat(y: Int, zoom: Int): Double =
atan(sinh(PI - 2.0 * PI * y / numTiles(zoom))).toDegrees()
private fun lon2tile(lon: Double, zoom: Int): Int =
(numTiles(zoom) * (lon + 180.0) / 360.0).toInt()
private fun lat2tile(lat: Double, zoom: Int): Int =
(numTiles(zoom) * (1.0 - asinh(tan(lat.toRadians())) / PI) / 2.0).toInt()
private fun numTiles(zoom: Int): Int = 1 shl zoom
private fun Double.toDegrees() = this / PI * 180.0
private fun Double.toRadians() = this / 180.0 * PI
| gpl-3.0 | f67210f40e05ad29cbdeb220e8a4b18e | 36.270492 | 102 | 0.673191 | 3.808208 | false | false | false | false |
huhanpan/smart | app/src/main/java/com/etong/smart/Main/Login/RegisterActivity.kt | 1 | 9417 | package com.etong.smart.Main.Login
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.Toolbar
import android.widget.Button
import android.widget.EditText
import com.alibaba.fastjson.JSONException
import com.alibaba.fastjson.JSONObject
import com.etong.smart.Main.MainActivity
import com.etong.smart.Other.AESCrypt
import com.etong.smart.Other.BaseActivity
import com.etong.smart.Other.Service
import com.etong.smart.Other.Storage
import com.etong.smart.R
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
class RegisterActivity : BaseActivity() {
private var mEditTextAccount: EditText? = null
private var mEditTextPhone: EditText? = null
private var mEditTextPwd: EditText? = null
private var mEditTextCode: EditText? = null
private var mSendCode: Button? = null //发送验证码Button
private var time = 60
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
mEditTextAccount = findViewById(R.id.etAccount) as EditText
mEditTextPhone = findViewById(R.id.et_phone) as EditText
mEditTextPwd = findViewById(R.id.et_pwd) as EditText
mEditTextCode = findViewById(R.id.et_code) as EditText
mSendCode = findViewById(R.id.button7) as Button
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
toolbar.setNavigationOnClickListener { v -> finish() }
val account = intent.getStringExtra("account")
if (account?.length == 11 && account[0] == '1') {
mEditTextPhone?.setText(account)
mEditTextAccount?.isFocusable = true
mEditTextAccount?.requestFocus()
} else {
mEditTextAccount?.setText(account)
mEditTextPhone?.isFocusable = true
mEditTextPhone?.requestFocus()
}
findViewById(R.id.edit_user_icon).setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, 1)
}
//发送code
mSendCode!!.setOnClickListener { v ->
if (mEditTextPhone!!.text.length < 11) {
Snackbar.make(v, "手机号不正确,请重新输入", Snackbar.LENGTH_SHORT).show()
} else {
Service.sendCode(mEditTextPhone?.text.toString(), false)
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
t?.printStackTrace()
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
try {
val json = JSONObject.parseObject(response?.body())
if (json.getIntValue("status") == 1) setTiemr() else {
Snackbar.make(v, json.getString("error"), Snackbar.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Snackbar.make(v, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show()
}
}
})
}
}
//激活按钮
findViewById(R.id.button).setOnClickListener {
if (mEditTextPhone!!.text.length < 11) {
Snackbar.make(it, "手机号不正确,请重新输入", Snackbar.LENGTH_SHORT).show()
} else if (mEditTextPwd!!.text.length < 6) {
Snackbar.make(it, "密码太短,请重新输入", Snackbar.LENGTH_SHORT).show()
} else if (mEditTextCode!!.text.length != 4) {
Snackbar.make(it, "验证码不正确,请重新输入", Snackbar.LENGTH_SHORT).show()
} else {
Service.activeAccount(mEditTextPwd?.text.toString(), mEditTextCode?.text.toString())
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
t?.printStackTrace()
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
try {
val jsonObj = JSONObject.parseObject(response?.body())
if (jsonObj.getInteger("status") == 1) {
val snackbar = Snackbar.make(it, "激活成功", Snackbar.LENGTH_SHORT)
snackbar.show()
snackbar.setCallback(object : Snackbar.Callback() {
override fun onDismissed(snackbar: Snackbar?, event: Int) {
val key = System.currentTimeMillis().toString()
Service.login(key, mEditTextAccount?.text.toString(), mEditTextPwd?.text.toString())
.enqueue(object : Callback<String> {
override fun onFailure(call: Call<String>?, t: Throwable?) {
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
try {
val json = JSONObject.parseObject(response?.body())
val responseData = json.getString("data")
if (responseData == null) {
Snackbar.make(it, json.getString("error"), Snackbar.LENGTH_SHORT).show()
} else {
val originalJson = JSONObject.parseObject(AESCrypt.decrypt(key, responseData))
for (i in originalJson) {
when (i.key) {
"token" -> Storage.saveToken(i.value.toString())
"is_admin" -> Storage.saveIsAdmin(i.value == 1)
"upload_token" -> Storage.saveQINIU(i.value.toString())
}
}
Storage.savePwd(mEditTextPwd?.text.toString())
startActivity(Intent(this@RegisterActivity, MainActivity::class.java))
finish()
}
} catch (e: JSONException) {
Snackbar.make(it, "服务器错误,请稍后再试", Snackbar.LENGTH_SHORT).show()
}
}
})
}
})
} else {
Snackbar.make(it, jsonObj.getString("error"), Snackbar.LENGTH_SHORT).show()
}
} catch (e: JSONException) {
Snackbar.make(it, "服务器出错,请稍后再试", Snackbar.LENGTH_SHORT).show()
}
}
})
}
}
}
//设置计时器
private fun setTiemr() {
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
if (time > 0) {
runOnUiThread {
mSendCode!!.setText(time.toString() + "s")
mSendCode!!.isEnabled = false
}
time--
} else {
runOnUiThread {
mSendCode!!.text = "重发验证码"
mSendCode!!.isEnabled = true
}
time = 60
timer.cancel()
}
}
}, 0, 1000)
}
}
| gpl-2.0 | ab1f59769a7acd93c8aea4925bb7b51a | 50.238889 | 150 | 0.422856 | 6.05979 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/test/kotlin/ReadTest.kt | 1 | 14152 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import org.junit.Test
import java.io.File
import java.util.regex.Matcher
import java.util.regex.Pattern
class ReadTest {
data class Trigger(
var trigger: String = "",
var actions: MutableList<String> = mutableListOf()
)
data class Import(
var initrc: String = ""
)
data class Service(
var name: String = "",
var cmd: String = "",
var theClass: String = "default",
var theUser: String? = null,
var theGroup: String? = null,
var theSeclabel: String? = null,
var theMiscAttr: MutableList<String> = mutableListOf(),
var theCaps: MutableList<String> = mutableListOf(),
var theSocket: String? = null,
var theWritePid: String? = null,
var theKeycodes: String? = null,
var thePriority: Int? = null,
var theIOPriority: String? = null,
var theOnRestart: MutableList<String> = mutableListOf()
)
fun parseConfig(inRootDir: String, inPath: String,
triggers: MutableList<Trigger>,
services: MutableList<Service>) {
if (!File(inRootDir + inPath).exists()) {
println("Parsing " + inPath + " fail: 404");
}
if (File(inRootDir + inPath).isFile()) {
parseConfigFile(inRootDir, inPath, triggers, services)
} else if (File(inRootDir + inPath).isDirectory()) {
parseConfigDir(inRootDir, inPath, triggers, services)
}
}
fun parseConfigDir(inRootDir: String, inPath: String,
triggers: MutableList<Trigger>,
services: MutableList<Service>) {
println("Parsing directory $inPath ...")
File(inRootDir + inPath).listFiles().forEach {
parseConfig(inRootDir,
it.path.substring(inRootDir.length - 1),
triggers, services)
}
}
fun parseConfigFile(inRootDir: String, inPath: String,
triggers: MutableList<Trigger>,
services: MutableList<Service>) {
if (!File(inRootDir + inPath).exists()) {
println("Parsing $inPath fail: 404")
return
}
println("Parsing file $inPath ...")
var imports: MutableList<Import> = mutableListOf()
var aTrigger: Trigger? = null
var aService: Service? = null
var aImport: Import? = null
var toBeContinued = false
val lines = File(inRootDir + inPath).readLines()
for (item in lines) {
val line = item.trim();
//comment
if (line.startsWith("#") || line.isEmpty()) {
continue
}
//continue
if (toBeContinued) {
if (line.endsWith("\\")) {
aService!!.cmd += " "
aService!!.cmd += line.substring(0, line.length - 1)
println(" CONTINUE:" + line.substring(0, line.length - 1))
} else {
toBeContinued = false
aService!!.cmd += " "
aService!!.cmd += line
println(" END :$line")
}
continue
}
val finderOn = Pattern.compile("^(on)\\s+(\\S+.*$)").matcher(line)
val finderService = Pattern.compile("^service\\s+(\\S+)\\s+(.*$)").matcher(line)
val finderImport = Pattern.compile("^import\\s+(\\S+)$").matcher(line)
if (finderOn.matches() || finderService.matches() || finderImport.matches()) {
//flush start >>
aTrigger?.let { /* println("[add] " + aTrigger); */ triggers.add(aTrigger!!); aTrigger = null }
aService?.let { /* println("[add] " + aService); */ services.add(aService!!); aService = null }
aImport?.let { /* println("[add] " + aImport); */ imports.add(aImport!!); aImport = null }
// << flush end
}
finderOn.reset()
finderService.reset()
finderImport.reset()
if (finderOn.find()) {
//println(" |on| " + line)
//println(" group.cnt = " + finderOn.groupCount())
//println(" " + line.substring(finderOn.start(), finderOn.end()))
//println(" >" + finderOn.group(1))
//println(" >" + finderOn.group(2))
aTrigger = Trigger(trigger = finderOn.group(2))
} else if (finderService.find()) {
aService = Service()
aService!!.name = finderService.group(1)
aService!!.cmd = finderService.group(2)
if (finderService.group(2).endsWith("\\")) { //remove trailing slash
toBeContinued = true
aService!!.cmd = aService!!.cmd.substring(0, aService!!.cmd.length - 1)
}
} else if (finderImport.find()) {
aImport = Import()
aImport!!.initrc = finderImport.group(1)
if (aImport!!.initrc.startsWith("/")) {
aImport!!.initrc = aImport!!.initrc.substring(1)
} else {
//do nothing
}
val ro_hardware = "\${ro.hardware}"
val ro_zygote = "\${ro.zygote}"
aImport!!.initrc = aImport!!.initrc.replace(ro_hardware, "sequoia")
aImport!!.initrc = aImport!!.initrc.replace(ro_zygote, "zygote32")
} else {
if (aTrigger != null) {
aTrigger!!.actions.add(line)
} else if (aService != null) {
//class
var bParsed = false
lateinit var mm: Matcher
if (!bParsed) {
mm = Pattern.compile("^class\\s+(.*)").matcher(line)
if (mm.matches()) {
aService!!.theClass = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//user
mm = Pattern.compile("^user\\s+(.*)").matcher(line)
if (mm.matches()) {
aService!!.theUser = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//capabilities
mm = Pattern.compile("^capabilities\\s+(.*)").matcher(line)
if (mm.matches()) {
aService!!.theCaps.add(mm.group(1))
bParsed = true
}
}
if (!bParsed) {
//group
mm = Pattern.compile("^group\\s+(.*)").matcher(line)
if (mm.matches()) {
aService!!.theGroup = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//seclabel
mm = Pattern.compile("^seclabel\\s+(.*)").matcher(line)
if (mm.matches()) {
aService!!.theSeclabel = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//writepid
mm = Pattern.compile("^writepid\\s+(.*)$").matcher(line)
if (mm.matches()) {
aService!!.theWritePid = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//onrestart
mm = Pattern.compile("^onrestart\\s+(.*)$").matcher(line)
if (mm.matches()) {
aService!!.theOnRestart.add(mm.group(1))
bParsed = true
}
}
if (!bParsed) {
//socket
mm = Pattern.compile("^socket\\s+(.*)$").matcher(line)
if (mm.matches()) {
aService!!.theSocket = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//ioprio
mm = Pattern.compile("^ioprio\\s+(.*)$").matcher(line)
if (mm.matches()) {
aService!!.theIOPriority = mm.group(1)
bParsed = true
}
}
if (!bParsed) {
//priority
mm = Pattern.compile("^priority\\s+(\\S+)$").matcher(line)
if (mm.matches()) {
aService!!.thePriority = Integer.parseInt(mm.group(1))
bParsed = true
}
}
if (!bParsed) {
//check space
mm = Pattern.compile("^\\S+$").matcher(line)
if (mm.matches()) {
aService!!.theMiscAttr.add(line)
bParsed = true
}
}
if (!bParsed) {
println("<< Dangling << $line")
}
} else {
println("<< Dangling << $line")
}
}
}
//flush start >>
aTrigger?.let { /* println("[add] " + aTrigger); */ triggers.add(aTrigger!!); aTrigger = null }
aService?.let { /* println("[add] " + aService); */ services.add(aService!!); aService = null }
aImport?.let { /* println("[add] " + aImport); */ imports.add(aImport!!); aImport = null }
// << flush end
imports.forEach { println(it) }
//parse imports again
val iteratorImport: Iterator<Import> = imports.iterator()
while (iteratorImport.hasNext()) {
val item: Import = iteratorImport.next()
parseConfigFile(inRootDir, item.initrc, triggers, services)
}
println("Parsing file $inPath done")
}
fun queueEventTrigger(inServices: MutableList<Service>,
inTriggers: List<Trigger>, inTriggerName: String,
inIndent: String = "") {
val aPre = inIndent
inTriggers.filter { it.trigger == inTriggerName }.forEach { aTrigger ->
println(aPre + " (on+${aTrigger.trigger})")
aTrigger.actions.forEach { aAction ->
aAction.executeCmd(inServices, inTriggers, aPre + " ")
}
}
}
fun String.executeCmd(inServices: MutableList<Service>,
inTriggers: List<Trigger>, inIndent: String) {
val aPre = inIndent + " "
if (this.startsWith("trigger ")) {
println(aPre + "|-- " + this)
queueEventTrigger(inServices, inTriggers, this.substring(8).trim(), aPre + "| ")
} else if (this.startsWith("chmod")) {
} else if (this.startsWith("chown")) {
} else if (this.startsWith("mkdir")) {
} else if (this.startsWith("write")) {
} else if (Pattern.compile("class_start\\s+\\S+").matcher(this).find()) {
println(aPre + "|-- " + this)
val m = Pattern.compile("class_start\\s+(\\S+)$").matcher(this)
if (m.find()) {
inServices
.filter {
it.theClass.split(" ").contains(m.group(1))
}
.forEach {
println(aPre + "| \\-- Starting " + it.name + "...")
}
} else {
println("error")
}
} else if (this.startsWith("start")) {
println("$aPre|-- $this")
println("""$aPre| \-- Starting ${this.substring(5).trim()}...""")
} else {
println(aPre + "|-- " + this)
}
}
@Test
fun parseTest() {
System.out.println(System.getProperty("user.dir"))
var gTriggers: MutableList<Trigger> = mutableListOf()
var gServices: MutableList<Service> = mutableListOf()
parseConfig("__temp/", "/init.rc", gTriggers, gServices)
parseConfig("__temp/", "/system/etc/init", gTriggers, gServices)
parseConfig("__temp/", "/vendor/etc/init", gTriggers, gServices)
parseConfig("__temp/", "/odm/etc/init", gTriggers, gServices)
gTriggers.forEach { println(it) }
gServices.forEach { println(it) }
println("Trigger count:" + gTriggers.size)
println("Service count:" + gServices.size)
queueEventTrigger(gServices, gTriggers, "early-init")
queueEventTrigger(gServices, gTriggers, "init")
queueEventTrigger(gServices, gTriggers, "late-init")
// println(">> mount_all() returned 0, trigger nonencrypted")
// queueEventTrigger(gServices, gTriggers, "nonencrypted")
}
} | apache-2.0 | 4dee6199d3236928e9ff1db838321cbb | 41.374251 | 111 | 0.455271 | 4.725209 | false | false | false | false |
binaryfoo/emv-bertlv | src/main/java/io/github/binaryfoo/decoders/apdu/ResponseCode.kt | 1 | 1032 | package io.github.binaryfoo.decoders.apdu
import io.github.binaryfoo.res.ClasspathIO
/**
* Maps the two status words (SW1, SW2) included in an R-APDU to a type and description.
*/
data class ResponseCode(val sw1: String, val sw2: String, val `type`: String, val description: String) {
fun getHex(): String {
return sw1 + sw2
}
companion object {
private val codes = ClasspathIO.readLines("r-apdu-status.txt").map { line ->
ResponseCode(line.substring(0, 2), line.substring(3, 5), line.substring(6, 7), line.substring(8))
}
@JvmStatic
fun lookup(hex: String): ResponseCode {
val sw1 = hex.substring(0, 2)
val sw2 = hex.substring(2, 4)
for (code in codes) {
if (sw1 == code.sw1) {
if ("XX" == code.sw2) {
return code
}
if ("--" == code.sw2) {
continue
}
if (sw2 == code.sw2) {
return code
}
}
}
return ResponseCode(sw1, sw2, "", "Unknown")
}
}
}
| mit | b974d5981f1967d232e7a79f9aaf830c | 24.8 | 104 | 0.562984 | 3.498305 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/viewmodel/DesignersViewModel.kt | 1 | 3667 | package com.boardgamegeek.ui.viewmodel
import android.app.Application
import android.content.SharedPreferences
import androidx.lifecycle.*
import com.boardgamegeek.db.DesignerDao
import com.boardgamegeek.entities.PersonEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.repository.DesignerRepository
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
class DesignersViewModel(application: Application) : AndroidViewModel(application) {
enum class SortType {
NAME, ITEM_COUNT, WHITMORE_SCORE
}
private val designerRepository = DesignerRepository(getApplication())
private val prefs: SharedPreferences by lazy { application.preferences() }
private val _sort = MutableLiveData<DesignersSort>()
val sort: LiveData<DesignersSort>
get() = _sort
private val _progress = MutableLiveData<Pair<Int, Int>>()
val progress: LiveData<Pair<Int, Int>>
get() = _progress
private var isCalculating = AtomicBoolean()
init {
val initialSort = if (prefs.isStatusSetToSync(COLLECTION_STATUS_RATED))
SortType.WHITMORE_SCORE
else
SortType.ITEM_COUNT
sort(initialSort)
}
val designers = _sort.switchMap {
liveData {
val designers = designerRepository.loadDesigners(it.sortBy)
emit(designers)
val lastCalculation = prefs[PREFERENCES_KEY_STATS_CALCULATED_TIMESTAMP_DESIGNERS, 0L] ?: 0L
if (lastCalculation.isOlderThan(1, TimeUnit.HOURS) &&
isCalculating.compareAndSet(false, true)
) {
designerRepository.calculateWhitmoreScores(designers, _progress)
emit(designerRepository.loadDesigners(it.sortBy))
isCalculating.set(false)
}
}
}
fun sort(sortType: SortType) {
if (_sort.value?.sortType != sortType) {
_sort.value = when (sortType) {
SortType.NAME -> DesignersSort.ByName()
SortType.ITEM_COUNT -> DesignersSort.ByItemCount()
SortType.WHITMORE_SCORE -> DesignersSort.ByWhitmoreScore()
}
}
}
fun refresh() {
_sort.value?.let { _sort.value = it }
}
fun getSectionHeader(designer: PersonEntity?): String {
return _sort.value?.getSectionHeader(designer).orEmpty()
}
sealed class DesignersSort {
abstract val sortType: SortType
abstract val sortBy: DesignerDao.SortType
abstract fun getSectionHeader(designer: PersonEntity?): String
class ByName : DesignersSort() {
override val sortType = SortType.NAME
override val sortBy = DesignerDao.SortType.NAME
override fun getSectionHeader(designer: PersonEntity?): String {
return if (designer?.name == "(Uncredited)") "-"
else designer?.name.firstChar()
}
}
class ByItemCount : DesignersSort() {
override val sortType = SortType.ITEM_COUNT
override val sortBy = DesignerDao.SortType.ITEM_COUNT
override fun getSectionHeader(designer: PersonEntity?): String {
return (designer?.itemCount ?: 0).orderOfMagnitude()
}
}
class ByWhitmoreScore : DesignersSort() {
override val sortType = SortType.WHITMORE_SCORE
override val sortBy = DesignerDao.SortType.WHITMORE_SCORE
override fun getSectionHeader(designer: PersonEntity?): String {
return (designer?.whitmoreScore ?: 0).orderOfMagnitude()
}
}
}
}
| gpl-3.0 | 8a108150bba4659d2f6111a8d21765a7 | 34.95098 | 103 | 0.64276 | 4.812336 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/catalog/LanternCatalogKeyBuilder.kt | 1 | 1414 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.catalog
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.plugin.PluginContainer
import org.lanternpowered.api.plugin.id
import org.lanternpowered.api.key.NamespacedKey.Builder as NamespacedKeyBuilder
class LanternNamespacedKeyBuilder : NamespacedKeyBuilder {
private var namespace: String? = null
private var value: String? = null
override fun namespace(namespace: String): NamespacedKeyBuilder = apply { this.namespace = namespace }
override fun namespace(container: PluginContainer): NamespacedKeyBuilder = namespace(container.id)
override fun value(value: String): NamespacedKeyBuilder = apply { this.value = value }
override fun build(): NamespacedKey {
val namespace = checkNotNull(this.namespace) { "The namespace must be set" }
val value = checkNotNull(this.value) { "The value must be set" }
return LanternNamespacedKey(namespace, value)
}
override fun reset(): NamespacedKeyBuilder = apply {
this.namespace = null
this.value = null
}
}
| mit | d9f3e3cf71eb9c79259616cc19571780 | 37.216216 | 106 | 0.734795 | 4.460568 | false | false | false | false |
googleapis/gapic-generator-kotlin | generator/src/main/kotlin/com/google/api/kotlin/generator/grpc/Stubs.kt | 1 | 12668 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.kotlin.generator.grpc
import com.google.api.kotlin.GeneratedSource
import com.google.api.kotlin.GeneratorContext
import com.google.api.kotlin.generator.grpc.Stubs.Companion.PROP_STUBS_API
import com.google.api.kotlin.generator.grpc.Stubs.Companion.PROP_STUBS_OPERATION
import com.google.api.kotlin.types.GrpcTypes
import com.google.protobuf.DescriptorProtos
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
/**
* Generates a type that holder the gRPC stubs that will be used by the client.
*
* The client will the use [PROP_STUBS_API] and [PROP_STUBS_OPERATION] to make API calls.
*/
internal interface Stubs {
/** Create a stub */
fun generate(context: GeneratorContext, by: AnnotationSpec): GeneratedSource
/** Creates a nested type that will be used to hold the gRPC stubs used by the client */
fun generateHolderType(context: GeneratorContext): TypeSpec
/** Gets the type name of the [generate]. */
fun getStubTypeName(context: GeneratorContext): TypeName
/** Gets the type name of the api type in the [generateHolderType]. */
fun getApiStubType(context: GeneratorContext): ParameterizedTypeName
/** Gets the type name of the operation type in the [generateHolderType]. */
fun getOperationsStubType(context: GeneratorContext): ParameterizedTypeName
companion object {
const val PROP_STUBS_API = "api"
const val PROP_STUBS_OPERATION = "operation"
const val PARAM_REQUEST = "request"
const val PARAM_RESPONSE_OBSERVER = "responseObserver"
const val CLASS_STUBS = "Stubs"
}
}
internal class StubsImpl : Stubs {
override fun generate(context: GeneratorContext, by: AnnotationSpec): GeneratedSource {
// create type
val type = createType(context, by)
// add static imports
val imports = listOf(
ClassName("io.grpc.MethodDescriptor", "generateFullMethodName"),
ClassName("io.grpc.stub.ClientCalls", "futureUnaryCall"),
ClassName("io.grpc.stub.ClientCalls", "asyncBidiStreamingCall"),
ClassName("io.grpc.stub.ClientCalls", "asyncClientStreamingCall"),
ClassName("io.grpc.stub.ClientCalls", "asyncServerStreamingCall"),
GrpcTypes.StatusCode
)
// put it all together
return GeneratedSource(
context.className.packageName,
getStubTypeName(context).simpleName,
types = listOf(type),
imports = imports
)
}
// creates the base class type
private fun createType(context: GeneratorContext, by: AnnotationSpec): TypeSpec {
val className = getStubTypeName(context)
val type = TypeSpec.classBuilder(className)
.addAnnotation(by)
.superclass(GrpcTypes.AbstractStub(className))
.addSuperclassConstructorParameter("channel", GrpcTypes.Channel)
.addSuperclassConstructorParameter("callOptions", GrpcTypes.CallOptions)
// and constructor
type.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter("channel", GrpcTypes.Channel)
.addParameter(
ParameterSpec.builder("callOptions", GrpcTypes.CallOptions)
.defaultValue("%T.DEFAULT", GrpcTypes.CallOptions)
.build()
)
.build()
)
// add the build method from the superclass
type.addFunction(
FunSpec.builder("build")
.addModifiers(KModifier.OVERRIDE)
.addParameter("channel", GrpcTypes.Channel)
.addParameter("callOptions", GrpcTypes.CallOptions)
.returns(className)
.addStatement("return %T(channel, callOptions)", className)
.build()
)
// generate a method descriptor for each method
type.addProperties(context.service.methodList.map {
createMethodDescriptor(context, it)
})
// add stub methods
type.addFunctions(context.service.methodList.map { createStubMethod(context, it) })
return type.build()
}
// creates a method descriptor
private fun createMethodDescriptor(
context: GeneratorContext,
method: DescriptorProtos.MethodDescriptorProto
): PropertySpec {
val inputType = context.typeMap.getKotlinType(method.inputType)
val outputType = context.typeMap.getKotlinType(method.outputType)
val type = GrpcTypes.MethodDescriptor(inputType, outputType)
// create the property
val prop = PropertySpec.builder(descriptorPropertyName(method), type)
.addModifiers(KModifier.PRIVATE)
// determine method type
val methodType = when {
method.hasServerStreaming() && method.hasClientStreaming() -> "BIDI_STREAMING"
method.hasClientStreaming() -> "CLIENT_STREAMING"
method.hasServerStreaming() -> "SERVER_STREAMING"
else -> "UNARY"
}
// determine marshaller to use (lite or normal)
val marshallerType = if (context.commandLineOptions.lite) {
GrpcTypes.ProtoLiteUtils
} else {
GrpcTypes.ProtoUtils
}
// create the initializer
val init = CodeBlock.of(
"""
|%T.newBuilder<%T, %T>()
| .setType(%T.%L)
| .setFullMethodName(generateFullMethodName(%S, %S))
| .setSampledToLocalTracing(true)
| .setRequestMarshaller(%T.marshaller(
| %T.getDefaultInstance()))
| .setResponseMarshaller(%T.marshaller(
| %T.getDefaultInstance()))
| .build()
|""".trimMargin(),
type.rawType, inputType, outputType,
GrpcTypes.MethodDescriptorType, methodType,
"${context.proto.`package`}.${context.service.name}", method.name,
marshallerType,
inputType,
marshallerType,
outputType
)
// wrap it in a lazy delegate
prop.delegate(
"""
|lazy·{
|%L
|}""".trimMargin(),
init
)
return prop.build()
}
// create the API method for the stub type
private fun createStubMethod(
context: GeneratorContext,
method: DescriptorProtos.MethodDescriptorProto
): FunSpec {
val func = FunSpec.builder(method.name.decapitalize())
val inputType = context.typeMap.getKotlinType(method.inputType)
val outputType = context.typeMap.getKotlinType(method.outputType)
// set return (if needed)
val returnType = when {
method.hasClientStreaming() -> GrpcTypes.StreamObserver(inputType)
method.hasServerStreaming() -> null
else -> GrpcTypes.Guava.ListenableFuture(outputType)
}
returnType?.let { func.returns(it) }
// add parameters and build method body
when {
method.hasServerStreaming() && method.hasClientStreaming() -> {
func.addParameter(
Stubs.PARAM_RESPONSE_OBSERVER, GrpcTypes.StreamObserver(outputType)
)
func.addStatement(
"""
|return asyncBidiStreamingCall(
| channel.newCall(%L, callOptions),
| %L
|)
""".trimMargin(),
descriptorPropertyName(method),
Stubs.PARAM_RESPONSE_OBSERVER
)
}
method.hasServerStreaming() -> {
func.addParameter(Stubs.PARAM_REQUEST, inputType)
func.addParameter(
Stubs.PARAM_RESPONSE_OBSERVER, GrpcTypes.StreamObserver(outputType)
)
func.addStatement(
"""
|return asyncServerStreamingCall(
| channel.newCall(%L, callOptions),
| %L,
| %L
|)
""".trimMargin(),
descriptorPropertyName(method),
Stubs.PARAM_REQUEST,
Stubs.PARAM_RESPONSE_OBSERVER
)
}
method.hasClientStreaming() -> {
func.addParameter(
Stubs.PARAM_RESPONSE_OBSERVER, GrpcTypes.StreamObserver(outputType)
)
func.addStatement(
"""
|return asyncClientStreamingCall(
| channel.newCall(%L, callOptions),
| %L
|)
""".trimMargin(),
descriptorPropertyName(method),
Stubs.PARAM_RESPONSE_OBSERVER
)
}
else -> {
func.addParameter(Stubs.PARAM_REQUEST, inputType)
func.addStatement(
"""
|return futureUnaryCall(
| channel.newCall(%L, callOptions),
| %L
|)
|""".trimMargin(),
descriptorPropertyName(method),
Stubs.PARAM_REQUEST
)
}
}
return func.build()
}
private fun descriptorPropertyName(method: DescriptorProtos.MethodDescriptorProto) =
"${method.name.decapitalize()}Descriptor"
override fun generateHolderType(context: GeneratorContext): TypeSpec {
val apiType = getApiStubType(context)
val opType = getOperationsStubType(context)
return TypeSpec.classBuilder(Stubs.CLASS_STUBS)
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter(Stubs.PROP_STUBS_API, apiType)
.addParameter(Stubs.PROP_STUBS_OPERATION, opType)
.build()
)
.addProperty(
PropertySpec.builder(Stubs.PROP_STUBS_API, apiType)
.initializer(Stubs.PROP_STUBS_API)
.build()
)
.addProperty(
PropertySpec.builder(Stubs.PROP_STUBS_OPERATION, opType)
.initializer(Stubs.PROP_STUBS_OPERATION)
.build()
)
.addType(
TypeSpec.interfaceBuilder("Factory")
.addFunction(
FunSpec.builder("create")
.addModifiers(KModifier.ABSTRACT)
.returns(ClassName("", Stubs.CLASS_STUBS))
.addParameter(Properties.PROP_CHANNEL, GrpcTypes.ManagedChannel)
.addParameter(
Properties.PROP_CALL_OPTS,
GrpcTypes.Support.ClientCallOptions
)
.build()
)
.build()
)
.build()
}
override fun getStubTypeName(context: GeneratorContext) =
ClassName(context.className.packageName, "${context.className.simpleName}Stub")
override fun getApiStubType(context: GeneratorContext) =
GrpcTypes.Support.GrpcClientStub(getStubTypeName(context))
override fun getOperationsStubType(context: GeneratorContext) =
GrpcTypes.Support.GrpcClientStub(GrpcTypes.OperationsClientStub)
}
| apache-2.0 | a6dbe6daf8ccef8027266c71884f9c9f | 36.81194 | 92 | 0.582537 | 5.3515 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/lists/ListsDialogViewModel.kt | 1 | 2248 | /*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.lists
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import net.simonvt.cathode.api.enumeration.ItemType
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.UserList
import net.simonvt.cathode.entitymapper.UserListListMapper
import net.simonvt.cathode.entitymapper.UserListMapper
import net.simonvt.cathode.provider.DatabaseContract.ListItemColumns
import net.simonvt.cathode.provider.ProviderSchematic.ListItems
import net.simonvt.cathode.provider.ProviderSchematic.Lists
import net.simonvt.cathode.ui.lists.DialogListItemListMapper.DialogListItem
class ListsDialogViewModel(application: Application) : AndroidViewModel(application) {
private lateinit var itemType: ItemType
private var itemId = -1L
lateinit var lists: LiveData<List<UserList>>
lateinit var listItems: LiveData<List<DialogListItem>>
fun setItemTypeAndId(itemType: ItemType, itemId: Long) {
if (this.itemId == -1L) {
this.itemType = itemType
this.itemId = itemId
lists = MappedCursorLiveData(
getApplication(),
Lists.LISTS,
UserListMapper.projection,
null,
null,
null,
UserListListMapper
)
listItems = MappedCursorLiveData(
getApplication(),
ListItems.LIST_ITEMS,
DialogListItemListMapper.PROJECTION,
ListItemColumns.ITEM_TYPE + "=? AND " + ListItemColumns.ITEM_ID + "=?",
arrayOf(itemType.toString(), itemId.toString()),
null,
DialogListItemListMapper()
)
}
}
}
| apache-2.0 | eaf3edaa660fbd15bd3a606442dec28c | 33.584615 | 86 | 0.741548 | 4.550607 | false | false | false | false |
Mauin/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/runners/SingleRuleRunner.kt | 1 | 1965 | package io.gitlab.arturbosch.detekt.cli.runners
import io.gitlab.arturbosch.detekt.api.BaseRule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.cli.CliArgs
import io.gitlab.arturbosch.detekt.cli.DetektProgressListener
import io.gitlab.arturbosch.detekt.cli.OutputFacade
import io.gitlab.arturbosch.detekt.cli.createPathFilters
import io.gitlab.arturbosch.detekt.cli.createPlugins
import io.gitlab.arturbosch.detekt.cli.loadConfiguration
import io.gitlab.arturbosch.detekt.core.DetektFacade
import io.gitlab.arturbosch.detekt.core.ProcessingSettings
import io.gitlab.arturbosch.detekt.core.RuleSetLocator
/**
* @author Artur Bosch
*/
class SingleRuleRunner(private val arguments: CliArgs) : Executable {
override fun execute() {
val (ruleSet, rule) = arguments.runRule?.split(":")
?: throw IllegalStateException("Unexpected empty 'runRule' argument.")
val settings = ProcessingSettings(
arguments.inputPath,
arguments.loadConfiguration(),
arguments.createPathFilters(),
arguments.parallel,
arguments.disableDefaultRuleSets,
arguments.createPlugins())
val ruleToRun = RuleSetLocator(settings).load()
.find { it.ruleSetId == ruleSet }
?.buildRuleset(Config.empty)
?.rules
?.find { it.id == rule }
?: throw IllegalArgumentException("There was no rule '$rule' in rule set '$ruleSet'.")
val provider = FakeRuleSetProvider("$ruleSet-$rule", ruleToRun)
val detektion = DetektFacade.create(
settings,
listOf(provider),
listOf(DetektProgressListener())
).run()
OutputFacade(arguments, detektion, settings).run()
}
}
private class FakeRuleSetProvider(
runPattern: String,
private val rule: BaseRule) : RuleSetProvider {
override val ruleSetId: String = runPattern
override fun instance(config: Config): RuleSet = RuleSet(ruleSetId, listOf(rule))
}
| apache-2.0 | 281017944889bd7bb6c0eb22f0b19418 | 32.87931 | 90 | 0.769975 | 3.985801 | false | true | false | false |
FHannes/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/PersistentMapManager.kt | 2 | 6717 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.configurationStore
import com.intellij.configurationStore.deserializeElementFromBinary
import com.intellij.configurationStore.serializeElementToBinary
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.ByteSequence
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.*
import com.intellij.util.loadElement
import com.intellij.util.write
import org.jdom.Element
import java.io.ByteArrayInputStream
import java.io.IOException
import java.nio.file.Path
private val LOG = logger<PersistentMapManager<Any>>()
class PersistentMapManager<VALUE>(name: String, dir: Path, valueExternalizer: DataExternalizer<VALUE>, parentDisposable: Disposable, formatVersion: Int, corruptedHandler: () -> Unit) {
private val file = dir.resolve(name)
private val fileInitiallyExisted = file.exists()
@Volatile
private var storageCreated = false
fun get(key: String) = if (fileInitiallyExisted || storageCreated) storage.get(key) else null
fun remove(key: String) {
put(key, null)
}
fun put(key: String, value: VALUE?) {
if (value != null) {
storage.put(key, value)
}
else if (fileInitiallyExisted || storageCreated) {
storage.remove(key)
}
}
val isDirty: Boolean
get() = if (storageCreated) storage.isDirty else false
private val storage by lazy {
val versionFile = dir.resolve("$name.version")
fun createMap() = PersistentHashMap(file.toFile(), EnumeratorStringDescriptor.INSTANCE, valueExternalizer)
fun deleteFileAndWriteLatestFormatVersion() {
dir.deleteChildrenStartingWith(file.fileName.toString())
file.delete()
versionFile.outputStream().use { it.write(formatVersion) }
corruptedHandler()
}
val data = try {
val fileVersion = versionFile.inputStreamIfExists()?.use { it.read() } ?: -1
if (fileVersion != formatVersion) {
deleteFileAndWriteLatestFormatVersion()
}
createMap()
}
catch (e: IOException) {
LOG.info(e)
deleteFileAndWriteLatestFormatVersion()
createMap()
}
Disposer.register(parentDisposable, Disposable { data.close() })
storageCreated = true
data
}
fun forceSave() {
if (storageCreated) {
storage.force()
}
}
}
internal interface ExternalSystemStorage {
val isDirty: Boolean
fun remove(name: String)
fun read(name: String): Element?
fun write(name: String, element: Element)
fun forceSave()
fun rename(oldName: String, newName: String)
}
private fun nameToFilename(name: String) = "${FileUtil.sanitizeFileName(name, false)}.xml"
internal class FileSystemExternalSystemStorage(project: Project) : ExternalSystemStorage {
override val isDirty = false
private val dir = ExternalProjectsDataStorage.getProjectConfigurationDir(project).resolve("modules")
private var hasSomeData: Boolean
init {
val fileAttributes = dir.basicAttributesIfExists()
if (fileAttributes == null) {
hasSomeData = false
}
else if (fileAttributes.isRegularFile) {
// old binary format
dir.parent.deleteChildrenStartingWith(dir.fileName.toString())
hasSomeData = false
}
else {
LOG.assertTrue(fileAttributes.isDirectory)
hasSomeData = true
}
}
private fun nameToPath(name: String) = dir.resolve(nameToFilename(name))
override fun forceSave() {
}
override fun remove(name: String) {
if (!hasSomeData) {
return
}
nameToPath(name).delete()
}
override fun read(name: String): Element? {
if (!hasSomeData) {
return null
}
return nameToPath(name).inputStreamIfExists()?.use {
loadElement(it)
}
}
override fun write(name: String, element: Element) {
hasSomeData = true
element.write(nameToPath(name))
}
override fun rename(oldName: String, newName: String) {
if (!hasSomeData) {
return
}
val oldFile = nameToPath(oldName)
if (oldFile.exists()) {
oldFile.move(nameToPath(newName))
}
}
}
// not used for now, https://upsource.jetbrains.com/IDEA/review/IDEA-CR-20673, later PersistentHashMap will be not used.
@Suppress("unused")
internal class BinaryExternalSystemStorage(project: Project) : ExternalSystemStorage {
override fun forceSave() {
moduleStorage.forceSave()
}
override val isDirty: Boolean
get() = moduleStorage.isDirty
@Suppress("INTERFACE_STATIC_METHOD_CALL_FROM_JAVA6_TARGET")
val moduleStorage = PersistentMapManager("modules", ExternalProjectsDataStorage.getProjectConfigurationDir(project), ByteSequenceDataExternalizer.INSTANCE, project, 0) {
StartupManager.getInstance(project).runWhenProjectIsInitialized {
val externalProjectManager = ExternalProjectsManager.getInstance(project)
externalProjectManager.runWhenInitialized {
externalProjectManager.externalProjectsWatcher.markDirtyAllExternalProjects()
}
}
}
override fun remove(name: String) {
moduleStorage.remove(name)
}
override fun read(name: String): Element? {
val data = moduleStorage.get(name) ?: return null
return ByteArrayInputStream(data.bytes, data.offset, data.length).use { deserializeElementFromBinary(it) }
}
override fun write(name: String, element: Element) {
val byteOut = BufferExposingByteArrayOutputStream()
serializeElementToBinary(element, byteOut)
moduleStorage.put(name, ByteSequence(byteOut.internalBuffer, 0, byteOut.size()))
}
override fun rename(oldName: String, newName: String) {
moduleStorage.get(oldName)?.let {
moduleStorage.remove(oldName)
moduleStorage.put(newName, it)
}
}
} | apache-2.0 | 062c5729672405cdcde97d791d2d0b11 | 28.857778 | 184 | 0.730534 | 4.339147 | false | false | false | false |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UVariable.kt | 6 | 4647 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A variable wrapper to be used in [UastVisitor].
*/
interface UVariable : UDeclaration, PsiVariable {
override val psi: PsiVariable
/**
* Returns the variable initializer or the parameter default value, or null if the variable has not an initializer.
*/
val uastInitializer: UExpression?
/**
* Returns variable type reference.
*/
val typeReference: UTypeReferenceExpression?
override fun accept(visitor: UastVisitor) {
if (visitor.visitVariable(this)) return
visitContents(visitor)
visitor.afterVisitVariable(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitVariable(this, data)
@Deprecated("Use uastInitializer instead.", ReplaceWith("uastInitializer"))
override fun getInitializer() = psi.initializer
override fun asLogString() = log("name = $name")
override fun asRenderString() = buildString {
append(psi.renderModifiers())
append("var ").append(psi.name).append(": ").append(psi.type.getCanonicalText(false))
uastInitializer?.let { initializer -> append(" = " + initializer.asRenderString()) }
}
}
private fun UVariable.visitContents(visitor: UastVisitor) {
annotations.acceptList(visitor)
uastInitializer?.accept(visitor)
}
interface UParameter : UVariable, PsiParameter {
override val psi: PsiParameter
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitParameter(this)) return
visitContents(visitor)
visitor.afterVisitParameter(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitParameter(this, data)
}
interface UField : UVariable, PsiField {
override val psi: PsiField
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitField(this)) return
visitContents(visitor)
visitor.afterVisitField(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitField(this, data)
}
interface ULocalVariable : UVariable, PsiLocalVariable {
override val psi: PsiLocalVariable
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitLocalVariable(this)) return
visitContents(visitor)
visitor.afterVisitLocalVariable(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitLocalVariable(this, data)
}
interface UEnumConstant : UField, UCallExpression, PsiEnumConstant {
override val psi: PsiEnumConstant
val initializingClass: UClass?
override fun asLogString() = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitEnumConstant(this)) return
annotations.acceptList(visitor)
methodIdentifier?.accept(visitor)
classReference?.accept(visitor)
valueArguments.acceptList(visitor)
initializingClass?.accept(visitor)
visitor.afterVisitEnumConstant(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitEnumConstantExpression(this, data)
override fun asRenderString() = buildString {
append(name ?: "<ERROR>")
if (valueArguments.isNotEmpty()) {
valueArguments.joinTo(this, prefix = "(", postfix = ")", transform = UExpression::asRenderString)
}
initializingClass?.let {
appendln(" {")
it.uastDeclarations.forEachIndexed { index, declaration ->
appendln(declaration.asRenderString().withMargin)
}
append("}")
}
}
} | apache-2.0 | 351947460f8e310568702df83e8381b1 | 31.964539 | 119 | 0.687971 | 4.60555 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/properties/FilePropertiesPromise.kt | 2 | 3137 | package com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.FilePropertiesContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.repository.IFilePropertiesContainerRepository
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.shared.UrlKeyHolder
import com.lasthopesoftware.resources.executors.ThreadPools
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.propagation.CancellationProxy
import com.namehillsoftware.handoff.promises.queued.MessageWriter
import com.namehillsoftware.handoff.promises.queued.QueuedPromise
import com.namehillsoftware.handoff.promises.response.ImmediateResponse
import com.namehillsoftware.handoff.promises.response.PromisedResponse
import okhttp3.Response
import xmlwise.Xmlwise
import java.io.IOException
import java.util.*
import kotlin.collections.HashMap
internal class FilePropertiesPromise(
private val connectionProvider: IConnectionProvider,
private val filePropertiesContainerProvider: IFilePropertiesContainerRepository,
private val serviceFile: ServiceFile,
private val serverRevision: Int
) :
Promise<Map<String, String>>(),
PromisedResponse<Response, Unit>,
MessageWriter<Unit>,
ImmediateResponse<Throwable, Unit>
{
private val cancellationProxy = CancellationProxy()
private lateinit var response: Response
init {
respondToCancellation(cancellationProxy)
val filePropertiesResponse = connectionProvider.promiseResponse("File/GetInfo", "File=" + serviceFile.key)
val promisedProperties = filePropertiesResponse.eventually(this)
// Handle cancellation errors directly in stack so that they don't become unhandled
promisedProperties.excuse(this)
cancellationProxy.doCancel(promisedProperties)
cancellationProxy.doCancel(filePropertiesResponse)
}
override fun promiseResponse(resolution: Response): Promise<Unit> {
response = resolution
return QueuedPromise(this, ThreadPools.compute)
}
override fun prepareMessage() {
val result = if (cancellationProxy.isCancelled) emptyMap()
else connectionProvider.urlProvider.baseUrl?.let { baseUrl ->
response.body
?.use { body -> Xmlwise.createXml(body.string()) }
?.let { xml ->
val parent = xml[0]
parent.associateTo(HashMap(), { el -> Pair(el.getAttribute("Name"), el.value) })
}
?.also { properties ->
filePropertiesContainerProvider.putFilePropertiesContainer(
UrlKeyHolder(baseUrl, serviceFile),
FilePropertiesContainer(serverRevision, properties)
)
}
} ?: emptyMap()
resolve(result)
}
override fun respond(resolution: Throwable) {
when (resolution) {
is IOException -> {
val message = resolution.message
if (message != null && message.lowercase(Locale.getDefault()).contains("canceled")) resolve(emptyMap())
else reject(resolution)
}
else -> reject(resolution)
}
}
}
| lgpl-3.0 | 7f23ffb125e049d6aecb57c172c54d74 | 37.256098 | 128 | 0.799809 | 4.393557 | false | false | false | false |
FHannes/intellij-community | platform/projectModel-api/src/com/intellij/openapi/application/actions.kt | 6 | 1933 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.util.Computable
import javax.swing.SwingUtilities
inline fun <T> runWriteAction(crossinline runnable: () -> T): T {
return ApplicationManager.getApplication().runWriteAction(Computable { runnable() })
}
inline fun <T> runUndoTransparentWriteAction(crossinline runnable: () -> T): T {
var result: T? = null
CommandProcessor.getInstance().runUndoTransparentAction {
result = ApplicationManager.getApplication().runWriteAction(Computable { runnable() })
}
return result as T
}
inline fun <T> runReadAction(crossinline runnable: () -> T): T = ApplicationManager.getApplication().runReadAction(Computable { runnable() })
/**
* @exclude Internal use only
*/
fun <T> invokeAndWaitIfNeed(modalityState: ModalityState? = null, runnable: () -> T): T {
val app = ApplicationManager.getApplication()
if (app == null) {
if (SwingUtilities.isEventDispatchThread()) {
return runnable()
}
else {
var result: T? = null
SwingUtilities.invokeAndWait { result = runnable() }
return result as T
}
}
else {
var result: T? = null
app.invokeAndWait({ result = runnable() }, modalityState ?: ModalityState.defaultModalityState())
return result as T
}
} | apache-2.0 | d0e153ae7cf8a7aee301d1f7a51c59a1 | 33.535714 | 141 | 0.721159 | 4.453917 | false | false | false | false |
phw/PicardBarcodeScanner | app/src/main/java/org/musicbrainz/picard/barcodescanner/activities/AboutActivity.kt | 1 | 2598 | /*
* Copyright (C) 2021 Philipp Wolfer <[email protected]>
*
* This file is part of MusicBrainz Picard Barcode Scanner.
*
* MusicBrainz Picard Barcode Scanner 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.
*
* MusicBrainz Picard Barcode Scanner 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
* MusicBrainz Picard Barcode Scanner. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.musicbrainz.picard.barcodescanner.activities
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.Menu
import android.view.View
import android.widget.TextView
import androidx.core.text.HtmlCompat
import org.musicbrainz.picard.barcodescanner.R
import org.musicbrainz.picard.barcodescanner.databinding.ActivityAboutBinding
class AboutActivity : BaseActivity() {
private lateinit var binding: ActivityAboutBinding
private val contentMappings = mapOf(
R.string.about_copyright to R.id.about_copyright,
R.string.about_license_1 to R.id.about_license_1,
R.string.about_license_2 to R.id.about_license_2,
R.string.about_picard_icon to R.id.about_picard_icon,
R.string.about_icons to R.id.about_icons,
R.string.about_lottie to R.id.about_lottie,
)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAboutBinding.inflate(layoutInflater)
setContentView(binding.root)
val versionName = packageManager.getPackageInfo(packageName, 0).versionName
binding.applicationVersion.text = getString(R.string.app_version, versionName)
for ((rText, rView) in contentMappings) {
val infoTextView = findViewById<View>(rView) as TextView
infoTextView.text = HtmlCompat.fromHtml(getString(rText), HtmlCompat.FROM_HTML_MODE_LEGACY)
infoTextView.movementMethod = LinkMovementMethod.getInstance()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val result = super.onCreateOptionsMenu(menu)
menu.findItem(R.id.action_about).isVisible = false
return result
}
} | gpl-3.0 | 0b10825b92c8b88ace31d924594a81a8 | 40.919355 | 103 | 0.73749 | 4.190323 | false | false | false | false |
NextFaze/dev-fun | devfun/src/main/java/com/nextfaze/devfun/invoke/Invoker.kt | 1 | 6323 | package com.nextfaze.devfun.invoke
import android.content.Context
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import com.nextfaze.devfun.DebugException
import com.nextfaze.devfun.core.ActivityTracker
import com.nextfaze.devfun.core.DevFun
import com.nextfaze.devfun.core.resumedActivity
import com.nextfaze.devfun.error.ErrorHandler
import com.nextfaze.devfun.function.FunctionItem
import com.nextfaze.devfun.function.InvokeResult
import com.nextfaze.devfun.inject.Constructable
import com.nextfaze.devfun.inject.InstanceProvider
import com.nextfaze.devfun.internal.log.*
import com.nextfaze.devfun.internal.toSignatureString
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.jvm.kotlinFunction
/** Used to invoke a [FunctionItem] or [UiFunction] and automatically handles parameter injection and errors. */
interface Invoker {
/**
* Invokes a function item, using the invocation UI if needed.
*
* Any exceptions thrown during invocation should be caught and returned as an [InvokeResult] - exception for
* [DebugException], which is intended to crash the app and should simply be re-thrown when encountered.
*
* @return The result of the invocation and/or any exception thrown (other than [DebugException]).
* If the result is `null` then the invocation is pending user interaction.
*/
fun invoke(item: FunctionItem): InvokeResult?
/**
* Invokes a function using the invocation UI.
*
* @param function The function description.
*
* @return The result of the invocation and/or any exception thrown (other than [DebugException]).
* If the result is `null` then the invocation is pending user interaction.
*/
fun invoke(function: UiFunction): InvokeResult?
}
@Constructable
internal class DefaultInvoker(
context: Context,
private val devFun: DevFun,
private val activityTracker: ActivityTracker,
private val errorHandler: ErrorHandler
) : Invoker {
private val log = logger()
private val application = context.applicationContext
private data class SimpleInvokeResult(override val value: Any? = null, override val exception: Throwable? = null) : InvokeResult
override fun invoke(item: FunctionItem): InvokeResult? {
return try {
doInvoke(item).apply {
if (this == null) {
log.i { "Invocation of $item is pending user interaction..." }
} else {
// todo show result dialog for non-null non-Unit return values?
val exception = exception
when (exception) {
null -> log.i { "Invocation of $item returned\n$value" }
else -> errorHandler.onError(
exception,
"Invocation Failure",
"Something went wrong when trying to invoke the method.",
item
)
}
}
}
} catch (de: DebugException) {
throw de
} catch (t: Throwable) {
errorHandler.onError(t, "Pre-invocation Failure", "Something went wrong when trying to detect/find type instances.", item)
SimpleInvokeResult(exception = t)
}
}
override fun invoke(function: UiFunction): InvokeResult? {
val activity = activityTracker.resumedActivity
when (activity) {
is FragmentActivity -> InvokingDialogFragment.show(activity, function)
else -> Toast.makeText(application, "Cannot show UI dialog without a resumed FragmentActivity.", Toast.LENGTH_SHORT).show()
}
return null
}
private fun doInvoke(item: FunctionItem): InvokeResult? {
var haveAllInstances = true
class Checker : InstanceProvider {
override fun <T : Any> get(clazz: KClass<out T>): T? =
when {
!haveAllInstances -> null
else ->
try {
devFun.instanceOf(clazz)
} catch (t: Throwable) {
haveAllInstances = false
null
}
}
}
val instanceProvider = Checker()
val receiver = item.receiverInstance(instanceProvider)
val args = item.parameterInstances(instanceProvider)
if (haveAllInstances) {
return try {
SimpleInvokeResult(value = item.invoke(receiver, args))
} catch (de: DebugException) {
throw de
} catch (t: Throwable) {
SimpleInvokeResult(exception = t)
}
} else {
val group = item.group
val category = item.category.name
val kFun = item.function.method.kotlinFunction
?: throw RuntimeException(
"""
Could not get Kotlin Function equivalent for ${item.function.method}
Try reloading the DevFun definitions:
DevFun > Misc > Reload Item Definitions""".trimIndent()
)
val parameters = kFun.parameters.filter { it.kind == KParameter.Kind.VALUE }.map(::NativeParameter)
val invoke: SimpleInvoke = {
log.d { "Invoke $item\nwith args: $it" }
item.invoke(item.receiverInstance(devFun.instanceProviders), it)
}
val description = uiFunction(
title = item.name,
subtitle = if (group == null) category else "$category - $group",
signature = kFun.toSignatureString(application.packageName),
parameters = parameters,
invoke = invoke
)
invoke(description)
}
return null
}
}
private class NativeParameter(
override val kParameter: KParameter
) : Parameter, WithKParameter {
override val name = kParameter.name
override val type: KClass<*> = kParameter.type.classifier as KClass<*>
override val annotations = kParameter.annotations
}
| apache-2.0 | 069b18caf6ec5a9cc2471f7b2a1ceb2f | 38.51875 | 135 | 0.600981 | 5.103309 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/fragment/DownloadDialogFragment.kt | 1 | 4105 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.appcompat.app.AlertDialog
import android.text.Html
import android.text.Spanned
import android.widget.Button
import kotlinx.android.synthetic.main.download_dialog.view.*
import mozilla.components.support.utils.DownloadUtils
import org.mozilla.focus.R
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.web.Download
/**
* Fragment displaying a download dialog
*/
class DownloadDialogFragment : DialogFragment() {
override fun onCreateDialog(bundle: Bundle?): AlertDialog {
val fileName = arguments!!.getString("fileName")
val pendingDownload = arguments!!.getParcelable<Download>("download")
val builder = AlertDialog.Builder(requireContext(), R.style.DialogStyle)
builder.setCancelable(true)
builder.setTitle(getString(R.string.download_dialog_title))
val inflater = activity!!.layoutInflater
val dialogView = inflater.inflate(R.layout.download_dialog, null)
builder.setView(dialogView)
dialogView.download_dialog_icon.setImageResource(R.drawable.ic_download)
dialogView.download_dialog_file_name.text = fileName
dialogView.download_dialog_cancel.text = getString(R.string.download_dialog_action_cancel)
dialogView.download_dialog_download.text =
getString(R.string.download_dialog_action_download)
dialogView.download_dialog_warning.text =
getSpannedTextFromHtml(R.string.download_dialog_warning, R.string.app_name)
setButtonOnClickListener(dialogView.download_dialog_cancel, pendingDownload, false)
setButtonOnClickListener(dialogView.download_dialog_download, pendingDownload, true)
return builder.create()
}
private fun setButtonOnClickListener(
button: Button,
pendingDownload: Download?,
shouldDownload: Boolean
) {
button.setOnClickListener {
sendDownloadDialogButtonClicked(pendingDownload, shouldDownload)
TelemetryWrapper.downloadDialogDownloadEvent(shouldDownload)
dismiss()
}
}
private fun sendDownloadDialogButtonClicked(download: Download?, shouldDownload: Boolean) {
val listener = parentFragment as DownloadDialogListener?
listener?.onFinishDownloadDialog(download, shouldDownload)
dismiss()
}
@Suppress("DEPRECATION")
private fun getSpannedTextFromHtml(text: Int, replaceString: Int): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(
String
.format(
getText(text)
.toString(), getString(replaceString)
), Html.FROM_HTML_MODE_LEGACY
)
} else {
Html.fromHtml(
String
.format(
getText(text)
.toString(), getString(replaceString)
)
)
}
}
interface DownloadDialogListener {
fun onFinishDownloadDialog(download: Download?, shouldDownload: Boolean)
}
companion object {
val FRAGMENT_TAG = "should-download-prompt-dialog"
fun newInstance(download: Download): DownloadDialogFragment {
val frag = DownloadDialogFragment()
val args = Bundle()
val fileName = download.fileName ?: DownloadUtils.guessFileName(
download.contentDisposition,
download.url,
download.mimeType
)
args.putString("fileName", fileName)
args.putParcelable("download", download)
frag.arguments = args
return frag
}
}
}
| mpl-2.0 | 960ad01f35c769b35f082959a6b95438 | 35.327434 | 98 | 0.655542 | 5.042998 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/stubs.kt | 1 | 4046 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.objcexport
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
class ObjCComment(val contentLines: List<String>) {
constructor(vararg contentLines: String) : this(contentLines.toList())
}
abstract class Stub<out D : DeclarationDescriptor>(val name: String, val comment: ObjCComment? = null) {
abstract val descriptor: D?
open val psi: PsiElement?
get() = ((descriptor as? DeclarationDescriptorWithSource)?.source as? PsiSourceElement)?.psi
open val isValid: Boolean
get() = descriptor?.module?.isValid ?: true
}
abstract class ObjCTopLevel<out D : DeclarationDescriptor>(name: String) : Stub<D>(name)
abstract class ObjCClass<out D : DeclarationDescriptor>(name: String,
val attributes: List<String>) : ObjCTopLevel<D>(name) {
abstract val superProtocols: List<String>
abstract val members: List<Stub<*>>
}
abstract class ObjCProtocol(name: String,
attributes: List<String>) : ObjCClass<ClassDescriptor>(name, attributes)
class ObjCProtocolImpl(
name: String,
override val descriptor: ClassDescriptor,
override val superProtocols: List<String>,
override val members: List<Stub<*>>,
attributes: List<String> = emptyList()) : ObjCProtocol(name, attributes)
abstract class ObjCInterface(name: String,
val generics: List<String>,
val categoryName: String?,
attributes: List<String>) : ObjCClass<ClassDescriptor>(name, attributes) {
abstract val superClass: String?
abstract val superClassGenerics: List<ObjCNonNullReferenceType>
}
class ObjCInterfaceImpl(
name: String,
generics: List<String> = emptyList(),
override val descriptor: ClassDescriptor? = null,
override val superClass: String? = null,
override val superClassGenerics: List<ObjCNonNullReferenceType> = emptyList(),
override val superProtocols: List<String> = emptyList(),
categoryName: String? = null,
override val members: List<Stub<*>> = emptyList(),
attributes: List<String> = emptyList()
) : ObjCInterface(name, generics, categoryName, attributes)
class ObjCMethod(
override val descriptor: DeclarationDescriptor?,
val isInstanceMethod: Boolean,
val returnType: ObjCType,
val selectors: List<String>,
val parameters: List<ObjCParameter>,
val attributes: List<String>,
comment: ObjCComment? = null
) : Stub<DeclarationDescriptor>(buildMethodName(selectors, parameters), comment)
class ObjCParameter(name: String,
override val descriptor: ParameterDescriptor?,
val type: ObjCType) : Stub<ParameterDescriptor>(name)
class ObjCProperty(name: String,
override val descriptor: DeclarationDescriptorWithSource?,
val type: ObjCType,
val propertyAttributes: List<String>,
val setterName: String? = null,
val getterName: String? = null,
val declarationAttributes: List<String> = emptyList()) : Stub<DeclarationDescriptorWithSource>(name) {
@Deprecated("", ReplaceWith("this.propertyAttributes"), DeprecationLevel.WARNING)
val attributes: List<String> get() = propertyAttributes
}
private fun buildMethodName(selectors: List<String>, parameters: List<ObjCParameter>): String =
if (selectors.size == 1 && parameters.size == 0) {
selectors[0]
} else {
assert(selectors.size == parameters.size)
selectors.joinToString(separator = "")
}
| apache-2.0 | 5c7be467aa8f46d9d75e5fd97e370075 | 41.589474 | 121 | 0.664607 | 4.928136 | false | false | false | false |
ezisazis/AOC-2015 | src/day1/DayOne.kt | 1 | 1766 | package day1
import java.io.File
/**
* Created by leventejonas on 25/06/17.
*/
/*
Santa is trying to deliver presents in a large apartment building, but he can't find the right floor -
the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the
instructions one character at a time.
An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should
go down one floor.
The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.
For example:
(()) and ()() both result in floor 0.
((( and (()(()( both result in floor 3.
))((((( also results in floor 3.
()) and ))( both result in floor -1 (the first basement level).
))) and )())()) both result in floor -3.
To what floor do the instructions take Santa?
*/
fun main(args: Array<String>) {
val input = File("src/day1/day_one_input.txt").readText()
var floor = 0
var basementFound = false
for ((index, character) in input.withIndex()) {
floor += move(character)
/*
Now, given the same instructions, find the position of the first character that causes him to enter the
basement (floor -1). The first character in the instructions has position 1, the second character has
position 2, and so on.
*/
if (floor == -1 && !basementFound) {
println("Basement found at ${index+1}")
basementFound = true
}
}
println("Final floor is $floor")
}
fun move(character: Char): Int {
when (character) {
'(' -> return 1
')' -> return -1
else -> return 0
}
} | unlicense | f002207ca6d5fb9db9143498ee84d265 | 31.722222 | 116 | 0.612684 | 4.087963 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/ui/fragments/ElevationFragment.kt | 1 | 8426 | package com.engineer.imitate.ui.fragments
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.engineer.imitate.R
import com.engineer.imitate.interfaces.SimpleProgressChangeListener
import com.engineer.imitate.util.TestHelper
import com.engineer.imitate.util.toastShort
import com.xw.repo.BubbleSeekBar
import kotlinx.android.synthetic.main.fragment_evelation.*
/**
* A simple [Fragment] subclass.
*
*/
@Route(path = "/anim/elevation")
class ElevationFragment : Fragment() {
private var mDeltaX = 0.0f
private var mDeltaY = 0.0f
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_evelation, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val anim = ObjectAnimator.ofFloat(fab, "rotation", 180f)
anim.repeatMode = ObjectAnimator.REVERSE
anim.repeatCount = ObjectAnimator.INFINITE
anim.start()
// start transformation when touching the fab.
fab.setOnClickListener {
transformationLayout.startTransform(parent)
}
// finish transformation when touching the myCardView.
myCardView.setOnClickListener {
transformationLayout.finishTransform(parent)
}
cardElevationSeekBar.onProgressChangedListener = object : SimpleProgressChangeListener() {
override fun onProgressChanged(
bubbleSeekBar: BubbleSeekBar?,
progress: Int,
progressFloat: Float,
fromUser: Boolean
) {
super.onProgressChanged(bubbleSeekBar, progress, progressFloat, fromUser)
cardView.cardElevation = progressFloat
fab.compatElevation = progressFloat
}
}
cardRadiusSeekBar.onProgressChangedListener = object : SimpleProgressChangeListener() {
override fun onProgressChanged(
bubbleSeekBar: BubbleSeekBar?,
progress: Int,
progressFloat: Float,
fromUser: Boolean
) {
super.onProgressChanged(bubbleSeekBar, progress, progressFloat, fromUser)
cardView.radius = progressFloat
}
}
deltaXSeekBar.onProgressChangedListener = object : SimpleProgressChangeListener() {
override fun onProgressChanged(
bubbleSeekBar: BubbleSeekBar?,
progress: Int,
progressFloat: Float,
fromUser: Boolean
) {
super.onProgressChanged(bubbleSeekBar, progress, progressFloat, fromUser)
mDeltaX = progressFloat
slide_view.update(progressFloat, mDeltaY)
}
}
deltaYSeekBar.onProgressChangedListener = object : SimpleProgressChangeListener() {
override fun onProgressChanged(
bubbleSeekBar: BubbleSeekBar?,
progress: Int,
progressFloat: Float,
fromUser: Boolean
) {
super.onProgressChanged(bubbleSeekBar, progress, progressFloat, fromUser)
val screenHeight = resources.displayMetrics.heightPixels
val delatY = progressFloat / deltaYSeekBar.max * screenHeight
mDeltaY = delatY
slide_view.update(mDeltaX, delatY)
}
}
textView.setOnClickListener {
context?.toastShort("context extension !")
}
open_push_setting.setOnClickListener {
if (context != null) {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.action = Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS
}
intent.data = Uri.fromParts("package", context?.packageName, null)
try {
startActivity(intent)
} catch (e: Exception) {
tryThis()
e.printStackTrace()
}
}
}
open_system_share.setOnClickListener {
// val shareIntent = ShareCompat.IntentBuilder.from(activity)
// .setText("share content")
// .setType("text/plain")
// .createChooserIntent()
// .apply {
// // https://android-developers.googleblog.com/2012/02/share-with-intents.html
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// // If we're on Lollipop, we can open the intent as a document
// addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
// } else {
// // Else, we will use the old CLEAR_WHEN_TASK_RESET flag
// addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
// }
// }
// startActivity(shareIntent)
}
read_sp.setOnClickListener {
val sp = it.context.getSharedPreferences("shared_prefs_doraemon", Context.MODE_PRIVATE)
val map = sp.all
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
map.forEach { t, any ->
Log.e("read_sp", "key = $t, value = $any")
}
}
}
view.findViewById<Button>(R.id.start11).setOnClickListener {
TestHelper.openActivity(it.context)
}
view.findViewById<Button>(R.id.start22).setOnClickListener {
TestHelper.openActivityHome(it.context)
}
view.findViewById<Button>(R.id.start33).setOnClickListener {
TestHelper.openActivityByUrl(it.context)
}
}
private fun tryThisOne() {
val intent = Intent()
intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
//for Android 5-7
intent.putExtra("app_package", context?.packageName)
intent.putExtra("app_uid", context?.applicationInfo?.uid)
// for Android O
intent.putExtra("android.provider.extra.APP_PACKAGE", context?.packageName)
try {
startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun tryThis() {
val intent = Intent()
when {
Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1 -> {
intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
intent.putExtra("android.provider.extra.APP_PACKAGE", context?.getPackageName())
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
intent.putExtra("app_package", context?.getPackageName())
intent.putExtra("app_uid", context?.getApplicationInfo()?.uid)
}
else -> {
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.data = Uri.parse("package:" + context?.packageName)
}
}
try {
startActivity(intent)
} catch (e: Exception) {
tryThisOne()
e.printStackTrace()
}
}
override fun onResume() {
super.onResume()
context?.let {
notification.text =
NotificationManagerCompat.from(it).areNotificationsEnabled().toString()
}
}
}
| apache-2.0 | 9bc25af76b8236a900a56a453714a58a | 34.552743 | 111 | 0.586874 | 5.091239 | false | false | false | false |
is00hcw/anko | dsl/testData/functional/sdk15/ViewTest.kt | 2 | 49493 | public object `$$Anko$Factories$Sdk15View` {
public val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) }
public val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) }
public val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) }
public val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) }
public val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) }
public val VIEW = { ctx: Context -> android.view.View(ctx) }
public val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) }
public val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) }
public val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) }
public val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) }
public val BUTTON = { ctx: Context -> android.widget.Button(ctx) }
public val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) }
public val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) }
public val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) }
public val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) }
public val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) }
public val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) }
public val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) }
public val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) }
public val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) }
public val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) }
public val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) }
public val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) }
public val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) }
public val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) }
public val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) }
public val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) }
public val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) }
public val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) }
public val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) }
public val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) }
public val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) }
public val SPACE = { ctx: Context -> android.widget.Space(ctx) }
public val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) }
public val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) }
public val SWITCH = { ctx: Context -> android.widget.Switch(ctx) }
public val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) }
public val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) }
public val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) }
public val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) }
public val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) }
public val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) }
public val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) }
public val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) }
public val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) }
public val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) }
}
public inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun ViewManager.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
public inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun Context.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
public inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun Activity.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() }
}
public inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({})
public inline fun ViewManager.extractEditText(init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EXTRACT_EDIT_TEXT) { init() }
}
public inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({})
public inline fun ViewManager.gLSurfaceView(init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk15View`.G_L_SURFACE_VIEW) { init() }
}
public inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({})
public inline fun ViewManager.surfaceView(init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk15View`.SURFACE_VIEW) { init() }
}
public inline fun ViewManager.textureView(): android.view.TextureView = textureView({})
public inline fun ViewManager.textureView(init: android.view.TextureView.() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXTURE_VIEW) { init() }
}
public inline fun ViewManager.view(): android.view.View = view({})
public inline fun ViewManager.view(init: android.view.View.() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW) { init() }
}
public inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({})
public inline fun ViewManager.viewStub(init: android.view.ViewStub.() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_STUB) { init() }
}
public inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun ViewManager.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
public inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun Context.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
public inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun Activity.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() }
}
public inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({})
public inline fun ViewManager.analogClock(init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk15View`.ANALOG_CLOCK) { init() }
}
public inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({})
public inline fun ViewManager.autoCompleteTextView(init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.AUTO_COMPLETE_TEXT_VIEW) { init() }
}
public inline fun ViewManager.button(): android.widget.Button = button({})
public inline fun ViewManager.button(init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { init() }
}
public inline fun ViewManager.button(text: CharSequence?): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
setText(text)
}
}
public inline fun ViewManager.button(text: CharSequence?, init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
init()
setText(text)
}
}
public inline fun ViewManager.button(text: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
setText(text)
}
}
public inline fun ViewManager.button(text: Int, init: android.widget.Button.() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) {
init()
setText(text)
}
}
public inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun ViewManager.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
public inline fun Context.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun Context.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
public inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun Activity.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() }
}
public inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({})
public inline fun ViewManager.checkBox(init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() }
}
public inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
}
}
public inline fun ViewManager.checkBox(text: CharSequence?, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
}
}
public inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
}
}
public inline fun ViewManager.checkBox(text: Int, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
}
}
public inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) {
init()
setText(text)
setChecked(checked)
}
}
public inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({})
public inline fun ViewManager.checkedTextView(init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.CHECKED_TEXT_VIEW) { init() }
}
public inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({})
public inline fun ViewManager.chronometer(init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk15View`.CHRONOMETER) { init() }
}
public inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun ViewManager.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
public inline fun Context.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun Context.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
public inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun Activity.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() }
}
public inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun ViewManager.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
public inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun Context.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
public inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun Activity.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() }
}
public inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({})
public inline fun ViewManager.digitalClock(init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk15View`.DIGITAL_CLOCK) { init() }
}
public inline fun ViewManager.editText(): android.widget.EditText = editText({})
public inline fun ViewManager.editText(init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { init() }
}
public inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
setText(text)
}
}
public inline fun ViewManager.editText(text: CharSequence?, init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
init()
setText(text)
}
}
public inline fun ViewManager.editText(text: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
setText(text)
}
}
public inline fun ViewManager.editText(text: Int, init: android.widget.EditText.() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) {
init()
setText(text)
}
}
public inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun ViewManager.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
public inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun Context.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
public inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun Activity.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() }
}
public inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({})
public inline fun ViewManager.imageButton(init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { init() }
}
public inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
setImageDrawable(imageDrawable)
}
}
public inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
init()
setImageDrawable(imageDrawable)
}
}
public inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
setImageResource(imageResource)
}
}
public inline fun ViewManager.imageButton(imageResource: Int, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) {
init()
setImageResource(imageResource)
}
}
public inline fun ViewManager.imageView(): android.widget.ImageView = imageView({})
public inline fun ViewManager.imageView(init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { init() }
}
public inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
setImageDrawable(imageDrawable)
}
}
public inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
init()
setImageDrawable(imageDrawable)
}
}
public inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
setImageResource(imageResource)
}
}
public inline fun ViewManager.imageView(imageResource: Int, init: android.widget.ImageView.() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) {
init()
setImageResource(imageResource)
}
}
public inline fun ViewManager.listView(): android.widget.ListView = listView({})
public inline fun ViewManager.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
public inline fun Context.listView(): android.widget.ListView = listView({})
public inline fun Context.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
public inline fun Activity.listView(): android.widget.ListView = listView({})
public inline fun Activity.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() }
}
public inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({})
public inline fun ViewManager.multiAutoCompleteTextView(init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk15View`.MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() }
}
public inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun ViewManager.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
public inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun Context.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
public inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun Activity.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() }
}
public inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({})
public inline fun ViewManager.progressBar(init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk15View`.PROGRESS_BAR) { init() }
}
public inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({})
public inline fun ViewManager.quickContactBadge(init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk15View`.QUICK_CONTACT_BADGE) { init() }
}
public inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({})
public inline fun ViewManager.radioButton(init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk15View`.RADIO_BUTTON) { init() }
}
public inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({})
public inline fun ViewManager.ratingBar(init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk15View`.RATING_BAR) { init() }
}
public inline fun ViewManager.searchView(): android.widget.SearchView = searchView({})
public inline fun ViewManager.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
public inline fun Context.searchView(): android.widget.SearchView = searchView({})
public inline fun Context.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
public inline fun Activity.searchView(): android.widget.SearchView = searchView({})
public inline fun Activity.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() }
}
public inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({})
public inline fun ViewManager.seekBar(init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk15View`.SEEK_BAR) { init() }
}
public inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun ViewManager.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
public inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun Context.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
public inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun Activity.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() }
}
public inline fun ViewManager.space(): android.widget.Space = space({})
public inline fun ViewManager.space(init: android.widget.Space.() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk15View`.SPACE) { init() }
}
public inline fun ViewManager.spinner(): android.widget.Spinner = spinner({})
public inline fun ViewManager.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
public inline fun Context.spinner(): android.widget.Spinner = spinner({})
public inline fun Context.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
public inline fun Activity.spinner(): android.widget.Spinner = spinner({})
public inline fun Activity.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() }
}
public inline fun ViewManager.stackView(): android.widget.StackView = stackView({})
public inline fun ViewManager.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
public inline fun Context.stackView(): android.widget.StackView = stackView({})
public inline fun Context.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
public inline fun Activity.stackView(): android.widget.StackView = stackView({})
public inline fun Activity.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() }
}
public inline fun ViewManager.switch(): android.widget.Switch = switch({})
public inline fun ViewManager.switch(init: android.widget.Switch.() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk15View`.SWITCH) { init() }
}
public inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({})
public inline fun ViewManager.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
public inline fun Context.tabHost(): android.widget.TabHost = tabHost({})
public inline fun Context.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
public inline fun Activity.tabHost(): android.widget.TabHost = tabHost({})
public inline fun Activity.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() }
}
public inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun ViewManager.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
public inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun Context.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
public inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun Activity.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() }
}
public inline fun ViewManager.textView(): android.widget.TextView = textView({})
public inline fun ViewManager.textView(init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { init() }
}
public inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
setText(text)
}
}
public inline fun ViewManager.textView(text: CharSequence?, init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
init()
setText(text)
}
}
public inline fun ViewManager.textView(text: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
setText(text)
}
}
public inline fun ViewManager.textView(text: Int, init: android.widget.TextView.() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) {
init()
setText(text)
}
}
public inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun ViewManager.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
public inline fun Context.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun Context.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
public inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun Activity.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() }
}
public inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({})
public inline fun ViewManager.toggleButton(init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk15View`.TOGGLE_BUTTON) { init() }
}
public inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun ViewManager.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
public inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun Context.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
public inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun Activity.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() }
}
public inline fun ViewManager.videoView(): android.widget.VideoView = videoView({})
public inline fun ViewManager.videoView(init: android.widget.VideoView.() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk15View`.VIDEO_VIEW) { init() }
}
public inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun ViewManager.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
public inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun Context.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
public inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun Activity.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() }
}
public inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({})
public inline fun ViewManager.zoomButton(init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_BUTTON) { init() }
}
public inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun ViewManager.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
public inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun Context.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
public inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun Activity.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() }
}
public object `$$Anko$Factories$Sdk15ViewGroup` {
public val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) }
public val WEB_VIEW = { ctx: Context -> _WebView(ctx) }
public val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) }
public val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) }
public val GALLERY = { ctx: Context -> _Gallery(ctx) }
public val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) }
public val GRID_VIEW = { ctx: Context -> _GridView(ctx) }
public val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) }
public val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) }
public val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) }
public val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) }
public val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) }
public val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) }
public val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) }
public val TABLE_ROW = { ctx: Context -> _TableRow(ctx) }
public val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) }
public val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) }
public val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) }
}
public inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun ViewManager.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
public inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun Context.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
public inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun Activity.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() }
}
public inline fun ViewManager.webView(): android.webkit.WebView = webView({})
public inline fun ViewManager.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
public inline fun Context.webView(): android.webkit.WebView = webView({})
public inline fun Context.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
public inline fun Activity.webView(): android.webkit.WebView = webView({})
public inline fun Activity.webView(init: _WebView.() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() }
}
public inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun ViewManager.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
public inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun Context.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
public inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun Activity.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() }
}
public inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun ViewManager.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
public inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun Context.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
public inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun Activity.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() }
}
public inline fun ViewManager.gallery(): android.widget.Gallery = gallery({})
public inline fun ViewManager.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
public inline fun Context.gallery(): android.widget.Gallery = gallery({})
public inline fun Context.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
public inline fun Activity.gallery(): android.widget.Gallery = gallery({})
public inline fun Activity.gallery(init: _Gallery.() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() }
}
public inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun ViewManager.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
public inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun Context.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
public inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun Activity.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() }
}
public inline fun ViewManager.gridView(): android.widget.GridView = gridView({})
public inline fun ViewManager.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
public inline fun Context.gridView(): android.widget.GridView = gridView({})
public inline fun Context.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
public inline fun Activity.gridView(): android.widget.GridView = gridView({})
public inline fun Activity.gridView(init: _GridView.() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() }
}
public inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun ViewManager.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
public inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun Context.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
public inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun Activity.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() }
}
public inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun ViewManager.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
public inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun Context.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
public inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun Activity.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() }
}
public inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun ViewManager.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
public inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun Context.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
public inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun Activity.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() }
}
public inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun ViewManager.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
public inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun Context.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
public inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun Activity.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() }
}
public inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun ViewManager.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
public inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun Context.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
public inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun Activity.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() }
}
public inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun ViewManager.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
public inline fun Context.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun Context.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
public inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun Activity.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() }
}
public inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun ViewManager.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
public inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun Context.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
public inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun Activity.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() }
}
public inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({})
public inline fun ViewManager.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
public inline fun Context.tableRow(): android.widget.TableRow = tableRow({})
public inline fun Context.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
public inline fun Activity.tableRow(): android.widget.TableRow = tableRow({})
public inline fun Activity.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() }
}
public inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun ViewManager.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
public inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun Context.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
public inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun Activity.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() }
}
public inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun ViewManager.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
public inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun Context.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
public inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun Activity.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() }
}
public inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun ViewManager.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
}
public inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun Context.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
}
public inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun Activity.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() }
} | apache-2.0 | 9fdbdca1f6fe7fd1098c2ef3a36667ab | 52.739414 | 168 | 0.742873 | 4.327068 | false | false | false | false |
apixandru/intellij-community | plugins/settings-repository/src/readOnlySourcesEditor.kt | 6 | 5601 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.text.trimMiddle
import com.intellij.util.ui.table.TableModelEditor
import gnu.trove.THashSet
import org.jetbrains.settingsRepository.git.asProgressMonitor
import org.jetbrains.settingsRepository.git.cloneBare
import javax.swing.JTextField
private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() {
override fun getColumnClass() = Boolean::class.java
override fun valueOf(item: ReadonlySource) = item.active
override fun setValue(item: ReadonlySource, value: Boolean) {
item.active = value
}
},
object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() {
override fun valueOf(item: ReadonlySource) = item.url
override fun setValue(item: ReadonlySource, value: String) {
item.url = value
}
})
internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> {
val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource> {
override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active)
override fun getItemClass() = ReadonlySource::class.java
override fun edit(item: ReadonlySource, mutator: Function<ReadonlySource, ReadonlySource>, isAdd: Boolean) {
val urlField = TextFieldWithBrowseButton(JTextField(20))
urlField.addBrowseFolderListener(TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()))
val panel = panel {
row("URL:") {
urlField()
}
}
dialog(title = "Add read-only source", panel = panel, focusedComponent = urlField) {
val url = urlField.text.nullize(true)
if (!validateUrl(url, null)) {
return@dialog false
}
mutator.`fun`(item).url = url
return@dialog true
}
.show()
}
override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) {
newItem.url = oldItem.url
}
override fun isUseDialogToAdd() = true
}
val editor = TableModelEditor(COLUMNS, itemEditor, "No sources configured")
editor.reset(if (ApplicationManager.getApplication().isUnitTestMode) emptyList() else icsManager.settings.readOnlySources)
return object : ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun apply(settings: IcsSettings) {
val oldList = settings.readOnlySources
val toDelete = THashSet<String>(oldList.size)
for (oldSource in oldList) {
ContainerUtil.addIfNotNull(toDelete, oldSource.path)
}
val toCheckout = THashSet<ReadonlySource>()
val newList = editor.apply()
for (newSource in newList) {
val path = newSource.path
if (path != null && !toDelete.remove(path)) {
toCheckout.add(newSource)
}
}
if (toDelete.isEmpty && toCheckout.isEmpty) {
return
}
runModalTask(icsMessage("task.sync.title")) { indicator ->
indicator.isIndeterminate = true
val root = icsManager.readOnlySourcesManager.rootDir
if (toDelete.isNotEmpty()) {
indicator.text = "Deleting old repositories"
for (path in toDelete) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text2 = path
root.resolve(path).delete()
}
}
}
if (toCheckout.isNotEmpty()) {
for (source in toCheckout) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text = "Cloning ${source.url!!.trimMiddle(255)}"
val dir = root.resolve(source.path!!)
if (dir.exists()) {
dir.delete()
}
cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close()
}
}
}
icsManager.readOnlySourcesManager.setSources(newList)
// blindly reload all
icsManager.schemeManagerFactory.value.process {
it.reload()
}
}
}
override fun reset(settings: IcsSettings) {
editor.reset(settings.readOnlySources)
}
override fun getComponent() = editor.createComponent()
}
}
| apache-2.0 | 4339acaca5f94f4fd3e55f99227cd06f | 33.574074 | 125 | 0.693448 | 4.77901 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-Events-JS/src/main/kotlin/x/katydid/events/types/KatydidMouseEventImpl.kt | 1 | 1570 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package /*js*/x.katydid.events.types
import o.katydid.events.types.KatydidMouseEvent
import x.katydid.events.domevents.MouseEvent
//---------------------------------------------------------------------------------------------------------------------
open class KatydidMouseEventImpl(
private val event: MouseEvent
) : KatydidUiEventImpl(event), KatydidMouseEvent {
override val altKey: Boolean
get() = event.altKey
override val button: Short
get() = event.button
override val buttons: Short
get() = event.buttons
override val clientX: Int
get() = event.clientX
override val clientY: Int
get() = event.clientY
override val ctrlKey: Boolean
get() = event.ctrlKey
override val metaKey: Boolean
get() = event.metaKey
override val offsetX: Double
get() = event.offsetX
override val offsetY: Double
get() = event.offsetY
override val pageX: Double
get() = event.pageX
override val pageY: Double
get() = event.pageY
override val screenX: Int
get() = event.screenX
override val screenY: Int
get() = event.screenY
override val shiftKey: Boolean
get() = event.shiftKey
////
override fun getModifierState(key: String): Boolean {
return event.getModifierState(key)
}
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | 2329932a47670b990448193c698591e0 | 22.088235 | 119 | 0.543949 | 4.937107 | false | false | false | false |
apixandru/intellij-community | platform/configuration-store-impl/src/StateMap.kt | 3 | 7451 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.SystemProperties
import gnu.trove.THashMap
import org.iq80.snappy.SnappyFramedInputStream
import org.iq80.snappy.SnappyFramedOutputStream
import org.jdom.Element
import java.io.ByteArrayInputStream
import java.util.*
import java.util.concurrent.atomic.AtomicReferenceArray
fun archiveState(state: Element): BufferExposingByteArrayOutputStream {
val byteOut = BufferExposingByteArrayOutputStream()
SnappyFramedOutputStream(byteOut).use {
serializeElementToBinary(state, it)
}
return byteOut
}
private fun unarchiveState(state: ByteArray) = SnappyFramedInputStream(ByteArrayInputStream(state), false).use { deserializeElementFromBinary(it) }
fun getNewByteIfDiffers(key: String, newState: Any, oldState: ByteArray): ByteArray? {
val newBytes: ByteArray
if (newState is Element) {
val byteOut = archiveState(newState)
if (arrayEquals(byteOut.internalBuffer, oldState, byteOut.size())) {
return null
}
newBytes = ArrayUtil.realloc(byteOut.internalBuffer, byteOut.size())
}
else {
newBytes = newState as ByteArray
if (Arrays.equals(newBytes, oldState)) {
return null
}
}
val logChangedComponents = SystemProperties.getBooleanProperty("idea.log.changed.components", false)
if (ApplicationManager.getApplication().isUnitTestMode || logChangedComponents ) {
fun stateToString(state: Any) = JDOMUtil.write(state as? Element ?: unarchiveState(state as ByteArray), "\n")
val before = stateToString(oldState)
val after = stateToString(newState)
if (before == after) {
throw IllegalStateException("$key serialization error - serialized are different, but unserialized are equal")
}
else if (logChangedComponents) {
LOG.info("$key ${StringUtil.repeat("=", 80 - key.length)}\nBefore:\n$before\nAfter:\n$after")
}
}
return newBytes
}
fun stateToElement(key: String, state: Any?, newLiveStates: Map<String, Element>? = null): Element? {
if (state is Element) {
return state.clone()
}
else {
return newLiveStates?.get(key) ?: (state as? ByteArray)?.let(::unarchiveState)
}
}
class StateMap private constructor(private val names: Array<String>, private val states: AtomicReferenceArray<Any?>) {
override fun toString() = if (this == EMPTY) "EMPTY" else states.toString()
companion object {
val EMPTY = StateMap(emptyArray(), AtomicReferenceArray(0))
fun fromMap(map: Map<String, Any>): StateMap {
if (map.isEmpty()) {
return EMPTY
}
val names = map.keys.toTypedArray()
if (map !is TreeMap) {
Arrays.sort(names)
}
val states = AtomicReferenceArray<Any?>(names.size)
for (i in names.indices) {
states.set(i, map[names[i]])
}
return StateMap(names, states)
}
}
fun toMutableMap(): MutableMap<String, Any> {
val map = THashMap<String, Any>(names.size)
for (i in names.indices) {
map.put(names[i], states.get(i))
}
return map
}
/**
* Sorted by name.
*/
fun keys() = names
fun get(key: String): Any? {
val index = Arrays.binarySearch(names, key)
return if (index < 0) null else states.get(index)
}
fun getElement(key: String, newLiveStates: Map<String, Element>? = null) = stateToElement(key, get(key), newLiveStates)
fun isEmpty(): Boolean = names.isEmpty()
fun hasState(key: String) = get(key) is Element
fun hasStates(): Boolean {
if (isEmpty()) {
return false
}
for (i in names.indices) {
if (states.get(i) is Element) {
return true
}
}
return false
}
fun compare(key: String, newStates: StateMap, diffs: MutableSet<String>) {
val oldState = get(key)
val newState = newStates.get(key)
if (oldState is Element) {
if (!JDOMUtil.areElementsEqual(oldState as Element?, newState as Element?)) {
diffs.add(key)
}
}
else if (oldState == null) {
if (newState != null) {
diffs.add(key)
}
}
else if (newState == null || getNewByteIfDiffers(key, newState, oldState as ByteArray) != null) {
diffs.add(key)
}
}
fun getState(key: String, archive: Boolean = false): Element? {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return null
}
val state = states.get(index) as? Element ?: return null
if (!archive) {
return state
}
return if (states.compareAndSet(index, state, archiveState(state).toByteArray())) state else getState(key, true)
}
fun archive(key: String, state: Element?) {
val index = Arrays.binarySearch(names, key)
if (index < 0) {
return
}
states.set(index, state?.let { archiveState(state).toByteArray() })
}
}
fun setStateAndCloneIfNeed(key: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>? = null): MutableMap<String, Any>? {
val oldState = oldStates.get(key)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(key)
return newStates
}
newLiveStates?.put(key, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return null
}
val newStates = oldStates.toMutableMap()
newStates.put(key, newBytes ?: newState)
return newStates
}
// true if updated (not equals to previous state)
internal fun updateState(states: MutableMap<String, Any>, key: String, newState: Element?, newLiveStates: MutableMap<String, Element>? = null): Boolean {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(key)
return true
}
newLiveStates?.put(key, newState)
val oldState = states.get(key)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return false
}
}
else if (oldState != null) {
newBytes = getNewByteIfDiffers(key, newState, oldState as ByteArray) ?: return false
}
states.put(key, newBytes ?: newState)
return true
}
private fun arrayEquals(a: ByteArray, a2: ByteArray, size: Int = a.size): Boolean {
if (a === a2) {
return true
}
if (a2.size != size) {
return false
}
for (i in 0 until size) {
if (a[i] != a2[i]) {
return false
}
}
return true
} | apache-2.0 | 2159119050023c89f02dd116da9a4480 | 28.109375 | 160 | 0.682459 | 3.956984 | false | false | false | false |
icapps/niddler-ui | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/codegen/CurlCodeGenerator.kt | 1 | 2882 | package com.icapps.niddler.ui.codegen
import com.icapps.niddler.lib.connection.model.NiddlerMessage
import com.icapps.niddler.lib.model.ParsedNiddlerMessage
/**
* @author Nicola Verbeeck
* @date 14/06/2017.
*/
class CurlCodeGenerator : CodeGenerator {
companion object {
private val COMMAND_NAME = "curl"
}
override fun generateRequestCode(request: ParsedNiddlerMessage): String {
if (!request.isRequest)
return "<not a request>"
return when (request.method!!.toLowerCase()) {
"get" -> generateGet(request.message)
"delete" -> generateDelete(request.message)
"head" -> generateHead(request.message)
"post" -> generatePost(request)
"put" -> generatePut(request)
else -> "<request type not yet supported>"
}
}
private fun generateHead(request: NiddlerMessage): String {
return generateNoBodyRequest(request, "HEAD")
}
private fun generateGet(request: NiddlerMessage): String {
return generateNoBodyRequest(request, "GET")
}
private fun generateDelete(request: NiddlerMessage): String {
return generateNoBodyRequest(request, "DELETE")
}
private fun generatePost(request: ParsedNiddlerMessage): String {
return generateBodyRequest(request, "POST")
}
private fun generatePut(request: ParsedNiddlerMessage): String {
return generateBodyRequest(request, "PUT")
}
private fun addHeaders(builder: StringBuilder, request: NiddlerMessage) {
val headers = request.headers ?: return
headers.forEach { key, values ->
builder.append("-H \"").append(key).append(": ").append(values.joinToString(",")).append("\" ")
}
}
private fun generateNoBodyRequest(request: NiddlerMessage, method: String): String {
val builder = StringBuilder(COMMAND_NAME)
builder.append(" -i ")
addHeaders(builder, request)
builder.append("-X \"").append(method.toUpperCase()).append("\" \"")
builder.append(request.url!!).append('"')
return builder.toString()
}
private fun generateBodyRequest(request: ParsedNiddlerMessage, method: String): String {
val builder = StringBuilder(COMMAND_NAME)
builder.append(" -i ")
addHeaders(builder, request.message)
builder.append("-X \"").append(method.toUpperCase()).append("\" ")
val bytes = request.message.getBodyAsBytes
if (bytes != null) {
builder.append("--data-binary \"")
builder.append(escape(String(bytes, 0, bytes.size)))
builder.append("\" ")
}
builder.append('"').append(request.url!!).append('"')
return builder.toString()
}
private fun escape(data: String): String {
return data.replace("\"", "\\\"")
}
} | apache-2.0 | 439fc377bcc8480a8e1695984d7386c3 | 31.761364 | 107 | 0.630118 | 4.61859 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/UniversityEventAdapter.kt | 1 | 2224 | package com.pennapps.labs.pennmobile.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pennapps.labs.pennmobile.R
import com.pennapps.labs.pennmobile.classes.CalendarEvent
import kotlinx.android.synthetic.main.university_event.view.*
class UniversityEventAdapter(private var events: ArrayList<CalendarEvent>) :
RecyclerView.Adapter<UniversityEventAdapter.UniversityEventViewHolder>() {
private lateinit var mContext: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UniversityEventViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.university_event, parent, false)
mContext = parent.context
return UniversityEventViewHolder(view)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: UniversityEventViewHolder, position: Int) {
val event = events[position]
val name = event.name
Log.i("EventAdapter", "Name $name Date $event.date")
// val formatter: DateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd")
// val from = formatter.parseDateTime(event.start)
// val to = formatter.parseDateTime(event.end)
// val dayOfMonth = from.toString("d")
// val month = from.toString("MMM")
// val start = from.toString("EEEE")
// val end = to.toString("EEEE")
// holder.itemView.event_day.text = dayOfMonth
// holder.itemView.event_month.text = month
holder.itemView.event_month.text = event.date
holder.itemView.event_name_tv.text = name
holder.itemView.event_name_tv.isSelected = true
/* if (from == to) {
holder.itemView.event_day_of_week.text = start
} else {
holder.itemView.event_day_of_week.text = "$start - $end"
}*/
}
override fun getItemCount(): Int {
return events.size
}
inner class UniversityEventViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val view = itemView
}
}
| mit | 8a1acbda0c7c06d5f1950a0314c1fc70 | 36.694915 | 104 | 0.698291 | 4.335283 | false | false | false | false |
ejeinc/VR-MultiView-UDP | controller-android/src/main/java/com/eje_c/multilink/controller/MainActivity.kt | 1 | 3756 | package com.eje_c.multilink.controller
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.SystemClock
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import com.eje_c.multilink.controller.db.DeviceEntity
import com.eje_c.multilink.controller.db.VideoEntity
import com.eje_c.multilink.data.DeviceInfo
import com.eje_c.multilink.udp.MultiLinkUdpMessenger
import com.eje_c.multilink.udp.UdpSocketService
import kotlinx.android.synthetic.main.activity_main.*
/**
* Application's main entry point.
*/
class MainActivity : AppCompatActivity() {
private val conn = object : ServiceConnection {
override fun onServiceConnected(componentName: ComponentName, binder: IBinder) {
val udpSocket = (binder as UdpSocketService.LocalBinder).service.udpSocket
MultiLinkUdpMessenger.initialize(udpSocket)
MultiLinkUdpMessenger.onReceivePingResponse += this@MainActivity::processDeviceInfo
MultiLinkUdpMessenger.ping()
}
override fun onServiceDisconnected(componentName: ComponentName) {
// Clear references
MultiLinkUdpMessenger.release()
}
}
/**
* Process {type: Message.TYPE_PING} message from remote.
*/
private fun processDeviceInfo(deviceInfo: DeviceInfo) {
val now = SystemClock.uptimeMillis()
// Save device info to local DB
val deviceEntity = DeviceEntity().apply {
imei = deviceInfo.imei
name = deviceInfo.name
updatedAt = now
}
App.db.deviceDao.create(deviceEntity)
// Save video info to local DB
deviceInfo.videos.let { videos ->
val videoEntities = videos.map { video ->
VideoEntity().apply {
deviceImei = deviceInfo.imei
path = video.path
name = video.name
length = video.length
updatedAt = now
}
}
App.db.videoDao.create(videoEntities)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Start UDP service
bindService(Intent(applicationContext, UdpSocketService::class.java), conn, Context.BIND_AUTO_CREATE)
setSupportActionBar(toolbar)
container.adapter = SectionsPagerAdapter(supportFragmentManager)
container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
}
override fun onDestroy() {
// Stop UDP service
unbindService(conn)
super.onDestroy()
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> DevicesFragment_.builder().build()
1 -> VideosFragment_.builder().build()
else -> throw IllegalStateException("No more tabs")
}
}
override fun getCount(): Int {
return 2
}
}
companion object {
const val TAG = "MainActivity"
}
}
| apache-2.0 | fd76fbc62ebf15a28f505261156aad73 | 30.3 | 109 | 0.660277 | 4.988048 | false | false | false | false |
Widgetlabs/fleet | fleet/units/src/main/kotlin/eu/widgetlabs/fleet/units/Length.kt | 1 | 2266 | package eu.widgetlabs.fleet.units
class Length private constructor(valueInMeters: Double) : Measurement<LengthUnit>(LengthUnit.METERS, valueInMeters) {
override fun valueInUnit(unit: LengthUnit): Double {
when (unit) {
LengthUnit.CENTIMETER -> return rawValue * CENTIMETERS_PER_METER
LengthUnit.MILES -> return rawValue * MILES_PER_METER
LengthUnit.FEET -> return rawValue * FEET_PER_METER
LengthUnit.INCH -> return rawValue * INCH_PER_METER
LengthUnit.KILOMETERS -> return rawValue * KILOMETERS_PER_METER
else -> return rawValue
}
}
companion object {
const val METERS_PER_CENTIMETER = 0.001
const val METERS_PER_FEET = 0.3048
const val METERS_PER_KILOMETER = 1000.0
const val METERS_PER_MILE = 1609.344
const val CENTIMETERS_PER_METER = 100.0
val FEET_PER_METER = 1.0 / METERS_PER_FEET
const val INCH_PER_METER = 39.3701
val KILOMETERS_PER_METER = 1.0 / METERS_PER_KILOMETER
val MILES_PER_METER = 1.0 / METERS_PER_MILE
@JvmStatic
fun centimeters(valueInCentimeters: Double?): Length? {
return if (valueInCentimeters != null) Length(valueInCentimeters.toDouble() * METERS_PER_CENTIMETER) else null
}
@JvmStatic
fun feet(valueInFeet: Double?): Length? {
return if (valueInFeet != null) Length(valueInFeet.toDouble() * METERS_PER_FEET) else null
}
@JvmStatic
fun inch(valueInInch: Double?): Length? {
return if (valueInInch != null) Length(valueInInch.toDouble() / INCH_PER_METER) else null
}
@JvmStatic
fun kilometers(valueInKilometers: Double?): Length? {
return if (valueInKilometers != null) Length(valueInKilometers.toDouble() * METERS_PER_KILOMETER) else null
}
@JvmStatic
fun meters(valueInMeters: Double?): Length? {
return if (valueInMeters != null) Length(valueInMeters.toDouble()) else null
}
@JvmStatic
fun miles(valueInMiles: Double?): Length? {
return if (valueInMiles != null) Length(valueInMiles.toDouble() * METERS_PER_MILE) else null
}
}
}
| mit | 9301308abf7a556cc06e993629e0e81a | 33.861538 | 122 | 0.627096 | 4.07554 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/concurrency/ThreadPool.kt | 1 | 1403 | package au.com.codeka.warworlds.server.concurrency
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
/**
* A pool of threads that we use for running things on [Threads.BACKGROUND].
*
* @param thread The [Threads] of the thread pool, that we use to name individual threads.
* @param maxQueuedItems The maximum number of items we'll allow to be queued.
* @param minThreads The minimum number of threads in the thread pool.
* @param maxThreads The maximum number of threads in the thread pool.
* @param keepAliveMs The number of milliseconds to keep an idle thread in the thread pool.
*/
class ThreadPool(
private val thread: Threads, maxQueuedItems: Int, minThreads: Int, maxThreads: Int,
keepAliveMs: Long) {
private val executor: Executor
init {
val threadFactory: ThreadFactory = object : ThreadFactory {
private val count = AtomicInteger(1)
override fun newThread(r: Runnable): Thread {
return Thread(r, "$thread #${count.getAndIncrement()}")
}
}
val workQueue: BlockingQueue<Runnable> = LinkedBlockingQueue(maxQueuedItems)
executor = ThreadPoolExecutor(
minThreads, maxThreads, keepAliveMs, TimeUnit.MILLISECONDS, workQueue, threadFactory)
}
fun runTask(runnable: Runnable) {
executor.execute(runnable)
}
fun isThread(thread: Threads): Boolean {
return thread == this.thread
}
} | mit | ac3bf57b7a45d63e2913bc1d2426a79d | 35 | 93 | 0.729865 | 4.384375 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/music/MusicContext.kt | 1 | 2122 | package com.xenoage.zong.core.music
import com.xenoage.zong.core.music.chord.Accidental
import com.xenoage.zong.core.music.clef.ClefType
import com.xenoage.zong.core.music.clef.clefTreble
import com.xenoage.zong.core.music.key.Key
import com.xenoage.zong.core.music.key.TraditionalKey
import com.xenoage.zong.core.music.key.TraditionalKey.Mode
/**
* A music context provides information about the musical state at a specific position.
*
* These are the current clef, the key signature, the list of accidentals and the number of staff lines.
*/
class MusicContext(
/** The current clef. */
val clef: ClefType,
/** The current key signature. */
val key: Key,
/** The list of current accidentals (key: pitch without alter, value: alter). */
val accidentals: Map<Pitch, Int>,
/** The number of staff lines. */
val linesCount: Int
) {
/** Creates a context with the given clef, key and list of accidentals. */
constructor(clef: ClefType, key: Key, accidentals: Array<Pitch>, linesCount: Int) :
this(clef, key,
if(accidentals.size == 0) noAccidentals else accidentals.associate { it.withoutAlter() to it.alter },
linesCount)
/** Computes and returns the line position of the given pitch. */
fun getLP(pitch: Pitch): LP =
clef.getLP(pitch)
/** Gets the accidental for the given pitch. When no accidental is needed, null is returned. */
fun getAccidental(pitch: Pitch): Accidental? {
//look, if this pitch is already set as an accidental
val alter = accidentals[pitch.withoutAlter()]
return if (alter != null) {
if (alter == pitch.alter)
null //we need no accidental
else
Accidental.fromAlter(pitch.alter) //we need to show the accidental
}
//look, if this alteration is already set in the key signature
else if (key.alterations[pitch.step.ordinal] === pitch.alter)
null //we need no accidental
else
Accidental.fromAlter(pitch.alter) //we need to show the accidental
}
companion object {
val noAccidentals = mapOf<Pitch, Int>()
val simpleMusicContext =
MusicContext(clefTreble, TraditionalKey(0, Mode.Major), noAccidentals, 5)
}
}
| agpl-3.0 | 577553ff5582cb659dc3e881417f51b1 | 33.786885 | 106 | 0.722432 | 3.310452 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/lints/RsUnreachableCodeInspection.kt | 3 | 3313 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.refactoring.suggested.stripWhitespace
import org.rust.ide.injected.isDoctestInjection
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.rangeWithPrevSpace
import org.rust.lang.core.psi.ext.startOffset
import org.rust.lang.core.types.controlFlowGraph
import org.rust.openapiext.document
import org.rust.stdext.mapToMutableList
import java.util.*
class RsUnreachableCodeInspection : RsLintInspection() {
override fun getDisplayName(): String = "Unreachable code"
override fun getLint(element: PsiElement): RsLint = RsLint.UnreachableCode
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
override fun visitFunction(func: RsFunction) {
if (func.isDoctestInjection) return
val controlFlowGraph = func.controlFlowGraph ?: return
val elementsToReport = controlFlowGraph
.unreachableElements
.takeIf { it.isNotEmpty() }
?: return
// Collect text ranges of unreachable elements and merge them in order to highlight
// most enclosing ranges entirely, instead of highlighting each element separately
val sortedRanges = elementsToReport
.filter { it.isPhysical }
.mapToMutableList { it.rangeWithPrevSpace }
.apply { sortWith(Segment.BY_START_OFFSET_THEN_END_OFFSET) }
.takeIf { it.isNotEmpty() }
?: return
val mergedRanges = mergeRanges(sortedRanges)
for (range in mergedRanges) {
registerUnreachableProblem(holder, func, range)
}
}
}
/** Merges intersecting (including adjacent) text ranges into one */
private fun mergeRanges(sortedRanges: List<TextRange>): Collection<TextRange> {
val mergedRanges = ArrayDeque<TextRange>()
mergedRanges.add(sortedRanges[0])
for (range in sortedRanges.drop(1)) {
val leftNeighbour = mergedRanges.peek()
if (leftNeighbour.intersects(range)) {
mergedRanges.pop()
mergedRanges.push(leftNeighbour.union(range))
} else {
mergedRanges.push(range)
}
}
return mergedRanges
}
private fun registerUnreachableProblem(holder: RsProblemsHolder, func: RsFunction, range: TextRange) {
val chars = func.containingFile.document?.immutableCharSequence ?: return
val strippedRangeInFunction = range.stripWhitespace(chars).shiftLeft(func.startOffset)
holder.registerLintProblem(
func,
"Unreachable code",
strippedRangeInFunction,
RsLintHighlightingType.UNUSED_SYMBOL,
listOf(SubstituteTextFix.delete("Remove unreachable code", func.containingFile, range))
)
}
}
| mit | ccecb51494fc3bc1e9464be8e09d4b99 | 38.915663 | 106 | 0.677634 | 4.753228 | false | false | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/oauth/AccessToken.kt | 1 | 1417 | package com.twitter.meil_mitu.twitter4hk.api.oauth
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.AbsPost
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.converter.IOauthTokenConverter
import com.twitter.meil_mitu.twitter4hk.data.OauthToken
import com.twitter.meil_mitu.twitter4hk.exception.IncorrectException
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
import com.twitter.meil_mitu.twitter4hk.oauth.Oauth
class AccessToken(
oauth: AbsOauth,
protected val json: IOauthTokenConverter<OauthToken>,
oauthVerifier: String) : AbsPost<OauthToken>(oauth) {
private var oauth1: Oauth
private var oauthVerifier: String? by stringParam("oauth_verifier")
override val url = "https://api.twitter.com/oauth/access_token"
override val allowOauthType = OauthType.oauth1
override val isAuthorization = true
init {
if (oauth is Oauth == false) {
throw IncorrectException("Oauth is not Oauth")
}
oauth1 = oauth as Oauth
this.oauthVerifier = oauthVerifier
}
@Throws(Twitter4HKException::class)
override fun call(): OauthToken {
val token = json.toOauthToken(oauth.post(this))
oauth1.accessToken = token.oauthToken
oauth1.accessTokenSecret = token.oauthTokenSecret
return token
}
}
| mit | 88a59d40c7bf385d1072038281255921 | 36.289474 | 71 | 0.737474 | 4.095376 | false | false | false | false |
McGars/basekitk | basekitk/src/main/kotlin/com/mcgars/basekitk/features/recycler2/AdapterDelegatesManager.kt | 1 | 13921 | /*
* Copyright (c) 2015 Hannes Dorfmann.
*
* 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.mcgars.basekitk.features.recycler2
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
/**
* This class is the element that ties [RecyclerView.Adapter] together with [ ].
*
*
* So you have to add / register your [AdapterDelegate]s to this manager by calling [ ][.addDelegate]
*
*
*
* Next you have to add this AdapterDelegatesManager to the [RecyclerView.Adapter] by calling
* corresponding methods:
*
* * [.getItemViewType]: Must be called from [ ][RecyclerView.Adapter.getItemViewType]
* * [.onCreateViewHolder]: Must be called from [ ][RecyclerView.Adapter.onCreateViewHolder]
* * [.onBindViewHolder]: Must be called from [ ][RecyclerView.Adapter.onBindViewHolder]
*
* You can also set a fallback [AdapterDelegate] by using [ ][.setFallbackDelegate] that will be used if no [AdapterDelegate] is
* responsible to handle a certain view type. If no fallback is specified, an Exception will be
* thrown if no [AdapterDelegate] is responsible to handle a certain view type
*
* @param <T> The type of the datasource of the adapter
* *
* @author Hannes Dorfmann
</T> */
class AdapterDelegatesManager<T> {
/**
* Map for ViewType to AdapterDelegate
*/
var delegates: SparseArrayCompat<AdapterDelegate<T>> = SparseArrayCompat()
/**
* Get the fallback delegate
* @return The fallback delegate or `null` if no fallback delegate has been set
* @see .setFallbackDelegate
*/
var fallbackDelegate: AdapterDelegate<T>? = null
/**
* Adds an [AdapterDelegate].
* **This method automatically assign internally the view type integer by using the next
* unused**
* Internally calls [.addDelegate] with
* allowReplacingDelegate = false as parameter.
* @param delegate the delegate to add
* @return self
* @throws NullPointerException if passed delegate is null
* @see addDelegate
*/
fun addDelegate(delegate: AdapterDelegate<T>): AdapterDelegatesManager<T> {
// algorithm could be improved since there could be holes,
// but it's very unlikely that we reach Integer.MAX_VALUE and run out of unused indexes
var viewType = delegates.size()
while (delegates.get(viewType) != null) {
viewType++
if (viewType == FALLBACK_DELEGATE_VIEW_TYPE) {
throw IllegalArgumentException(
"Oops, we are very close to Integer.MAX_VALUE. It seems that there are no more free and unused view type integers left to add another AdapterDelegate.")
}
}
return addDelegate(viewType, delegate)
}
/**
* Adds an [AdapterDelegate].
* @param viewType The viewType id
* *
* @param allowReplacingDelegate if true, you allow to replacing the given delegate any previous
* * delegate for the same view type. if false, you disallow and a [IllegalArgumentException]
* * will be thrown if you try to replace an already registered [AdapterDelegate] for the
* * same view type.
* *
* @param delegate The delegate to add
* *
* @throws IllegalArgumentException if **allowReplacingDelegate** is false and an [ ] is already added (registered)
* * with the same ViewType.
* *
* @throws IllegalArgumentException if viewType is [.FALLBACK_DELEGATE_VIEW_TYPE] which is
* * reserved
* *
* @see .addDelegate
* @see .addDelegate
* @see .setFallbackDelegate
*/
fun addDelegate(
viewType: Int,
delegate: AdapterDelegate<T>,
allowReplacingDelegate: Boolean = false
): AdapterDelegatesManager<T> {
if (viewType == FALLBACK_DELEGATE_VIEW_TYPE) {
throw IllegalArgumentException("The view type = "
+ FALLBACK_DELEGATE_VIEW_TYPE
+ " is reserved for fallback adapter delegate (see setFallbackDelegate() ). Please use another view type.")
}
if (!allowReplacingDelegate && delegates.get(viewType) != null) {
throw IllegalArgumentException(
"An AdapterDelegate is already registered for the viewType = "
+ viewType
+ ". Already registered AdapterDelegate is "
+ delegates.get(viewType))
}
delegates.put(viewType, delegate)
return this
}
/**
* Removes a previously registered delegate if and only if the passed delegate is registered
* (checks the reference of the object). This will not remove any other delegate for the same
* viewType (if there is any).
* @param delegate The delegate to remove
* *
* @return self
*/
fun removeDelegate(delegate: AdapterDelegate<T>): AdapterDelegatesManager<T> {
val indexToRemove = delegates.indexOfValue(delegate)
if (indexToRemove >= 0) {
delegates.removeAt(indexToRemove)
}
return this
}
/**
* Removes the adapterDelegate for the given view types.
* @param viewType The Viewtype
* @return self
*/
fun removeDelegate(viewType: Int): AdapterDelegatesManager<T> {
delegates.remove(viewType)
return this
}
/**
* Must be called from [RecyclerView.Adapter.getItemViewType]. Internally it scans all
* the registered [AdapterDelegate] and picks the right one to return the ViewType integer.
* @param items Adapter's data source
* @param position the position in adapters data source
* @return the ViewType (integer). Returns [.FALLBACK_DELEGATE_VIEW_TYPE] in case that the
* * fallback adapter delegate should be used
* @throws NullPointerException if no [AdapterDelegate] has been found that is
* * responsible for the given data element in data set (No [AdapterDelegate] for the given
* * ViewType)
* @throws NullPointerException if items is null
*/
fun getItemViewType(items: List<T>, position: Int): Int {
val delegatesCount = delegates.size()
for (i in 0 until delegatesCount) {
val delegate = delegates.valueAt(i)
if (delegate.isForViewType(items, position)) {
return delegates.keyAt(i)
}
}
if (fallbackDelegate != null) {
return FALLBACK_DELEGATE_VIEW_TYPE
}
throw NullPointerException(
"No AdapterDelegate added that matches position=$position in data source")
}
/**
* This method must be called in [RecyclerView.Adapter.onCreateViewHolder]
* @param parent the parent
* @param viewType the view type
* @return The new created ViewHolder
* @throws NullPointerException if no AdapterDelegate has been registered for ViewHolders
* * viewType
*/
fun onCreateViewHolder(kitAdapter: KitAdapter<T>, parent: ViewGroup, viewType: Int) = getDelegateForViewType(viewType)?.run {
onCreateViewHolder(kitAdapter, parent)
} ?: throw NullPointerException("No AdapterDelegate added for ViewType $viewType")
/**
* Must be called from[RecyclerView.Adapter.onBindViewHolder]
* @param items Adapter's data source
* *
* @param position the position in data source
* *
* @param viewHolder the ViewHolder to bind
* *
* @param payloads A non-null list of merged payloads. Can be empty list if requires full update.
* *
* @throws NullPointerException if no AdapterDelegate has been registered for ViewHolders
* * viewType
*/
@JvmOverloads
fun onBindViewHolder(items: List<T>, position: Int,
viewHolder: RecyclerView.ViewHolder, payloads: List<Any> = PAYLOADS_EMPTY_LIST) {
val delegate = getDelegateForViewType(viewHolder.itemViewType)
?: throw NullPointerException("No delegate found for item at position = "
+ position
+ " for viewType = "
+ viewHolder.itemViewType)
delegate.onBindViewHolder(items, position, viewHolder, payloads)
}
/**
* Must be called from [RecyclerView.Adapter.onViewRecycled]
* @param viewHolder The ViewHolder for the view being recycled
*/
fun onViewRecycled(viewHolder: RecyclerView.ViewHolder) {
val delegate = getDelegateForViewType(viewHolder.itemViewType)
?: throw NullPointerException("No delegate found for "
+ viewHolder
+ " for item at position = "
+ viewHolder.adapterPosition
+ " for viewType = "
+ viewHolder.itemViewType)
delegate.onViewRecycled(viewHolder)
}
/**
* Must be called from [RecyclerView.Adapter.onFailedToRecycleView]
* @param viewHolder The ViewHolder containing the View that could not be recycled due to its
* * transient state.
* *
* @return True if the View should be recycled, false otherwise. Note that if this method
* * returns `true`, RecyclerView *will ignore* the transient state of
* * the View and recycle it regardless. If this method returns `false`,
* * RecyclerView will check the View's transient state again before giving a final decision.
* * Default implementation returns false.
*/
fun onFailedToRecycleView(viewHolder: RecyclerView.ViewHolder): Boolean {
val delegate = getDelegateForViewType(viewHolder.itemViewType)
?: throw NullPointerException("No delegate found for "
+ viewHolder
+ " for item at position = "
+ viewHolder.adapterPosition
+ " for viewType = "
+ viewHolder.itemViewType)
return delegate.onFailedToRecycleView(viewHolder)
}
/**
* Must be called from [RecyclerView.Adapter.onViewAttachedToWindow]
* @param viewHolder Holder of the view being attached
*/
fun onViewAttachedToWindow(kitAdapter: KitAdapter<T>, viewHolder: RecyclerView.ViewHolder) {
val delegate = getDelegateForViewType(viewHolder.itemViewType)
?: throw NullPointerException("No delegate found for "
+ viewHolder
+ " for item at position = "
+ viewHolder.adapterPosition
+ " for viewType = "
+ viewHolder.itemViewType)
delegate.onViewAttachedToWindow(kitAdapter, viewHolder)
}
/**
* Must be called from [RecyclerView.Adapter.onViewDetachedFromWindow]
* @param viewHolder Holder of the view being attached
*/
fun onViewDetachedFromWindow(viewHolder: RecyclerView.ViewHolder) {
val delegate = getDelegateForViewType(viewHolder.itemViewType)
?: throw NullPointerException("No delegate found for "
+ viewHolder
+ " for item at position = "
+ viewHolder.adapterPosition
+ " for viewType = "
+ viewHolder.itemViewType)
delegate.onViewDetachedFromWindow(viewHolder)
}
/**
* Set a fallback delegate that should be used if no [AdapterDelegate] has been found that
* can handle a certain view type.
* @param fallbackDelegate The [AdapterDelegate] that should be used as fallback if no
* * other AdapterDelegate has handled a certain view type. `null` you can set this to
* * null if
* * you want to remove a previously set fallback AdapterDelegate
*/
fun setFallbackDelegate(
fallbackDelegate: AdapterDelegate<T>?): AdapterDelegatesManager<T> {
this.fallbackDelegate = fallbackDelegate
return this
}
/**
* Get the view type integer for the given [AdapterDelegate]
* @param delegate The delegate we want to know the view type for
* *
* @return -1 if passed delegate is unknown, otherwise the view type integer
*/
fun getViewType(delegate: AdapterDelegate<T>): Int {
val index = delegates.indexOfValue(delegate)
if (index == -1) {
return -1
}
return delegates.keyAt(index)
}
/**
* Get the [AdapterDelegate] associated with the given view type integer
* @param viewType The view type integer we want to retrieve the associated
* * delegate for.
* *
* @return The [AdapterDelegate] associated with the view type param if it exists,
* * the fallback delegate otherwise if it is set or returns `null` if no delegate is
* * associated to this viewType (and no fallback has been set).
*/
fun getDelegateForViewType(viewType: Int) = delegates.get(viewType) ?: fallbackDelegate
companion object {
/**
* This id is used internally to claim that the []
*/
internal val FALLBACK_DELEGATE_VIEW_TYPE = Integer.MAX_VALUE - 1
/**
* Used internally for [.onBindViewHolder] as empty
* payload parameter
*/
private val PAYLOADS_EMPTY_LIST = emptyList<Any>()
}
} | apache-2.0 | 1f38a8da21e1ac1e46dc12e12bc8c8ff | 37.997199 | 176 | 0.64083 | 5.091807 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/OxygenSaturationRecord.kt | 3 | 2358 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.health.connect.client.records
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Percentage
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the amount of oxygen circulating in the blood, measured as a percentage of
* oxygen-saturated hemoglobin. Each record represents a single blood oxygen saturation reading at
* the time of measurement.
*/
public class OxygenSaturationRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/** Percentage. Required field. Valid range: 0-100. */
public val percentage: Percentage,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
init {
requireNonNegative(value = percentage.value, name = "percentage")
percentage.value.requireNotMore(other = 100.0, name = "percentage")
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is OxygenSaturationRecord) return false
if (percentage != other.percentage) return false
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = percentage.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
}
| apache-2.0 | 00d0af871a7fc8bc77f7cee41aea338a | 34.727273 | 98 | 0.687023 | 4.310786 | false | false | false | false |
androidx/androidx | compose/ui/ui-test-junit4/src/androidAndroidTest/kotlin/androidx/compose/ui/test/junit4/FirstDrawTest.kt | 3 | 3488 | /*
* 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.test.junit4
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.runAndroidComposeUiTest
import androidx.compose.ui.test.runComposeUiTest
import androidx.test.filters.LargeTest
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
@MediumTest
@OptIn(ExperimentalTestApi::class)
class FirstDrawTest {
/**
* Tests that the compose tree has been drawn at least once when
* [ComposeUiTest.setContent] finishes.
*/
@LargeTest
@Test
fun waitsForFirstDraw_withoutOnIdle() = runComposeUiTest {
var drawn = false
setContent {
Canvas(Modifier.fillMaxSize()) {
drawn = true
}
}
// waitForIdle() shouldn't be necessary
assertThat(drawn).isTrue()
}
/**
* Tests that [ComposeUiTest.waitForIdle] doesn't timeout when the compose tree is
* completely off-screen and will hence not be drawn.
*/
@Test
fun waitsForOutOfBoundsComposeView() = runAndroidComposeUiTest<ComponentActivity> {
var drawn = false
runOnUiThread {
// Set the compose content in a FrameLayout that is completely placed out of the
// screen, and set clipToPadding to make sure the content won't be drawn.
val root = object : FrameLayout(activity!!) {
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
// Place our child out of bounds
getChildAt(0).layout(-200, 0, -100, 100)
}
}.apply {
// Enforce clipping:
setPadding(1, 1, 1, 1)
clipToPadding = true
}
val outOfBoundsView = ComposeView(activity!!).apply {
layoutParams = ViewGroup.MarginLayoutParams(100, 100)
}
root.addView(outOfBoundsView)
activity!!.setContentView(root)
outOfBoundsView.setContent {
// If you see this box when running the test, the test is setup incorrectly
Canvas(Modifier.fillMaxSize()) {
drawRect(Color.Yellow)
drawn = true
}
}
}
// onIdle shouldn't timeout
waitForIdle()
// The compose view was off-screen, so it hasn't drawn yet
assertThat(drawn).isFalse()
}
} | apache-2.0 | a25cf79ec1c10f3c4e452c68f07ddd22 | 33.89 | 92 | 0.653383 | 4.713514 | false | true | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/lastfm/ArtistEntity.kt | 1 | 1600 | package taiwan.no1.app.ssfm.models.entities.lastfm
import com.google.gson.annotations.SerializedName
/**
* @author jieyi
* @since 10/16/17
*/
data class ArtistEntity(var artist: Artist?) {
data class Artist(var name: String? = "",
var mbid: String? = "",
var match: String? = "",
var url: String? = "",
@SerializedName("image")
var images: List<Image>? = listOf(),
var streamable: String? = "",
var listeners: String? = "",
@SerializedName("ontour")
var onTour: String? = "",
@SerializedName("playcount")
var playCount: String? = "",
var stats: Stats? = null,
var similar: Similar? = null,
var tags: Tags? = null,
var bio: Bio? = null) : BaseEntity
data class Bio(var links: Links?,
var published: String?,
var summary: String?,
var content: String?)
data class Links(var link: Link?)
data class Link(@SerializedName("#text")
var text: String?,
var rel: String?,
var href: String?)
data class Stats(var listeners: String?,
@SerializedName("playcount")
var playCount: String?)
data class Similar(@SerializedName("artist")
var artists: List<Artist>?)
}
| apache-2.0 | 4333545565c413ac7e1106a1c171f012 | 34.555556 | 58 | 0.46375 | 5.144695 | false | false | false | false |
taigua/exercism | kotlin/simple-cipher/src/main/kotlin/Cipher.kt | 1 | 889 | import java.util.Random
class Cipher(key: String = genKey()) {
companion object {
private val KEY_LENGTH = 100
private fun genKey() : String {
val rand = Random()
return (1..KEY_LENGTH).map {'a' + rand.nextInt(26)}.joinToString("")
}
}
init {
if (key.isEmpty() || !key.matches(Regex("[a-z]+")))
throw IllegalArgumentException()
}
val key: String = key
fun encode(input: String) = code(key, input, 1)
fun decode(input: String) = code(key, input, -1)
private fun mod(n: Int, m: Int) = ((n % m) + m) % m
private fun code(key: String, text: String, sign: Int) : String {
return text.toList().foldIndexed("") { i, output, letter ->
val offset = sign * (key[mod(i, key.length)] - 'a')
output + ('a' + mod(letter - 'a' + offset, 26))
}
}
} | mit | 076f6f88c4cac7e5931fa55be09345cc | 25.969697 | 80 | 0.530934 | 3.556 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/CalendarSync.kt | 1 | 16372 | /**
* Copyright (c) 2015 Vojtech Kral
* LICENSE:
* Simpletask 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.
* Simpletask 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 Sinpletask. If not, see
* //www.gnu.org/licenses/>.
* @author Vojtech Kral
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2015 Vojtech Kral
*/
package nl.mpcjanssen.simpletask
import java.util.*
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.ContentResolver
import android.content.ContentValues
import android.content.ContentProviderOperation
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Color
import android.net.Uri
import android.provider.CalendarContract
import android.provider.CalendarContract.*
import android.support.v4.content.ContextCompat
import android.util.Log
import hirondelle.date4j.DateTime
import nl.mpcjanssen.simpletask.task.*
import nl.mpcjanssen.simpletask.util.Config
import nl.mpcjanssen.simpletask.util.toDateTime
private enum class EvtStatus {
KEEP,
DELETE,
INSERT,
}
data class EvtKey(val dtStart: Long, val title: String)
private class Evt(
var id: Long,
var dtStart: Long,
var title: String,
var description: String,
var remID: Long = -1,
var remMinutes: Long = -1,
var status: EvtStatus = EvtStatus.DELETE) {
constructor(cursor: Cursor) // Create from a db record
: this(cursor.getLong(0), cursor.getLong(2), cursor.getString(3), cursor.getString(4))
constructor(date: DateTime, title: String, desc: String) // Create from a Task
: this(-1, date.getMilliseconds(CalendarSync.UTC), title, desc, -1, -1, EvtStatus.INSERT) {
val localZone = Calendar.getInstance().timeZone
val remMargin = Config.reminderDays * 1440
val remTime = Config.reminderTime
val remDT = DateTime.forTimeOnly(remTime / 60, remTime % 60, 0, 0)
// Reminder data:
// Only create reminder if it's in the future, otherwise it would go off immediately
// NOTE: DateTime.minus()/plus() only accept values >=0 and <10000 (goddamnit date4j!), hence the division.
var remDate = date.minus(0, 0, 0, remMargin / 60, remMargin % 60, 0, 0, DateTime.DayOverflow.Spillover)
remDate = remDate.plus(0, 0, 0, remDT.hour, remDT.minute, 0, 0, DateTime.DayOverflow.Spillover)
if (remDate.isInTheFuture(localZone)) {
remID = 0L // 0 = reminder entry to be created
remMinutes = remDate.numSecondsFrom(date) / 60
}
}
fun key() = EvtKey(dtStart, title)
infix fun equals(other: Evt) =
dtStart == other.dtStart &&
title.equals(other.title) &&
description.equals(other.description) &&
remMinutes == other.remMinutes
@TargetApi(16)
fun addOp(list: ArrayList<ContentProviderOperation>, calID: Long) {
if (status == EvtStatus.DELETE) {
val args = arrayOf(id.toString())
list.add(ContentProviderOperation.newDelete(Events.CONTENT_URI)
.withSelection(Events._ID + "=?", args)
.build())
if (remID >= 0) {
val remArgs = arrayOf(remID.toString())
list.add(ContentProviderOperation.newDelete(Reminders.CONTENT_URI)
.withSelection(Reminders._ID + "=?", remArgs)
.build())
}
} else if (status == EvtStatus.INSERT) {
list.add(ContentProviderOperation.newInsert(Events.CONTENT_URI)
.withValue(Events.CALENDAR_ID, calID)
.withValue(Events.TITLE, title)
.withValue(Events.DTSTART, dtStart)
.withValue(Events.DTEND, dtStart + 24 * 60 * 60 * 1000) // Needs to be set to DTSTART +24h, otherwise reminders don't work
.withValue(Events.ALL_DAY, 1)
.withValue(Events.DESCRIPTION, description)
.withValue(Events.EVENT_TIMEZONE, CalendarSync.UTC.id)
.withValue(Events.STATUS, Events.STATUS_CONFIRMED)
.withValue(Events.HAS_ATTENDEE_DATA, true) // If this is not set, Calendar app is confused about Event.STATUS
.withValue(Events.CUSTOM_APP_PACKAGE, TodoApplication.app.packageName)
.withValue(Events.CUSTOM_APP_URI, Uri.withAppendedPath(Simpletask.URI_SEARCH, title).toString())
.build())
if (remID >= 0) {
val evtIdx = list.size - 1
list.add(ContentProviderOperation.newInsert(Reminders.CONTENT_URI)
.withValueBackReference(Reminders.EVENT_ID, evtIdx)
.withValue(Reminders.MINUTES, remMinutes)
.withValue(Reminders.METHOD, Reminders.METHOD_ALERT)
.build())
}
}
}
}
private class SyncStats(val inserts: Long, val keeps: Long, val deletes: Long)
/**
* A hashmap of Evts
*
* In order to make calendar notifications sync more efficient, we want to only add/remove those
* that actually need to be added/removed. However, Simpletask doesn't track task identity
* and consequently we don't know what changed, not to mention todo.txt might've also
* been changed outside of Simpletask.
*
* And so we need to diff between task list and what's actually in the calendar.
* To do that, this hashmap is used, which stores events (Evt) by their date and text (EvtKey).
* (Note that there might be multiple equal events, hence the LinkedList as the map value type.)
* When constructed, the hashmap loads events from the DB, all of which are initially marked for deletion.
* Then, task list is merged in: Each event (that comes from a task) is located in the hashmap
* - if an equal one is found, it is marked to be kept unchanged.
* If not, new event is inserted into the map and marked for insertion.
*
* Finally, the hashmap contents are applied - contained events are iterated and inserted/deleted as appropriate.
* This is done using ContentResolver.applyBatch for better efficiency.
*/
@SuppressLint("Recycle", "NewAPI")
private class EvtMap private constructor() : HashMap<EvtKey, LinkedList<Evt>>() {
@SuppressLint("MissingPermission")
constructor(cr: ContentResolver, calID: Long) : this() {
val evtPrj = arrayOf(Events._ID, Events.CALENDAR_ID, Events.DTSTART, Events.TITLE, Events.DESCRIPTION)
val evtSel = "${Events.CALENDAR_ID} = ?"
val evtArgs = arrayOf(calID.toString())
val remPrj = arrayOf(Reminders._ID, Reminders.EVENT_ID, Reminders.MINUTES)
val remSel = "${Reminders.EVENT_ID} = ?"
val evts = cr.query(Events.CONTENT_URI, evtPrj, evtSel, evtArgs, null)
?: throw IllegalArgumentException("null cursor")
while (evts.moveToNext()) {
val evt = Evt(evts)
// Try to find a matching reminder
val remArgs = arrayOf(evt.id.toString())
val rem = cr.query(Reminders.CONTENT_URI, remPrj, remSel, remArgs, null)
?: throw IllegalArgumentException("null cursor")
if (rem.count > 0) {
rem.moveToFirst()
evt.remID = rem.getLong(0)
evt.remMinutes = rem.getLong(2)
}
rem.close()
// Insert into the hashmap
val evtkey = evt.key()
var list = this.get(evtkey)
if (list != null) list.add(evt)
else {
list = LinkedList<Evt>()
list.add(evt)
this.put(evtkey, list)
}
}
evts.close()
}
fun mergeEvt(evt: Evt) {
val key = evt.key()
val list = this.get(key)
evt.status = EvtStatus.INSERT
if (list == null) {
val nlist = LinkedList<Evt>()
nlist.add(evt)
this.put(key, nlist)
} else {
for (oevt in list) {
if (oevt.status == EvtStatus.DELETE && oevt equals evt) {
oevt.status = EvtStatus.KEEP
return
}
}
list.add(evt)
}
}
fun mergeTasks(tasks: List<Task>) {
for (task in tasks) {
if (task.isCompleted()) continue
var text: String? = null
// Check due date:
var dt = task.dueDate?.toDateTime()
if (Config.isSyncDues && dt != null) {
text = task.showParts(CalendarSync.TASK_TOKENS)
val evt = Evt(dt, text, TodoApplication.app.getString(R.string.calendar_sync_desc_due))
mergeEvt(evt)
}
// Check threshold date:
dt = task.thresholdDate?.toDateTime()
if (Config.isSyncThresholds && dt != null) {
if (text == null) text = task.showParts(CalendarSync.TASK_TOKENS)
val evt = Evt(dt, text, TodoApplication.app.getString(R.string.calendar_sync_desc_thre))
mergeEvt(evt)
}
}
}
@SuppressLint("NewApi")
fun apply(cr: ContentResolver, calID: Long): SyncStats {
val ops = ArrayList<ContentProviderOperation>()
var ins = 0L
var kps = 0L
var dels = 0L
for (list in values) {
for (evt in list) {
if (evt.status == EvtStatus.INSERT) ins++
else if (evt.status == EvtStatus.KEEP) kps++
else if (evt.status == EvtStatus.DELETE) dels++
evt.addOp(ops, calID)
}
}
cr.applyBatch(CalendarContract.AUTHORITY, ops)
return SyncStats(ins, kps, dels)
}
}
object CalendarSync {
private val ACCOUNT_NAME = "Simpletask Calendar"
private val ACCOUNT_TYPE = CalendarContract.ACCOUNT_TYPE_LOCAL
private val CAL_URI = Calendars.CONTENT_URI.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE)
.build()
private val CAL_NAME = "simpletask_reminders_v34SsjC7mwK9WSVI"
private val CAL_COLOR = Color.BLUE // Chosen arbitrarily...
private val EVT_DURATION_DAY = 24 * 60 * 60 * 1000 // ie. 24 hours
private val SYNC_DELAY_MS = 20 * 1000
private val TAG = "CalendarSync"
val UTC: TimeZone = TimeZone.getTimeZone("UTC")
val TASK_TOKENS: (TToken) -> Boolean = {
when (it) {
is CompletedToken, is CreateDateToken, is CompletedDateToken, is PriorityToken, is ThresholdDateToken,
is DueDateToken, is HiddenToken, is RecurrenceToken -> false
else -> true
}
}
private class SyncRunnable : Runnable {
override fun run() {
try {
sync()
} catch (e: Exception) {
Log.e(TAG, "STPE exception", e)
}
}
}
private val m_sync_runnable: SyncRunnable
private val m_cr: ContentResolver
private var m_rem_margin = 1440
private var m_rem_time = DateTime.forTimeOnly(12, 0, 0, 0)
private val m_stpe: ScheduledThreadPoolExecutor
@SuppressLint("Recycle")
private fun findCalendar(): Long {
val projection = arrayOf(Calendars._ID, Calendars.NAME)
val selection = Calendars.NAME + " = ?"
val args = arrayOf(CAL_NAME)
/* Check for calendar permission */
val permissionCheck = ContextCompat.checkSelfPermission(TodoApplication.app,
Manifest.permission.WRITE_CALENDAR)
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
if (Config.isSyncDues || Config.isSyncThresholds) {
throw IllegalStateException("no calendar access")
} else {
return -1
}
}
val cursor = m_cr.query(CAL_URI, projection, selection, args, null)
?: throw IllegalArgumentException("null cursor")
if (cursor.count == 0) {
cursor.close()
return -1
}
cursor.moveToFirst()
val ret = cursor.getLong(0)
cursor.close()
return ret
}
private fun addCalendar() {
val cv = ContentValues()
cv.apply {
put(Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
put(Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE)
put(Calendars.NAME, CAL_NAME)
put(Calendars.CALENDAR_DISPLAY_NAME, TodoApplication.app.getString(R.string.calendar_disp_name))
put(Calendars.CALENDAR_COLOR, CAL_COLOR)
put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ)
put(Calendars.OWNER_ACCOUNT, ACCOUNT_NAME)
put(Calendars.VISIBLE, 1)
put(Calendars.SYNC_EVENTS, 1)
}
m_cr.insert(CAL_URI, cv)
}
@SuppressLint("NewApi")
private fun removeCalendar() {
Log.d(TAG, "Removing Simpletask calendar")
val selection = Calendars.NAME + " = ?"
val args = arrayOf(CAL_NAME)
try {
val ret = m_cr.delete(CAL_URI, selection, args)
if (ret == 0)
Log.d(TAG, "No calendar to remove")
else if (ret == 1)
Log.d(TAG, "Calendar removed")
else
Log.e(TAG, "Unexpected return value while removing calendar: " + ret)
} catch (e: Exception) {
Log.e(TAG, "Error while removing calendar", e)
}
}
private fun sync() {
Log.d(TAG, "Checking whether calendar sync is needed")
try {
var calID = findCalendar()
if (!Config.isSyncThresholds && !Config.isSyncDues) {
if (calID >= 0) {
Log.d(TAG, "Calendar sync not enabled")
removeCalendar()
}
return
}
if (calID < 0) {
addCalendar()
calID = findCalendar() // Re-find the calendar, this is needed to verify it has been added
if (calID < 0) {
// This happens when CM privacy guard disallows to write calendar (1)
// OR it allows to write calendar but disallows reading it (2).
// Either way, we cannot continue, but before bailing,
// try to remove Calendar in case we're here because of (2).
Log.d(TAG, "No access to Simpletask calendar")
removeCalendar()
throw IllegalStateException("Calendar nor added")
}
}
Log.d(TAG, "Syncing due/threshold calendar reminders...")
val evtmap = EvtMap(m_cr, calID)
val tasks = TodoList.todoItemsCopy
evtmap.mergeTasks(tasks)
val stats = evtmap.apply(m_cr, calID)
Log.d(TAG, "Sync finished: ${stats.inserts} inserted, ${stats.keeps} unchanged, ${stats.deletes} deleted")
} catch (e: SecurityException) {
Log.e(TAG, "No calendar access permissions granted", e )
} catch (e: Exception) {
Log.e(TAG, "Calendar error", e)
}
}
fun updatedSyncTypes() {
syncLater()
}
init {
m_sync_runnable = SyncRunnable()
m_cr = TodoApplication.app.contentResolver
m_stpe = ScheduledThreadPoolExecutor(1)
}
fun syncLater() {
m_stpe.queue.clear()
m_stpe.schedule(m_sync_runnable, SYNC_DELAY_MS.toLong(), TimeUnit.MILLISECONDS)
}
}
| gpl-3.0 | 5d234b9efe286b92c8b80faa26cf30f1 | 37.704492 | 142 | 0.597972 | 4.252468 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/place_name/AddPlaceName.kt | 1 | 3968 | package de.westnordost.streetcomplete.quests.place_name
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddPlaceName(o: OverpassMapDataDao) : SimpleOverpassQuestType<PlaceNameAnswer>(o) {
override val tagFilters =
"nodes, ways, relations with !name and noname != yes " +
" and (shop and shop !~ no|vacant or tourism = information and information = office " +
" or " +
mapOf(
"amenity" to arrayOf(
"restaurant", "cafe", "ice_cream", "fast_food", "bar", "pub", "biergarten", "food_court", "nightclub", // eat & drink
"cinema", "theatre", "planetarium", "arts_centre", "studio", // culture
"events_venue", "conference_centre", "exhibition_centre", "music_venue", // events
"townhall", "prison", "courthouse", "embassy", "police", "fire_station", "ranger_station", // civic
"bank", "bureau_de_change", "money_transfer", "post_office", "library", "marketplace", "internet_cafe", // commercial
"community_centre", "social_facility", "nursing_home", "childcare", "retirement_home", "social_centre", "youth_centre", // social
"car_wash", "car_rental", "boat_rental", "fuel", // car stuff
"dentist", "doctors", "clinic", "pharmacy", "hospital", // health care
"place_of_worship", "monastery", // religious
"kindergarten", "school", "college", "university", "research_institute", // education
"driving_school", "dive_centre", "language_school", "music_school", // learning
"casino", "brothel", "gambling", "love_hotel", "stripclub", // bad stuff
"animal_boarding", "animal_shelter", "animal_breeding", "veterinary"
),
"tourism" to arrayOf(
"attraction", "zoo", "aquarium", "theme_park", "gallery", "museum", // attractions
"hotel", "guest_house", "motel", "hostel", "alpine_hut", "apartment", "resort", "camp_site", "caravan_site" // accomodations
// and tourism=information, see above
),
"leisure" to arrayOf(
"park", "nature_reserve", "sports_centre", "fitness_centre", "dance", "golf_course",
"water_park", "miniature_golf", "stadium", "marina", "bowling_alley",
"amusement_arcade", "adult_gaming_centre", "tanning_salon", "horse_riding"
),
"office" to arrayOf(
"insurance", "estate_agent", "travel_agent"
)
).map { it.key + " ~ " + it.value.joinToString("|") }.joinToString(" or ") +
")"
override val commitMessage = "Determine place names"
override val icon = R.drawable.ic_quest_label
override fun getTitle(tags: Map<String, String>) = R.string.quest_placeName_title
override fun createForm() = AddPlaceNameForm()
override fun applyAnswerTo(answer: PlaceNameAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is NoPlaceNameSign -> changes.add("noname", "yes")
is PlaceName -> changes.add("name", answer.name)
}
}
}
| gpl-3.0 | b076634bdfeec14f0da71fea86e6c1e9 | 66.254237 | 150 | 0.511089 | 4.399113 | false | false | false | false |
JesseScott/Make-A-Wish | MakeAWish/app/src/main/java/tt/co/jesses/makeawish/helpers/PreferenceHelper.kt | 1 | 1118 | package tt.co.jesses.makeawish.helpers
import android.content.Context
import android.preference.PreferenceManager
import tt.co.jesses.makeawish.R
/**
* Created by jessescott on 2017-02-27.
*/
class PreferenceHelper(private val mContext: Context) {
fun setPrefValueByKey(key: String, value: Boolean) {
val preferences = PreferenceManager.getDefaultSharedPreferences(mContext)
val editor = preferences.edit()
editor.putBoolean(key, value)
editor.apply()
if (key == mContext.getString(R.string.prefs_enable_daytime_alarms) || key == mContext.getString(R.string.prefs_enable_nighttime_alarms)) {
triggerAlarmRegeneration()
}
}
private fun triggerAlarmRegeneration() {
val alarmHelper = AlarmHelper(mContext)
alarmHelper.setAlarms()
}
fun getPrefValueByKey(key: String): Boolean {
val preferences = PreferenceManager.getDefaultSharedPreferences(mContext)
return preferences.getBoolean(key, false)
}
companion object {
private val TAG = PreferenceHelper::class.java.simpleName
}
}
| gpl-2.0 | ce72e5729fc3cbbc91f1e902ba5090d7 | 28.421053 | 147 | 0.701252 | 4.333333 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/screen/SettingsDownloadScreen.kt | 1 | 11872 | package eu.kanade.presentation.more.settings.screen
import android.content.Intent
import android.os.Environment
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.core.net.toUri
import com.hippo.unifile.UniFile
import eu.kanade.domain.category.interactor.GetCategories
import eu.kanade.domain.category.model.Category
import eu.kanade.domain.download.service.DownloadPreferences
import eu.kanade.presentation.category.visualName
import eu.kanade.presentation.more.settings.Preference
import eu.kanade.presentation.more.settings.widget.TriStateListDialog
import eu.kanade.presentation.util.collectAsState
import eu.kanade.tachiyomi.R
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.runBlocking
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
class SettingsDownloadScreen : SearchableSettings {
@ReadOnlyComposable
@Composable
@StringRes
override fun getTitleRes() = R.string.pref_category_downloads
@Composable
override fun getPreferences(): List<Preference> {
val getCategories = remember { Injekt.get<GetCategories>() }
val allCategories by getCategories.subscribe().collectAsState(initial = runBlocking { getCategories.await() })
val downloadPreferences = remember { Injekt.get<DownloadPreferences>() }
return listOf(
getDownloadLocationPreference(downloadPreferences = downloadPreferences),
Preference.PreferenceItem.SwitchPreference(
pref = downloadPreferences.downloadOnlyOverWifi(),
title = stringResource(R.string.connected_to_wifi),
),
Preference.PreferenceItem.SwitchPreference(
pref = downloadPreferences.saveChaptersAsCBZ(),
title = stringResource(R.string.save_chapter_as_cbz),
),
Preference.PreferenceItem.SwitchPreference(
pref = downloadPreferences.splitTallImages(),
title = stringResource(R.string.split_tall_images),
subtitle = stringResource(R.string.split_tall_images_summary),
),
getDeleteChaptersGroup(
downloadPreferences = downloadPreferences,
categories = allCategories,
),
getAutoDownloadGroup(
downloadPreferences = downloadPreferences,
allCategories = allCategories,
),
getDownloadAheadGroup(downloadPreferences = downloadPreferences),
)
}
@Composable
private fun getDownloadLocationPreference(
downloadPreferences: DownloadPreferences,
): Preference.PreferenceItem.ListPreference<String> {
val context = LocalContext.current
val currentDirPref = downloadPreferences.downloadsDirectory()
val currentDir by currentDirPref.collectAsState()
val pickLocation = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocumentTree(),
) { uri ->
if (uri != null) {
val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
context.contentResolver.takePersistableUriPermission(uri, flags)
val file = UniFile.fromUri(context, uri)
currentDirPref.set(file.uri.toString())
}
}
val defaultDirPair = rememberDefaultDownloadDir()
val customDirEntryKey = currentDir.takeIf { it != defaultDirPair.first } ?: "custom"
return Preference.PreferenceItem.ListPreference(
pref = currentDirPref,
title = stringResource(R.string.pref_download_directory),
subtitle = remember(currentDir) {
UniFile.fromUri(context, currentDir.toUri())?.filePath
} ?: stringResource(R.string.invalid_location, currentDir),
entries = mapOf(
defaultDirPair,
customDirEntryKey to stringResource(R.string.custom_dir),
),
onValueChanged = {
val default = it == defaultDirPair.first
if (!default) {
pickLocation.launch(null)
}
default // Don't update when non-default chosen
},
)
}
@Composable
private fun rememberDefaultDownloadDir(): Pair<String, String> {
val appName = stringResource(R.string.app_name)
return remember {
val file = UniFile.fromFile(
File(
"${Environment.getExternalStorageDirectory().absolutePath}${File.separator}$appName",
"downloads",
),
)!!
file.uri.toString() to file.filePath!!
}
}
@Composable
private fun getDeleteChaptersGroup(
downloadPreferences: DownloadPreferences,
categories: List<Category>,
): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_delete_chapters),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = downloadPreferences.removeAfterMarkedAsRead(),
title = stringResource(R.string.pref_remove_after_marked_as_read),
),
Preference.PreferenceItem.ListPreference(
pref = downloadPreferences.removeAfterReadSlots(),
title = stringResource(R.string.pref_remove_after_read),
entries = mapOf(
-1 to stringResource(R.string.disabled),
0 to stringResource(R.string.last_read_chapter),
1 to stringResource(R.string.second_to_last),
2 to stringResource(R.string.third_to_last),
3 to stringResource(R.string.fourth_to_last),
4 to stringResource(R.string.fifth_to_last),
),
),
Preference.PreferenceItem.SwitchPreference(
pref = downloadPreferences.removeBookmarkedChapters(),
title = stringResource(R.string.pref_remove_bookmarked_chapters),
),
getExcludedCategoriesPreference(
downloadPreferences = downloadPreferences,
categories = { categories },
),
),
)
}
@Composable
private fun getExcludedCategoriesPreference(
downloadPreferences: DownloadPreferences,
categories: () -> List<Category>,
): Preference.PreferenceItem.MultiSelectListPreference {
val none = stringResource(R.string.none)
val pref = downloadPreferences.removeExcludeCategories()
val entries = categories().associate { it.id.toString() to it.visualName }
val subtitle by produceState(initialValue = "") {
pref.changes()
.stateIn(this)
.collect { mutable ->
value = mutable
.mapNotNull { id -> entries[id] }
.sortedBy { entries.values.indexOf(it) }
.joinToString()
.ifEmpty { none }
}
}
return Preference.PreferenceItem.MultiSelectListPreference(
pref = pref,
title = stringResource(R.string.pref_remove_exclude_categories),
subtitle = subtitle,
entries = entries,
)
}
@Composable
private fun getAutoDownloadGroup(
downloadPreferences: DownloadPreferences,
allCategories: List<Category>,
): Preference.PreferenceGroup {
val downloadNewChaptersPref = downloadPreferences.downloadNewChapters()
val downloadNewChapterCategoriesPref = downloadPreferences.downloadNewChapterCategories()
val downloadNewChapterCategoriesExcludePref = downloadPreferences.downloadNewChapterCategoriesExclude()
val downloadNewChapters by downloadNewChaptersPref.collectAsState()
val included by downloadNewChapterCategoriesPref.collectAsState()
val excluded by downloadNewChapterCategoriesExcludePref.collectAsState()
var showDialog by rememberSaveable { mutableStateOf(false) }
if (showDialog) {
TriStateListDialog(
title = stringResource(R.string.categories),
message = stringResource(R.string.pref_download_new_categories_details),
items = allCategories,
initialChecked = included.mapNotNull { id -> allCategories.find { it.id.toString() == id } },
initialInversed = excluded.mapNotNull { id -> allCategories.find { it.id.toString() == id } },
itemLabel = { it.visualName },
onDismissRequest = { showDialog = false },
onValueChanged = { newIncluded, newExcluded ->
downloadNewChapterCategoriesPref.set(newIncluded.map { it.id.toString() }.toSet())
downloadNewChapterCategoriesExcludePref.set(newExcluded.map { it.id.toString() }.toSet())
showDialog = false
},
)
}
return Preference.PreferenceGroup(
title = stringResource(R.string.pref_category_auto_download),
preferenceItems = listOf(
Preference.PreferenceItem.SwitchPreference(
pref = downloadNewChaptersPref,
title = stringResource(R.string.pref_download_new),
),
Preference.PreferenceItem.TextPreference(
title = stringResource(R.string.categories),
subtitle = getCategoriesLabel(
allCategories = allCategories,
included = included,
excluded = excluded,
),
onClick = { showDialog = true },
enabled = downloadNewChapters,
),
),
)
}
@Composable
private fun getDownloadAheadGroup(
downloadPreferences: DownloadPreferences,
): Preference.PreferenceGroup {
return Preference.PreferenceGroup(
title = stringResource(R.string.download_ahead),
preferenceItems = listOf(
Preference.PreferenceItem.ListPreference(
pref = downloadPreferences.autoDownloadWhileReading(),
title = stringResource(R.string.auto_download_while_reading),
entries = listOf(0, 2, 3, 5, 10).associateWith {
if (it == 0) {
stringResource(R.string.disabled)
} else {
pluralStringResource(id = R.plurals.next_unread_chapters, count = it, it)
}
},
),
Preference.PreferenceItem.InfoPreference(stringResource(R.string.download_ahead_info)),
),
)
}
}
| apache-2.0 | feb623f8242336fe51f86668dee450aa | 42.647059 | 118 | 0.619609 | 5.56848 | false | false | false | false |
MaTriXy/timber | android/src/main/java/timber/log/LogcatTree.kt | 1 | 3205 | package timber.log
import android.os.Build
import android.util.Log
import java.io.PrintWriter
import java.io.StringWriter
private const val MAX_LOG_LENGTH = 4000
private const val MAX_TAG_LENGTH = 23
/**
* A [Tree] which forwards to [Log].
*
* Calls to [performLog] are sent to either [Log.wtf] (for [Timber.ASSERT] level) or [Log.println]
* (for everything else). Prior to API 24, log tags are automatically truncated to 23 characters.
* Log messages will be split if they exceed 4000 characters to work around the platform message
* limit.
*
* Note: This does not check [Log.isLoggable] by default. Call [withCompliantLogging] for an
* instance which delegates to this method prior to logging.
*/
class LogcatTree @JvmOverloads constructor(private val defaultTag: String = "App") : Tree() {
/** Return a new [Tree] that checks [Log.isLoggable] prior to logging. */
fun withCompliantLogging() = object : Tree() {
override fun isLoggable(priority: Int, tag: String?): Boolean {
return Log.isLoggable(tag.asSafeTag(), priority)
}
override fun performLog(priority: Int, tag: String?, throwable: Throwable?, message: String?) {
[email protected](priority, tag, throwable, message)
}
}
override fun performLog(priority: Int, tag: String?, throwable: Throwable?, message: String?) {
val safeTag = tag.asSafeTag()
val fullMessage = if (message != null) {
if (throwable != null) {
"$message\n${throwable.stackTraceString}"
} else {
message
}
} else if (throwable != null) {
throwable.stackTraceString
} else {
return // Nothing to do!
}
val length = fullMessage.length
if (length <= MAX_LOG_LENGTH) {
// Fast path for small messages which can fit in a single call.
if (priority == Timber.ASSERT) {
Log.wtf(safeTag, fullMessage)
} else {
Log.println(priority, safeTag, fullMessage)
}
return
}
// Slow path: Split by line, then ensure each line can fit into Log's maximum length.
// TODO use lastIndexOf instead of indexOf to batch multiple lines into single calls.
var i = 0
while (i < length) {
var newline = fullMessage.indexOf('\n', i)
newline = if (newline != -1) newline else length
do {
val end = Math.min(newline, i + MAX_LOG_LENGTH)
val part = fullMessage.substring(i, end)
if (priority == Log.ASSERT) {
Log.wtf(safeTag, part)
} else {
Log.println(priority, safeTag, part)
}
i = end
} while (i < newline)
i++
}
}
private fun String?.asSafeTag(): String {
val tag = this ?: defaultTag
// Tag length limit was removed in API 24.
if (Build.VERSION.SDK_INT < 24 && tag.length > MAX_TAG_LENGTH) {
return tag.substring(0, MAX_TAG_LENGTH)
}
return tag
}
private val Throwable.stackTraceString get(): String {
// DO NOT replace this with Log.getStackTraceString() - it hides UnknownHostException, which is
// not what we want.
val sw = StringWriter(256)
val pw = PrintWriter(sw, false)
printStackTrace(pw)
pw.flush()
return sw.toString()
}
}
| apache-2.0 | a1c35c99f7374aedc96d7b4869f419be | 31.704082 | 99 | 0.64805 | 3.966584 | false | false | false | false |
hurricup/intellij-community | plugins/settings-repository/src/CredentialsStore.kt | 1 | 4717 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.credentialStore.Credentials
import com.intellij.layout.*
import com.intellij.layout.CCFlags.*
import com.intellij.layout.LCFlags.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.dialog
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.PathUtilRt
import com.intellij.util.nullize
import com.intellij.util.trimMiddle
import com.intellij.util.ui.UIUtil
import java.util.regex.Pattern
import javax.swing.JPasswordField
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
private val HREF_PATTERN = Pattern.compile("<a(?:\\s+href\\s*=\\s*[\"']([^\"']*)[\"'])?\\s*>([^<]*)</a>")
private val LINK_TEXT_ATTRIBUTES = SimpleTextAttributes(SimpleTextAttributes.STYLE_SMALLER, JBColor.blue)
private val SMALL_TEXT_ATTRIBUTES = SimpleTextAttributes(SimpleTextAttributes.STYLE_SMALLER, null)
fun showAuthenticationForm(credentials: Credentials?, uri: String, host: String?, path: String?, sshKeyFile: String?): Credentials? {
if (ApplicationManager.getApplication()?.isUnitTestMode === true) {
throw AssertionError("showAuthenticationForm called from tests")
}
val isGitHub = host == "github.com"
val note = if (sshKeyFile == null) icsMessage(if (isGitHub) "login.github.note" else "login.other.git.provider.note") else null
var username = credentials?.user
if (username == null && isGitHub && path != null && sshKeyFile == null) {
val firstSlashIndex = path.indexOf('/', 1)
username = path.substring(1, if (firstSlashIndex == -1) path.length else firstSlashIndex)
}
val message = if (sshKeyFile == null) icsMessage("log.in.to", uri.trimMiddle(50)) else icsMessage("enter.your.password.for.ssh.key", PathUtilRt.getFileName(sshKeyFile))
return UIUtil.invokeAndWaitIfNeeded(Computable {
val userField = JTextField(username)
val passwordField = JPasswordField(credentials?.password)
val centerPanel = panel(fillX) {
label(message, wrap, span, bold = true, gapBottom = 10)
if (sshKeyFile == null && !isGitHub) {
label("Username:")
userField(grow, wrap)
}
label(if (sshKeyFile == null && isGitHub) "Token:" else "Password:")
passwordField(grow, wrap)
note?.let { noteComponent(it)(skip) }
}
val authenticationForm = dialog(
title = "Settings Repository",
resizable = false,
centerPanel = centerPanel,
preferedFocusComponent = userField,
okActionEnabled = false)
passwordField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
authenticationForm.okActionEnabled(e.document.length != 0)
}
})
authenticationForm.okActionEnabled(false)
if (authenticationForm.showAndGet()) {
username = sshKeyFile ?: userField.text.nullize(true)
val passwordChars = passwordField.password
Credentials(username, if (passwordChars == null || passwordChars.isEmpty()) (if (username == null) null else "x-oauth-basic") else String(passwordChars))
}
else {
null
}
})
}
private fun noteComponent(note: String): SimpleColoredComponent {
val noteComponent = SimpleColoredComponent()
val matcher = HREF_PATTERN.matcher(note)
var prev = 0
if (matcher.find()) {
do {
if (matcher.start() != prev) {
noteComponent.append(note.substring(prev, matcher.start()), SMALL_TEXT_ATTRIBUTES)
}
noteComponent.append(matcher.group(2), LINK_TEXT_ATTRIBUTES, SimpleColoredComponent.BrowserLauncherTag(matcher.group(1)))
prev = matcher.end()
}
while (matcher.find())
LinkMouseListenerBase.installSingleTagOn(noteComponent)
}
if (prev < note.length) {
noteComponent.append(note.substring(prev), SMALL_TEXT_ATTRIBUTES)
}
return noteComponent
} | apache-2.0 | e28612587f0105b92f7c93b0b8f64ec6 | 37.048387 | 172 | 0.723341 | 4.211607 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/utils/MediaIDHelper.kt | 1 | 7685 | /*
* Copyright (C) 2014 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.sjn.stamp.utils
import android.app.Activity
import android.support.v4.media.session.MediaControllerCompat
import android.text.TextUtils
import com.sjn.stamp.media.provider.ProviderType
import com.sjn.stamp.model.constant.CategoryType
import java.util.*
/**
* Utility class to help on queue related tasks.
*/
object MediaIDHelper {
// Media IDs used on browseable items of MediaBrowser
const val MEDIA_ID_EMPTY_ROOT = "__EMPTY_ROOT__"
const val MEDIA_ID_ROOT = "__ROOT__"
const val MEDIA_ID_MUSICS_BY_GENRE = "__BY_GENRE__"
const val MEDIA_ID_MUSICS_BY_SEARCH = "__BY_SEARCH__"
const val MEDIA_ID_MUSICS_BY_ARTIST = "__BY_ARTIST__"
const val MEDIA_ID_MUSICS_BY_ALBUM = "__BY_ALBUM__"
const val MEDIA_ID_MUSICS_BY_ALL = "__BY_ALL__"
const val MEDIA_ID_MUSICS_BY_QUEUE = "__BY_QUEUE__"
const val MEDIA_ID_MUSICS_BY_MY_STAMP = "__BY_MY_STAMP__"
const val MEDIA_ID_MUSICS_BY_SMART_STAMP = "__BY_SMART_STAMP__"
const val MEDIA_ID_MUSICS_BY_PLAYLIST = "__BY_PLAYLIST__"
const val MEDIA_ID_MUSICS_BY_PLAYLIST_LIST = "__BY_PLAYLIST__"
const val MEDIA_ID_MUSICS_BY_NEW = "__BY_NEW__"
const val MEDIA_ID_MUSICS_BY_MOST_PLAYED = "__BY_MOST_PLAYED__"
const val MEDIA_ID_MUSICS_BY_DIRECT = "__BY_DIRECT__"
const val MEDIA_ID_MUSICS_BY_TIMELINE = "__BY_TIMELINE__"
const val MEDIA_ID_MUSICS_BY_RANKING = "__BY_RANKING__"
private const val CATEGORY_SEPARATOR = '/'
private const val LEAF_SEPARATOR = '|'
/**
* Create a String value that represents a playable or a browsable media.
*
*
* Encode the media browseable categories, if any, and the unique music ID, if any,
* into a single String mediaID.
*
*
* MediaIDs are of the form <categoryType>/<categoryValue>|<musicUniqueId>, to make it easy
* to find the category (like genre) that a music was selected from, so we
* can correctly build the playing queue. This is specially useful when
* one music can appear in more than one list, like "by genre -> genre_1"
* and "by artist -> artist_1".
*
* @param musicID Unique music ID for playable items, or null for browseable items.
* @param categories hierarchy of categories representing this item's browsing parents
* @return a hierarchy-aware media ID
</musicUniqueId></categoryValue></categoryType> */
fun createMediaID(musicID: String?, vararg categories: String): String =
StringBuilder().apply {
for (i in categories.indices) {
//if (!isValidCategory(categories[i])) {
// throw new IllegalArgumentException("Invalid category: " + categories[i]);
//}
append(escape(categories[i]))
if (i < categories.size - 1) {
append(CATEGORY_SEPARATOR)
}
}
musicID?.let {
append(LEAF_SEPARATOR).append(escape(it))
}
}.toString()
fun createDirectMediaId(musicID: String): String = createMediaID(musicID, MEDIA_ID_MUSICS_BY_DIRECT)
private fun isValidCategory(category: String?): Boolean =
category == null || category.indexOf(CATEGORY_SEPARATOR) < 0 && category.indexOf(LEAF_SEPARATOR) < 0
fun resolveMusicId(musicIdOrMediaId: String): String? =
if (MediaIDHelper.isTrack(musicIdOrMediaId)) MediaIDHelper.extractMusicIDFromMediaID(musicIdOrMediaId) else musicIdOrMediaId
/**
* Extracts unique musicID from the mediaID. mediaID is, by this sample's convention, a
* concatenation of category (eg "by_genre"), categoryValue (eg "Classical") and unique
* musicID. This is necessary so we know where the user selected the music from, when the music
* exists in more than one music list, and thus we are able to correctly build the playing queue.
*
* @param mediaID that contains the musicID
* @return musicID
*/
fun extractMusicIDFromMediaID(mediaID: String?): String? {
if (mediaID == null) {
return null
}
val pos = mediaID.indexOf(LEAF_SEPARATOR)
return if (pos >= 0) {
mediaID.substring(pos + 1)
} else null
}
/**
* Extracts category and categoryValue from the mediaID. mediaID is, by this sample's
* convention, a concatenation of category (eg "by_genre"), categoryValue (eg "Classical") and
* mediaID. This is necessary so we know where the user selected the music from, when the music
* exists in more than one music list, and thus we are able to correctly build the playing queue.
*
* @param mediaID that contains a category and categoryValue.
*/
fun getHierarchy(mediaID: String): Array<String> {
var result = mediaID
val pos = mediaID.indexOf(LEAF_SEPARATOR)
if (pos >= 0) {
result = mediaID.substring(0, pos)
}
return result.split(CATEGORY_SEPARATOR.toString().toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
}
fun extractBrowseCategoryValueFromMediaID(mediaID: String): String? {
val hierarchy = getHierarchy(mediaID)
return if (hierarchy.size == 2) {
hierarchy[1]
} else null
}
fun isBrowseable(mediaID: String): Boolean {
return mediaID.indexOf(LEAF_SEPARATOR) < 0
}
fun getParentMediaID(mediaID: String): String {
val hierarchy = getHierarchy(mediaID)
if (!isBrowseable(mediaID)) {
return createMediaID(null, *hierarchy)
}
if (hierarchy.size <= 1) {
return MEDIA_ID_ROOT
}
return createMediaID(null, *Arrays.copyOf(hierarchy, hierarchy.size - 1))
}
fun isMediaItemPlaying(activity: Activity, mediaId: String): Boolean {
// Media item is considered to be playing or paused based on the controller's current media id
MediaControllerCompat.getMediaController(activity)?.let { controller ->
controller.metadata?.let { metadata ->
metadata.description.mediaId?.let {
return TextUtils.equals(it, MediaIDHelper.extractMusicIDFromMediaID(mediaId))
}
}
}
return false
}
fun isTrack(mediaID: String): Boolean = !isBrowseable(mediaID)
fun unescape(musicID: String): String {
return musicID.replace("/".toRegex(), "/").replace("|".toRegex(), "|")
}
fun escape(musicID: String): String {
return musicID.replace("/".toRegex(), "/").replace("\\|".toRegex(), "|")
}
fun getCategoryType(mediaId: String): CategoryType? = getProviderType(mediaId)?.categoryType
fun getProviderType(mediaId: String): ProviderType? {
val hierarchy = getHierarchy(mediaId)
return if (hierarchy.isEmpty()) {
null
} else ProviderType.of(hierarchy[0])
}
fun isDirect(categoryType: String): Boolean = MEDIA_ID_MUSICS_BY_DIRECT == categoryType
}
| apache-2.0 | dbb9a4160b4f21c01e0801412bd7c611 | 39.835106 | 136 | 0.644132 | 4.111944 | false | false | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/tests/es300/es-300-fbo-srgb.kt | 1 | 6491 | package ogl_samples.tests.es300
/**
* Created by GBarbieri on 21.04.2017.
*/
import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import ogl_samples.framework.Compiler
import ogl_samples.framework.TestA
import org.lwjgl.opengl.ARBFramebufferObject.GL_COLOR_ATTACHMENT0
import org.lwjgl.opengl.ARBFramebufferObject.GL_DEPTH_ATTACHMENT
import org.lwjgl.opengl.ARBMapBufferRange.GL_MAP_INVALIDATE_BUFFER_BIT
import org.lwjgl.opengl.ARBMapBufferRange.GL_MAP_WRITE_BIT
import org.lwjgl.opengl.ARBUniformBufferObject.GL_UNIFORM_BUFFER
import org.lwjgl.opengl.ARBUniformBufferObject.glBindBufferBase
import org.lwjgl.opengl.ARBVertexArrayObject.glBindVertexArray
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL14.GL_DEPTH_COMPONENT24
import org.lwjgl.opengl.GL15.GL_STATIC_DRAW
import org.lwjgl.opengl.GL20.glUseProgram
import org.lwjgl.opengl.GL21.GL_SRGB
import org.lwjgl.opengl.GL21.GL_SRGB8_ALPHA8
import uno.buffer.bufferOf
import uno.caps.Caps.Profile
import uno.glf.generateIcosahedron
import uno.glf.glf
import uno.glf.semantic
import uno.gln.*
/**
* Created by GBarbieri on 30.03.2017.
*/
fun main(args: Array<String>) {
es_300_fbo_srgb().loop()
}
private class es_300_fbo_srgb : TestA("es-300-fbo-srgb", Profile.ES, 3, 0) {
val SHADER_SOURCE_RENDER = "es-300/fbo-srgb"
val SHADER_SOURCE_SPLASH = "es-300/fbo-srgb-blit"
override fun begin(): Boolean {
glEnable(GL_CULL_FACE)
return super.begin()
}
override fun initProgram(): Boolean {
var validated = true
val compiler = Compiler()
val shaderName = IntArray(Shader.values().size)
initPrograms {
if (validated) {
shaderName[Shader.VERT_RENDER] = compiler.create("$SHADER_SOURCE_RENDER.vert")
shaderName[Shader.FRAG_RENDER] = compiler.create("$SHADER_SOURCE_RENDER.frag")
with(Program.RENDER) {
attach(shaderName[Shader.VERT_RENDER], shaderName[Shader.FRAG_RENDER])
link()
}
}
if (validated) {
shaderName[Shader.VERT_SPLASH] += compiler.create("$SHADER_SOURCE_SPLASH.vert")
shaderName[Shader.FRAG_SPLASH] = compiler.create("$SHADER_SOURCE_SPLASH.frag")
with(Program.SPLASH) {
attach(shaderName[Shader.VERT_SPLASH], shaderName[Shader.FRAG_SPLASH])
link()
}
}
if (validated) {
validated = validated && compiler.check()
validated = validated && compiler checkProgram Program.RENDER
validated = validated && compiler checkProgram Program.SPLASH
}
if (validated) {
using(Program.RENDER) { "transform".blockIndex = semantic.uniform.TRANSFORM0 }
using(Program.SPLASH) { "Diffuse".unit = semantic.sampler.DIFFUSE }
}
}
return validated && checkError("initProgram")
}
override fun initBuffer(): Boolean {
val vertices = generateIcosahedron(4)
vertexCount = vertices.size * Vec3.length
vertexData = bufferOf(vertices)
initArrayBuffer(vertexData)
val uniformBlockSize = glm.max(Mat4.size, caps.limits.UNIFORM_BUFFER_OFFSET_ALIGNMENT)
withUniformBuffer(Buffer.TRANSFORM) { data(uniformBlockSize, GL_STATIC_DRAW) }
return true
}
override fun initTexture(): Boolean {
val windowSize = windowSize * framebufferScale
initTextures2d() {
at(Texture.COLORBUFFER) {
levels(base = 0, max = 0)
filter(min = linear, mag = linear)
storage(GL_SRGB8_ALPHA8, windowSize)
}
at(Texture.RENDERBUFFER) {
levels(base = 0, max = 0)
filter(min = nearest, mag = nearest)
storage(GL_DEPTH_COMPONENT24, windowSize)
}
}
return true
}
override fun initVertexArray(): Boolean {
initVertexArrays {
at(VertexArray.RENDER) { array(Buffer.VERTEX, glf.pos3) }
at(VertexArray.SPLASH) {}
}
return true
}
override fun initFramebuffer(): Boolean {
initFramebuffer(framebufferName) {
// GL_FRAMEBUFFER, which is the default target, is equivalent to GL_DRAW_FRAMEBUFFER, we can then omit it
texture2D(GL_COLOR_ATTACHMENT0, Texture.COLORBUFFER)
texture2D(GL_DEPTH_ATTACHMENT, Texture.RENDERBUFFER)
if (getColorEncoding() != GL_SRGB)
return false
if (!complete)
return false
}
/*
GLint Encoding = -1;
glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &Encoding);
GLint Capable = 0;
glGetIntegerv(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &Capable);
*/
return true
}
override fun render(): Boolean {
mappingUniformBufferRange(Buffer.TRANSFORM, Mat4.size, GL_MAP_WRITE_BIT or GL_MAP_INVALIDATE_BUFFER_BIT) {
//glm::mat4 Projection = glm::perspectiveFov(glm::pi<float>() * 0.25f, 640.f, 480.f, 0.1f, 100.0f);
val projection = glm.perspective(glm.PIf * 0.25f, windowSize, 0.1f, 100f)
pointer = projection * view
} // Automatically unmapped and unbinded, to make sure the uniform buffer is uploaded
// Render to a sRGB framebuffer object.
run {
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glViewport(windowSize * framebufferScale)
glBindFramebuffer(framebufferName)
glClearDepthBuffer()
glClearColorBuffer(1f, 0.5f, 0f, 1f)
glUseProgram(Program.RENDER)
glBindVertexArray(VertexArray.RENDER)
glBindBufferBase(GL_UNIFORM_BUFFER, semantic.uniform.TRANSFORM0, Buffer.TRANSFORM)
glDrawArraysInstanced(vertexCount, 1)
}
// Blit the sRGB framebuffer to the default framebuffer back buffer.
run {
glDisable(GL_DEPTH_TEST)
glViewport(windowSize)
glBindFramebuffer()
glUseProgram(Program.SPLASH)
withTexture2d(0, Texture.COLORBUFFER) {
glBindVertexArray(VertexArray.SPLASH)
glDrawArraysInstanced(3, 1)
}
}
return true
}
} | mit | 54e48df53058a336bc8a847be62d548e | 30.062201 | 128 | 0.625173 | 4.171594 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/extensions/modifier/ModifierExt.kt | 1 | 1954 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.design.compose.extensions.modifier
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import com.google.accompanist.placeholder.material.placeholder
/**
* Conditionally applies the [builder] block if [condition].
*/
inline fun Modifier.thenIf(
condition: Boolean,
builder: Modifier.() -> Modifier
) = if (condition) builder() else this
/**
* Applies a placeholder modifier
*/
fun Modifier.asPlaceholder(
visible: Boolean,
color: Color? = null,
shape: Shape? = null
) = composed {
placeholder(
visible = visible,
color = color ?: MaterialTheme.colorScheme.inverseOnSurface,
shape = shape
)
}
| mit | 3340f2a9b5929410a926aefe6c8e2d73 | 35.867925 | 80 | 0.747185 | 4.361607 | false | false | false | false |
square/wire | wire-library/wire-moshi-adapter/src/main/java/com/squareup/wire/AnyMessageJsonAdapter.kt | 1 | 2669 | /*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.io.IOException
internal class AnyMessageJsonAdapter(
private val moshi: Moshi,
private val typeUrlToAdapter: Map<String, ProtoAdapter<*>>
) : JsonAdapter<AnyMessage>() {
@Throws(IOException::class)
override fun toJson(writer: JsonWriter, value: AnyMessage?) {
if (value == null) {
writer.nullValue()
return
}
writer.beginObject()
writer.name("@type")
writer.value(value.typeUrl)
val protoAdapter = typeUrlToAdapter[value.typeUrl]
?: throw JsonDataException("Cannot find type for url: ${value.typeUrl} in ${writer.path}")
val delegate = moshi.adapter(protoAdapter.type!!.java) as JsonAdapter<Message<*, *>>
val flattenToken = writer.beginFlatten()
delegate.toJson(writer, value.unpack(protoAdapter) as Message<*, *>)
writer.endFlatten(flattenToken)
writer.endObject()
}
@Throws(IOException::class)
override fun fromJson(reader: JsonReader): AnyMessage? {
if (reader.peek() == JsonReader.Token.NULL) {
reader.nextNull<Any>()
return null
}
val typeUrl = reader.peekJson().use { it.readStringNamed("@type") }
?: throw JsonDataException("expected @type in ${reader.path}")
val protoAdapter = typeUrlToAdapter[typeUrl]
?: throw JsonDataException("Cannot resolve type: $typeUrl in ${reader.path}")
val delegate = moshi.adapter(protoAdapter.type!!.java) as JsonAdapter<Message<*, *>>
val value = delegate.fromJson(reader)
return AnyMessage.pack(value!!)
}
/** Returns the string named [name] of an object, or null if no such property exists. */
private fun JsonReader.readStringNamed(name: String): String? {
beginObject()
while (hasNext()) {
if (nextName() == name) {
return nextString()
} else {
skipValue()
}
}
return null // No such field on 'reader'.
}
}
| apache-2.0 | 890fbaadae1bd3d0de2b8aa04a02a10d | 30.77381 | 96 | 0.699138 | 4.263578 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/crdt/testing/CrdtEntityHelper.kt | 1 | 3875 | package arcs.core.crdt.testing
import arcs.core.common.ReferenceId
import arcs.core.crdt.Actor
import arcs.core.crdt.CrdtEntity
import arcs.core.crdt.VersionMap
import arcs.core.data.FieldName
/**
* Helper for interacting with a [CrdtEntity] in tests. Provides convenience methods for
* constructing CRDT operations and sending them to the [entity]. Maintains its own internal CRDT
* [VersionMap] instances so that you don't have to!
*/
class CrdtEntityHelper(private val actor: Actor, private val entity: CrdtEntity) {
// Maintain a separate VersionMap for each field.
private val singletonVersionMaps = mutableMapOf<String, VersionMap>()
private val collectionVersionMaps = mutableMapOf<String, VersionMap>()
/** Set the given singleton [field] to [value]. */
fun update(field: FieldName, value: CrdtEntity.Reference) {
val op = createSetSingletonOp(field, value)
applyOp(op) { "Failed to set singleton field '$field' to '$value'." }
}
/** Clears the value of the given singleton [field]. */
fun clearSingleton(field: FieldName) {
val op = createClearSingletonOp(field)
applyOp(op) { "Failed to clear singleton field '$field'." }
}
/** Adds [element] to the given collection [field]. */
fun add(field: FieldName, element: CrdtEntity.Reference) {
val op = createAddToSetOp(field, element)
applyOp(op) { "Failed to add element '$element' to collection field '$field'." }
}
/** Removes [element] from the given collection [field]. */
fun remove(field: FieldName, element: ReferenceId) {
val op = createRemoveFromSetOp(field, element)
applyOp(op) { "Failed to remove element '$element' from collection field '$field'." }
}
/** Clears everything from the [CrdtEntity]; all fields and metadata. */
fun clearAll() {
val op = createClearAllOp()
applyOp(op) { "Failed to clear everything from CrdtEntity." }
}
private fun getSingletonVersionMap(field: FieldName): VersionMap {
return singletonVersionMaps.getOrPut(field) { VersionMap() }
}
private fun getCollectionVersionMap(field: FieldName): VersionMap {
return collectionVersionMaps.getOrPut(field) { VersionMap() }
}
private fun createSetSingletonOp(
field: FieldName,
value: CrdtEntity.Reference
): CrdtEntity.Operation.SetSingleton {
val versionMap = getSingletonVersionMap(field).increment(actor)
return CrdtEntity.Operation.SetSingleton(actor, versionMap.copy(), field, value)
}
private fun createClearSingletonOp(field: FieldName): CrdtEntity.Operation.ClearSingleton {
// Don't increment version map for removals.
val versionMap = getSingletonVersionMap(field)
return CrdtEntity.Operation.ClearSingleton(actor, versionMap.copy(), field)
}
private fun createAddToSetOp(
field: FieldName,
element: CrdtEntity.Reference
): CrdtEntity.Operation.AddToSet {
val versionMap = getCollectionVersionMap(field).increment(actor)
return CrdtEntity.Operation.AddToSet(actor, versionMap.copy(), field, element)
}
private fun createRemoveFromSetOp(
field: FieldName,
element: ReferenceId
): CrdtEntity.Operation.RemoveFromSet {
// Don't increment version map for removals.
val versionMap = getCollectionVersionMap(field)
return CrdtEntity.Operation.RemoveFromSet(actor, versionMap.copy(), field, element)
}
private fun createClearAllOp(): CrdtEntity.Operation.ClearAll {
// TODO(b/175657591): ClearAll is broken; there's no good value to use for versionMap here.
val versionMap = VersionMap()
return CrdtEntity.Operation.ClearAll(actor, versionMap.copy())
}
private fun applyOp(op: CrdtEntity.Operation, errorMessage: () -> String) {
val success = entity.applyOperation(op)
check(success) {
"""
${errorMessage()}
Operation: $op
CrdtEntity: ${entity.data}
""".trimIndent()
}
}
}
| bsd-3-clause | d0aa1fd96360f707fe0caa2d5f8174cc | 36.259615 | 97 | 0.724129 | 4.319955 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt | 2 | 9780 | // 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.highlighter.markers
import com.intellij.codeInsight.daemon.DaemonBundle
import com.intellij.codeInsight.navigation.BackgroundUpdaterTask
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.util.MethodCellRenderer
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.PsiElementProcessorAdapter
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.FunctionalExpressionSearch
import com.intellij.util.CommonProcessors
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isTraitFakeOverride
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.presentation.DeclarationByModuleRenderer
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachDeclaredMemberOverride
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import java.awt.event.MouseEvent
import javax.swing.JComponent
private fun PsiMethod.isMethodWithDeclarationInOtherClass(): Boolean {
return this is KtLightMethod && this.isTraitFakeOverride()
}
internal fun <T> getOverriddenDeclarations(mappingToJava: MutableMap<PsiElement, T>, classes: Set<PsiClass>): Set<T> {
val overridden = HashSet<T>()
for (aClass in classes) {
aClass.forEachDeclaredMemberOverride { superMember, overridingMember ->
ProgressManager.checkCanceled()
val possiblyFakeLightMethods = overridingMember.toPossiblyFakeLightMethods()
possiblyFakeLightMethods.find { !it.isMethodWithDeclarationInOtherClass() }?.let {
mappingToJava.remove(superMember)?.let { declaration ->
// Light methods points to same methods
// and no reason to keep searching those methods
// those originals are found
if (mappingToJava.remove(it) == null) {
mappingToJava.values.removeIf(superMember::equals)
}
overridden.add(declaration)
}
false
}
mappingToJava.isNotEmpty()
}
}
return overridden
}
// Module-specific version of MarkerType.getSubclassedClassTooltip
fun getSubclassedClassTooltip(klass: PsiClass): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit(5, HashSet<PsiClass>())
ClassInheritorsSearch.search(klass).forEach(PsiElementProcessorAdapter(processor))
if (processor.isOverflow) {
return if (klass.isInterface) IdeDeprecatedMessagesBundle.message("interface.is.implemented.too.many") else DaemonBundle.message("class.is.subclassed.too.many")
}
val subclasses = processor.toArray(PsiClass.EMPTY_ARRAY)
if (subclasses.isEmpty()) {
val functionalImplementations = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiFunctionalExpression>())
FunctionalExpressionSearch.search(klass).forEach(PsiElementProcessorAdapter(functionalImplementations))
return if (functionalImplementations.collection.isNotEmpty())
KotlinBundle.message("highlighter.text.has.functional.implementations")
else
null
}
val start = IdeDeprecatedMessagesBundle.message(if (klass.isInterface) "interface.is.implemented.by.header" else "class.is.subclassed.by.header")
val shortcuts = ActionManager.getInstance().getAction(IdeActions.ACTION_GOTO_IMPLEMENTATION).shortcutSet.shortcuts
val shortcut = shortcuts.firstOrNull()
val shortCutText = if (shortcut != null)
KotlinBundle.message("highlighter.text.or.press", KeymapUtil.getShortcutText(shortcut))
else
""
val postfix = "<br><div style=''margin-top: 5px''><font size=''2''>" + KotlinBundle.message(
"highlighter.text.click.for.navigate",
shortCutText
) + "</font></div>"
val renderer = DeclarationByModuleRenderer()
val comparator = renderer.comparator
return subclasses.toList().sortedWith(comparator).joinToString(
prefix = "<html><body>$start", postfix = "$postfix</body</html>", separator = "<br>"
) { clazz ->
val moduleNameRequired = if (clazz is KtLightClass) {
val origin = clazz.kotlinOrigin
origin?.hasActualModifier() == true || origin?.isExpectDeclaration() == true
} else false
val moduleName = clazz.module?.name
val elementText = renderer.getElementText(clazz) + (moduleName?.takeIf { moduleNameRequired }?.let { " [$it]" } ?: "")
val refText = (moduleName?.let { "$it:" } ?: "") + ClassPresentationUtil.getNameForClass(clazz, /* qualified = */ true)
" <a href=\"#kotlinClass/$refText\">$elementText</a>"
}
}
fun getOverriddenMethodTooltip(method: PsiMethod): String? {
val processor = PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(5)
method.forEachOverridingMethod(processor = PsiElementProcessorAdapter(processor)::process)
val isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT)
if (processor.isOverflow) {
return if (isAbstract) DaemonBundle.message("method.is.implemented.too.many") else DaemonBundle.message("method.is.overridden.too.many")
}
val comparator = MethodCellRenderer(false).comparator
val overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }.sortedWith(comparator)
if (overridingJavaMethods.isEmpty()) return null
val start = if (isAbstract) DaemonBundle.message("method.is.implemented.header") else DaemonBundle.message("method.is.overriden.header")
return com.intellij.codeInsight.daemon.impl.GutterIconTooltipHelper.composeText(
overridingJavaMethods,
start,
" {1}"
)
}
fun buildNavigateToOverriddenMethodPopup(e: MouseEvent?, element: PsiElement?): NavigationPopupDescriptor? {
val method = getPsiMethod(element) ?: return null
if (DumbService.isDumb(method.project)) {
DumbService.getInstance(method.project)
?.showDumbModeNotification(KotlinBundle.message("highlighter.notification.text.navigation.to.overriding.classes.is.not.possible.during.index.update"))
return null
}
val processor = PsiElementProcessor.CollectElementsWithLimit(2, HashSet<PsiMethod>())
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
method.forEachOverridingMethod {
runReadAction {
processor.execute(it)
}
}
},
KotlinBundle.message("highlighter.title.searching.for.overriding.declarations"),
true,
method.project,
e?.component as JComponent?
)
) {
return null
}
var overridingJavaMethods = processor.collection.filter { !it.isMethodWithDeclarationInOtherClass() }
if (overridingJavaMethods.isEmpty()) return null
val renderer = MethodCellRenderer(false)
overridingJavaMethods = overridingJavaMethods.sortedWith(renderer.comparator)
val methodsUpdater = OverridingMethodsUpdater(method, renderer.comparator)
return NavigationPopupDescriptor(
overridingJavaMethods,
methodsUpdater.getCaption(overridingJavaMethods.size),
KotlinBundle.message("highlighter.title.overriding.declarations.of", method.name),
renderer,
methodsUpdater
)
}
private class OverridingMethodsUpdater(
private val myMethod: PsiMethod,
comparator: Comparator<PsiMethod>,
) : BackgroundUpdaterTask(
myMethod.project,
KotlinBundle.message("highlighter.title.searching.for.overriding.methods"),
createComparatorWrapper { o1: PsiElement, o2: PsiElement ->
if (o1 is PsiMethod && o2 is PsiMethod) comparator.compare(o1, o2) else 0
}
) {
@Suppress("DialogTitleCapitalization")
override fun getCaption(size: Int): String {
return if (myMethod.hasModifierProperty(PsiModifier.ABSTRACT))
DaemonBundle.message("navigation.title.implementation.method", myMethod.name, size)
else
DaemonBundle.message("navigation.title.overrider.method", myMethod.name, size)
}
override fun run(indicator: ProgressIndicator) {
super.run(indicator)
val processor = object : CommonProcessors.CollectProcessor<PsiMethod>() {
override fun process(psiMethod: PsiMethod): Boolean {
if (!updateComponent(psiMethod)) {
indicator.cancel()
}
indicator.checkCanceled()
return super.process(psiMethod)
}
}
myMethod.forEachOverridingMethod { processor.process(it) }
}
}
| apache-2.0 | 801f5e13ee387876a01772333b4d4ff7 | 44.915493 | 168 | 0.721166 | 4.875374 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt | 1 | 10529 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.ReplaceWithOrdinaryAssignmentIntention
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() {
private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
binaryExpressionVisitor(fun(binaryExpression) {
if (binaryExpression.right == null) return
val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return
if (operationToken !in targetOperations) return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
if (!property.isVar) return
val context = binaryExpression.analyze()
val leftType = left.getType(context) ?: return
val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return
if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return
if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return
val fixes = mutableListOf<LocalQuickFix>()
if (ChangeTypeToMutableFix.isApplicable(property)) {
fixes.add(ChangeTypeToMutableFix(leftType))
}
if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) {
fixes.add(ReplaceWithFilterFix())
}
when {
ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix())
JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken))
else -> fixes.add(IntentionWrapper(ReplaceWithOrdinaryAssignmentIntention()))
}
val typeText = leftDefaultType.toString().takeWhile { it != '<' }.toLowerCase()
val operationReference = binaryExpression.operationReference
holder.registerProblem(
operationReference,
KotlinBundle.message("0.creates.new.1.under.the.hood", operationReference.text, typeText),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
})
private class ChangeTypeToMutableFix(private val type: KotlinType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
ChangeToMutableCollectionFix.applyFix(property, type)
property.valOrVarKeyword.replace(KtPsiFactory(property).createValKeyword())
binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset)
}
companion object {
fun isApplicable(property: KtProperty): Boolean {
return ChangeToMutableCollectionFix.isApplicable(property)
}
}
}
private class ReplaceWithFilterFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.filter.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right))
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false
if (leftType == binaryExpression.builtIns.map.defaultType) return false
return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true
}
}
}
private class ReplaceWithAssignmentFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
}
companion object {
val emptyCollectionFactoryMethods =
listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" }
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false
if (!property.isLocal) return false
val initializer = property.initializer as? KtCallExpression ?: return false
if (initializer.valueArguments.isNotEmpty()) return false
val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor
val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString()
if (fqName !in emptyCollectionFactoryMethods) return false
val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false
val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false
if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false
if (binaryExpression.siblings(forward = false, withItself = false)
.filter { it != property }
.any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } }
) return false
return true
}
}
}
private class JoinWithInitializerFix(private val op: KtSingleValueToken) : LocalQuickFix {
override fun getName() = KotlinBundle.message("join.with.initializer.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
val initializer = property.initializer ?: return
val psiFactory = KtPsiFactory(operationReference)
val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS
val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right))
binaryExpression.delete()
property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset)
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean {
if (!property.isLocal || property.initializer == null) return false
return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property
}
}
}
}
private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor
internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean {
val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false
return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType)
} | apache-2.0 | f75f52d11973667fce3e1ad7bfd541d8 | 53 | 158 | 0.709184 | 5.869008 | false | false | false | false |
blindpirate/gradle | build-logic/dependency-modules/src/main/kotlin/gradlebuild/modules/extension/ExternalModulesExtension.kt | 1 | 12300 | /*
* Copyright 2020 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 gradlebuild.modules.extension
import gradlebuild.modules.model.License
abstract class ExternalModulesExtension {
val groovyVersion = "3.0.10"
val configurationCacheReportVersion = "1.1"
val kotlinVersion = "1.6.21"
fun futureKotlin(module: String) = "org.jetbrains.kotlin:kotlin-$module:$kotlinVersion"
val ansiControlSequenceUtil = "net.rubygrapefruit:ansi-control-sequence-util"
val ant = "org.apache.ant:ant"
val antLauncher = "org.apache.ant:ant-launcher"
val asm = "org.ow2.asm:asm"
val asmAnalysis = "org.ow2.asm:asm-analysis"
val asmCommons = "org.ow2.asm:asm-commons"
val asmTree = "org.ow2.asm:asm-tree"
val asmUtil = "org.ow2.asm:asm-util"
val assertj = "org.assertj:assertj-core"
val awsS3Core = "com.amazonaws:aws-java-sdk-core"
val awsS3Kms = "com.amazonaws:aws-java-sdk-kms"
val awsS3S3 = "com.amazonaws:aws-java-sdk-s3"
val awsS3Sts = "com.amazonaws:aws-java-sdk-sts"
val bouncycastlePgp = "org.bouncycastle:bcpg-jdk15on"
val bouncycastlePkix = "org.bouncycastle:bcpkix-jdk15on"
val bouncycastleProvider = "org.bouncycastle:bcprov-jdk15on"
val bsh = "org.apache-extras.beanshell:bsh"
val capsule = "io.usethesource:capsule"
val commonsCodec = "commons-codec:commons-codec"
val commonsCompress = "org.apache.commons:commons-compress"
val commonsHttpclient = "org.apache.httpcomponents:httpclient"
val commonsIo = "commons-io:commons-io"
val commonsLang = "commons-lang:commons-lang"
val commonsLang3 = "org.apache.commons:commons-lang3"
val commonsMath = "org.apache.commons:commons-math3"
val configurationCacheReport = "org.gradle.buildtool.internal:configuration-cache-report:$configurationCacheReportVersion"
val fastutil = "it.unimi.dsi:fastutil"
val gcs = "com.google.apis:google-api-services-storage"
val googleApiClient = "com.google.api-client:google-api-client"
val googleHttpClient = "com.google.http-client:google-http-client"
val googleHttpClientJackson2 = "com.google.http-client:google-http-client-jackson2"
val googleOauthClient = "com.google.oauth-client:google-oauth-client"
val gradleProfiler = "org.gradle.profiler:gradle-profiler"
val groovy = "org.codehaus.groovy:groovy"
val groovyAnt = "org.codehaus.groovy:groovy-ant"
val groovyAstbuilder = "org.codehaus.groovy:groovy-astbuilder"
val groovyConsole = "org.codehaus.groovy:groovy-console"
val groovyDateUtil = "org.codehaus.groovy:groovy-dateutil"
val groovyDatetime = "org.codehaus.groovy:groovy-datetime"
val groovyDoc = "org.codehaus.groovy:groovy-groovydoc"
val groovyJson = "org.codehaus.groovy:groovy-json"
val groovyNio = "org.codehaus.groovy:groovy-nio"
val groovySql = "org.codehaus.groovy:groovy-sql"
val groovyTemplates = "org.codehaus.groovy:groovy-templates"
val groovyTest = "org.codehaus.groovy:groovy-test"
val groovyXml = "org.codehaus.groovy:groovy-xml"
val gson = "com.google.code.gson:gson"
val guava = "com.google.guava:guava"
val hamcrest = "org.hamcrest:hamcrest-core"
val httpcore = "org.apache.httpcomponents:httpcore"
val inject = "javax.inject:javax.inject"
val ivy = "org.apache.ivy:ivy"
val jacksonAnnotations = "com.fasterxml.jackson.core:jackson-annotations"
val jacksonCore = "com.fasterxml.jackson.core:jackson-core"
val jacksonDatabind = "com.fasterxml.jackson.core:jackson-databind"
val jakartaActivation = "com.sun.activation:jakarta.activation"
val jakartaXmlBind = "jakarta.xml.bind:jakarta.xml.bind-api"
val jansi = "org.fusesource.jansi:jansi"
val jatl = "com.googlecode.jatl:jatl"
val jaxbCore = "com.sun.xml.bind:jaxb-core"
val jaxbImpl = "com.sun.xml.bind:jaxb-impl"
val jcifs = "jcifs:jcifs"
val jclToSlf4j = "org.slf4j:jcl-over-slf4j"
val jcommander = "com.beust:jcommander"
val jetbrainsAnnotations = "org.jetbrains:annotations"
val jgit = "org.eclipse.jgit:org.eclipse.jgit"
val joda = "joda-time:joda-time"
val jsch = "com.jcraft:jsch"
val jsr305 = "com.google.code.findbugs:jsr305"
val julToSlf4j = "org.slf4j:jul-to-slf4j"
val junit = "junit:junit"
val junit5Vintage = "org.junit.vintage:junit-vintage-engine"
val junit5JupiterApi = "org.junit.jupiter:junit-jupiter-api"
val junitPlatform = "org.junit.platform:junit-platform-launcher"
val jzlib = "com.jcraft:jzlib"
val kryo = "com.esotericsoftware.kryo:kryo"
val log4jToSlf4j = "org.slf4j:log4j-over-slf4j"
val maven3BuilderSupport = "org.apache.maven:maven-builder-support"
val maven3Model = "org.apache.maven:maven-model"
val maven3RepositoryMetadata = "org.apache.maven:maven-repository-metadata"
val maven3Settings = "org.apache.maven:maven-settings"
val maven3SettingsBuilder = "org.apache.maven:maven-settings-builder"
val minlog = "com.esotericsoftware.minlog:minlog"
val nativePlatform = "net.rubygrapefruit:native-platform"
val nativePlatformFileEvents = "net.rubygrapefruit:file-events"
val objenesis = "org.objenesis:objenesis"
val plexusCipher = "org.sonatype.plexus:plexus-cipher"
val plexusInterpolation = "org.codehaus.plexus:plexus-interpolation"
val plexusSecDispatcher = "org.codehaus.plexus:plexus-sec-dispatcher"
val plexusUtils = "org.codehaus.plexus:plexus-utils"
val plist = "com.googlecode.plist:dd-plist"
val pmavenCommon = "org.sonatype.pmaven:pmaven-common"
val pmavenGroovy = "org.sonatype.pmaven:pmaven-groovy"
val slf4jApi = "org.slf4j:slf4j-api"
val snakeyaml = "org.yaml:snakeyaml"
val testng = "org.testng:testng"
val tomlj = "org.tomlj:tomlj"
val trove4j = "org.jetbrains.intellij.deps:trove4j"
val jna = "net.java.dev.jna:jna"
val agp = "com.android.tools.build:gradle"
val xbeanReflect = "org.apache.xbean:xbean-reflect"
val xmlApis = "xml-apis:xml-apis"
// Compile only dependencies (dynamically downloaded if needed)
val maven3Compat = "org.apache.maven:maven-compat"
val maven3PluginApi = "org.apache.maven:maven-plugin-api"
// Test classpath only libraries
val aircompressor = "io.airlift:aircompressor"
val archunit = "com.tngtech.archunit:archunit"
val archunitJunit5 = "com.tngtech.archunit:archunit-junit5"
val awaitility = "org.awaitility:awaitility-kotlin"
val bytebuddy = "net.bytebuddy:byte-buddy"
val bytebuddyAgent = "net.bytebuddy:byte-buddy-agent"
val cglib = "cglib:cglib"
val equalsverifier = "nl.jqno.equalsverifier:equalsverifier"
val hikariCP = "com.zaxxer:HikariCP"
val guice = "com.google.inject:guice"
val httpmime = "org.apache.httpcomponents:httpmime"
val jacksonKotlin = "com.fasterxml.jackson.module:jackson-module-kotlin"
val javaParser = "com.github.javaparser:javaparser-core"
val jetty = "org.eclipse.jetty:jetty-http"
val jettySecurity = "org.eclipse.jetty:jetty-security"
val jettyWebApp = "org.eclipse.jetty:jetty-webapp"
val joptSimple = "net.sf.jopt-simple:jopt-simple"
val jsoup = "org.jsoup:jsoup"
val jtar = "org.kamranzafar:jtar"
val kotlinCoroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core"
val kotlinCoroutinesDebug = "org.jetbrains.kotlinx:kotlinx-coroutines-debug"
val littleproxy = "xyz.rogfam:littleproxy"
val mina = "org.apache.mina:mina-core"
val mockitoCore = "org.mockito:mockito-core"
val mockitoKotlin = "com.nhaarman:mockito-kotlin"
val mockitoKotlin2 = "com.nhaarman.mockitokotlin2:mockito-kotlin"
val mySqlConnector = "mysql:mysql-connector-java"
val samplesCheck = "org.gradle.exemplar:samples-check"
val snappy = "org.iq80.snappy:snappy"
val servletApi = "javax.servlet:javax.servlet-api"
val socksProxy = "com.github.bbottema:java-socks-proxy-server"
val spock = "org.spockframework:spock-core"
val spockJUnit4 = "org.spockframework:spock-junit4"
val sshdCore = "org.apache.sshd:sshd-core"
val sshdScp = "org.apache.sshd:sshd-scp"
val sshdSftp = "org.apache.sshd:sshd-sftp"
val testcontainersSpock = "org.testcontainers:spock"
val typesafeConfig = "com.typesafe:config"
val xerces = "xerces:xercesImpl"
val xmlunit = "xmlunit:xmlunit"
val licenses = mapOf(
ansiControlSequenceUtil to License.Apache2,
ant to License.Apache2,
antLauncher to License.Apache2,
asm to License.BSD3,
asmAnalysis to License.BSD3,
asmCommons to License.BSD3,
asmTree to License.BSD3,
asmUtil to License.BSD3,
assertj to License.Apache2,
awsS3Core to License.Apache2,
awsS3Kms to License.Apache2,
awsS3S3 to License.Apache2,
awsS3Sts to License.Apache2,
bouncycastlePgp to License.MIT,
bouncycastleProvider to License.MIT,
bsh to License.Apache2,
capsule to License.BSDStyle,
commonsCodec to License.Apache2,
commonsCompress to License.Apache2,
commonsHttpclient to License.Apache2,
commonsIo to License.Apache2,
commonsLang to License.Apache2,
commonsLang3 to License.Apache2,
commonsMath to License.Apache2,
configurationCacheReport to License.Apache2,
fastutil to License.Apache2,
gcs to License.Apache2,
googleApiClient to License.Apache2,
googleHttpClient to License.Apache2,
googleHttpClientJackson2 to License.Apache2,
googleOauthClient to License.Apache2,
gradleProfiler to License.Apache2,
groovy to License.Apache2,
gson to License.Apache2,
guava to License.Apache2,
hamcrest to License.BSD3,
httpcore to License.Apache2,
hikariCP to License.Apache2,
inject to License.Apache2,
ivy to License.Apache2,
jacksonAnnotations to License.Apache2,
jacksonCore to License.Apache2,
jacksonDatabind to License.Apache2,
jakartaActivation to License.EDL,
jakartaXmlBind to License.EDL,
jansi to License.Apache2,
jatl to License.Apache2,
jaxbCore to License.EDL,
jaxbImpl to License.EDL,
jcifs to License.LGPL21,
jclToSlf4j to License.MIT,
jcommander to License.Apache2,
jetbrainsAnnotations to License.Apache2,
jgit to License.EDL,
joda to License.Apache2,
jsch to License.BSDStyle,
jsr305 to License.BSD3,
julToSlf4j to License.MIT,
junit to License.EPL,
junit5Vintage to License.EPL,
junit5JupiterApi to License.EPL,
junitPlatform to License.EPL,
jzlib to License.BSDStyle,
kryo to License.BSD3,
log4jToSlf4j to License.MIT,
maven3BuilderSupport to License.Apache2,
maven3Model to License.Apache2,
maven3RepositoryMetadata to License.Apache2,
maven3Settings to License.Apache2,
maven3SettingsBuilder to License.Apache2,
minlog to License.BSD3,
nativePlatform to License.Apache2,
nativePlatformFileEvents to License.Apache2,
objenesis to License.Apache2,
plexusCipher to License.Apache2,
plexusInterpolation to License.Apache2,
plexusSecDispatcher to License.Apache2,
plexusUtils to License.Apache2,
plist to License.MIT,
pmavenCommon to License.Apache2,
pmavenGroovy to License.Apache2,
slf4jApi to License.MIT,
snakeyaml to License.Apache2,
testng to License.Apache2,
tomlj to License.Apache2,
trove4j to License.LGPL21,
xbeanReflect to License.Apache2,
xmlApis to License.Apache2
)
}
| apache-2.0 | ef9047e7c93d09daee25a2de654a06f7 | 44.895522 | 126 | 0.711382 | 3.43192 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/async/ContinuationWithProgress.kt | 1 | 4373 | /*
* Copyright 2020 Poly Forest, 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.acornui.async
import kotlinx.coroutines.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
/**
* A composition of a [MutableProgress] and a [Continuation].
* This ensures that a coroutine suspension that reports its progress marks the progress as complete when the
* continuation resumes.
*/
open class ContinuationWithProgress<T>(
protected val progress: MutableProgress,
private val continuation: Continuation<T>
) : Continuation<T>, MutableProgress by progress {
override val context: CoroutineContext
get() = continuation.context
override fun resumeWith(result: Result<T>) {
continuation.resumeWith(result)
progress.complete()
}
/**
* Use the [kotlin.coroutines.resume] methods to mark this progress as complete.
*/
override fun complete(): Nothing {
error("Can only complete through resume methods.")
}
}
/**
* Wraps a continuation with progress tracking.
* When this continuation is resumed, the progress tracker will be marked completed.
*/
fun <T> Continuation<T>.withProgress(progress: MutableProgress) =
ContinuationWithProgress(progress, this)
/**
* A composition of a [MutableProgress] and a [CancellableContinuation].
* This ensures that a coroutine suspension that reports its progress marks the progress as complete when the
* continuation resumes.
*/
open class CancellableContinuationWithProgress<T>(
progress: MutableProgress,
private val cancellableContinuation: CancellableContinuation<T>
) : CancellableContinuation<T>, ContinuationWithProgress<T>(progress, cancellableContinuation) {
override val isActive: Boolean
get() = cancellableContinuation.isActive
override val isCancelled: Boolean
get() = cancellableContinuation.isCancelled
override val isCompleted: Boolean
get() = cancellableContinuation.isCompleted
override fun cancel(cause: Throwable?): Boolean {
return cancellableContinuation.cancel(cause).also {
progress.complete()
}
}
@InternalCoroutinesApi
override fun completeResume(token: Any) {
cancellableContinuation.completeResume(token)
progress.complete()
}
@InternalCoroutinesApi
override fun initCancellability() = cancellableContinuation.initCancellability()
override fun invokeOnCancellation(handler: CompletionHandler) = cancellableContinuation.invokeOnCancellation(handler)
@ExperimentalCoroutinesApi
override fun resume(value: T, onCancellation: ((cause: Throwable) -> Unit)?) {
cancellableContinuation.resume(value, onCancellation)
progress.complete()
}
@InternalCoroutinesApi
override fun tryResume(value: T, idempotent: Any?): Any? {
return cancellableContinuation.tryResume(value, idempotent).also {
progress.complete()
}
}
@InternalCoroutinesApi
override fun tryResume(value: T, idempotent: Any?, onCancellation: ((cause: Throwable) -> Unit)?): Any? {
return cancellableContinuation.tryResume(value, idempotent, onCancellation).also {
progress.complete()
}
}
@InternalCoroutinesApi
override fun tryResumeWithException(exception: Throwable): Any? {
return cancellableContinuation.tryResumeWithException(exception).also {
progress.complete()
}
}
@ExperimentalCoroutinesApi
override fun CoroutineDispatcher.resumeUndispatched(value: T) {
resumeUndispatched(value)
progress.complete()
}
@ExperimentalCoroutinesApi
override fun CoroutineDispatcher.resumeUndispatchedWithException(exception: Throwable) {
resumeUndispatchedWithException(exception)
progress.complete()
}
}
/**
* Wraps a cancellable continuation with progress tracking.
* When this continuation is resumed, the progress tracker will be marked completed.
*/
fun <T> CancellableContinuation<T>.withProgress(progress: MutableProgress) =
CancellableContinuationWithProgress(progress, this) | apache-2.0 | 01625d9929d5301936076351585ee7e1 | 30.927007 | 118 | 0.778413 | 4.494347 | false | false | false | false |
duncte123/SkyBot | src/main/kotlin/ml/duncte123/skybot/commands/fun/KpopCommand.kt | 1 | 2848 | /*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.`fun`
import me.duncte123.botcommons.messaging.EmbedUtils
import me.duncte123.botcommons.messaging.MessageUtils
import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed
import ml.duncte123.skybot.objects.api.DuncteApis
import ml.duncte123.skybot.objects.api.KpopObject
import ml.duncte123.skybot.objects.command.Command
import ml.duncte123.skybot.objects.command.CommandCategory
import ml.duncte123.skybot.objects.command.CommandContext
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
class KpopCommand : Command() {
init {
this.category = CommandCategory.FUN
this.name = "kpop"
this.help = "Gives you a random kpop member, command suggestion by Exa"
this.usage = "[search term]"
}
override fun execute(ctx: CommandContext) {
val queryString = if (ctx.args.isNotEmpty()) ctx.argsRaw else ""
val member = ctx.variables.apis.getRandomKpopMember(queryString)
if (member == null) {
MessageUtils.sendMsg(ctx, "Nothing found, but we're open to suggestions")
return
}
sendEmbed(
ctx,
EmbedUtils.getDefaultEmbed()
.setDescription("Here is a kpop member from the group ${member.band}")
.addField("Name of the member", member.name, false)
.setImage(member.image)
.setFooter("Query id: ${member.id}")
)
}
private fun DuncteApis.getRandomKpopMember(search: String): KpopObject? {
val path = if (!search.isBlank()) "/${URLEncoder.encode(search, StandardCharsets.UTF_8)}" else ""
val response = executeDefaultGetRequest("kpop$path", false)
if (!response["success"].asBoolean()) {
return null
}
val json = response["data"]
return KpopObject(
json["id"].asInt(),
json["name"].asText(),
json["band"].asText(),
json["img"].asText()
)
}
}
| agpl-3.0 | f76e0d3ca66104bf93452bed36606aab | 35.987013 | 105 | 0.670646 | 4.238095 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/activitylog/list/ActivityLogListActivity.kt | 1 | 6907 | package org.wordpress.android.ui.activitylog.list
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.R
import org.wordpress.android.databinding.ActivityLogListActivityBinding
import org.wordpress.android.ui.LocaleAwareActivity
import org.wordpress.android.ui.RequestCodes
import org.wordpress.android.ui.ScrollableViewInitializedListener
import org.wordpress.android.ui.activitylog.detail.ActivityLogDetailActivity
import org.wordpress.android.ui.jetpack.backup.download.KEY_BACKUP_DOWNLOAD_ACTION_STATE_ID
import org.wordpress.android.ui.jetpack.backup.download.KEY_BACKUP_DOWNLOAD_DOWNLOAD_ID
import org.wordpress.android.ui.jetpack.backup.download.KEY_BACKUP_DOWNLOAD_REWIND_ID
import org.wordpress.android.ui.jetpack.common.JetpackBackupDownloadActionState
import org.wordpress.android.ui.jetpack.restore.KEY_RESTORE_RESTORE_ID
import org.wordpress.android.ui.jetpack.restore.KEY_RESTORE_REWIND_ID
import org.wordpress.android.ui.mysite.jetpackbadge.JetpackPoweredBottomSheetFragment
import org.wordpress.android.util.JetpackBrandingUtils
import org.wordpress.android.util.JetpackBrandingUtils.Screen.ACTIVITY_LOG
import org.wordpress.android.viewmodel.activitylog.ACTIVITY_LOG_REWINDABLE_ONLY_KEY
import javax.inject.Inject
@AndroidEntryPoint
class ActivityLogListActivity : LocaleAwareActivity(), ScrollableViewInitializedListener {
@Inject lateinit var jetpackBrandingUtils: JetpackBrandingUtils
private var binding: ActivityLogListActivityBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
with(ActivityLogListActivityBinding.inflate(layoutInflater)) {
setContentView(root)
binding = this
checkAndUpdateUiToBackupScreen()
setSupportActionBar(toolbarMain)
}
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
}
}
override fun onScrollableViewInitialized(containerId: Int) {
initJetpackBanner(containerId)
}
private fun initJetpackBanner(scrollableContainerId: Int) {
if (jetpackBrandingUtils.shouldShowJetpackBranding()) {
binding?.root?.post {
val jetpackBannerView = binding?.jetpackBanner?.root ?: return@post
val scrollableView = binding?.root?.findViewById<View>(scrollableContainerId) as? RecyclerView
?: return@post
jetpackBrandingUtils.showJetpackBannerIfScrolledToTop(jetpackBannerView, scrollableView)
jetpackBrandingUtils.initJetpackBannerAnimation(jetpackBannerView, scrollableView)
if (jetpackBrandingUtils.shouldShowJetpackPoweredBottomSheet()) {
binding?.jetpackBanner?.root?.setOnClickListener {
jetpackBrandingUtils.trackBannerTapped(ACTIVITY_LOG)
JetpackPoweredBottomSheetFragment
.newInstance()
.show(supportFragmentManager, JetpackPoweredBottomSheetFragment.TAG)
}
}
}
}
}
/**
* It was decided to reuse the 'Activity Log' screen instead of creating a new 'Backup' screen. This was due to the
* fact that there will be lots of code that would need to be duplicated for the new 'Backup' screen. On the other
* hand, not much more complexity would be introduced if the 'Activity Log' screen is reused (mainly some 'if/else'
* code branches here and there).
*
* However, should more 'Backup' related additions are added to the 'Activity Log' screen, then it should become a
* necessity to split those features in separate screens in order not to increase further the complexity of this
* screen's architecture.
*/
private fun ActivityLogListActivityBinding.checkAndUpdateUiToBackupScreen() {
if (intent.getBooleanExtra(ACTIVITY_LOG_REWINDABLE_ONLY_KEY, false)) {
setTitle(R.string.backup)
activityTypeFilter.visibility = View.GONE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
@Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
RequestCodes.ACTIVITY_LOG_DETAIL -> {
when (data?.getStringExtra(ActivityLogDetailActivity.EXTRA_INNER_FLOW)) {
ActivityLogDetailActivity.EXTRA_RESTORE_FLOW -> onActivityResultForRestore(data)
ActivityLogDetailActivity.EXTRA_BACKUP_DOWNLOAD_FLOW -> onActivityResultForBackupDownload(data)
else -> Unit // Do nothing
}
}
RequestCodes.RESTORE -> onActivityResultForRestore(data)
RequestCodes.BACKUP_DOWNLOAD -> onActivityResultForBackupDownload(data)
}
}
private fun onActivityResultForRestore(data: Intent?) {
val rewindId = data?.getStringExtra(KEY_RESTORE_REWIND_ID)
val restoreId = data?.getLongExtra(KEY_RESTORE_RESTORE_ID, 0)
if (rewindId != null && restoreId != null) {
passQueryRestoreStatus(rewindId, restoreId)
}
}
private fun onActivityResultForBackupDownload(data: Intent?) {
val rewindId = data?.getStringExtra(KEY_BACKUP_DOWNLOAD_REWIND_ID)
val downloadId = data?.getLongExtra(KEY_BACKUP_DOWNLOAD_DOWNLOAD_ID, 0)
val actionState = data?.getIntExtra(KEY_BACKUP_DOWNLOAD_ACTION_STATE_ID, 0)
?: JetpackBackupDownloadActionState.CANCEL.id
if (actionState != JetpackBackupDownloadActionState.CANCEL.id && rewindId != null && downloadId != null) {
passQueryBackupDownloadStatus(rewindId, downloadId, actionState)
}
}
private fun passQueryRestoreStatus(rewindId: String, restoreId: Long) {
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment is ActivityLogListFragment) {
fragment.onQueryRestoreStatus(rewindId, restoreId)
}
}
private fun passQueryBackupDownloadStatus(rewindId: String, downloadId: Long, actionState: Int) {
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment is ActivityLogListFragment) {
fragment.onQueryBackupDownloadStatus(rewindId, downloadId, actionState)
}
}
}
| gpl-2.0 | 40b40aec7b20654e45ee89316b9b6c1c | 46.634483 | 119 | 0.707543 | 5.063783 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinFieldBreakpointType.kt | 2 | 8349 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// The package directive doesn't match the file location to prevent API breakage
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.ui.breakpoints.Breakpoint
import com.intellij.debugger.ui.breakpoints.BreakpointManager
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.JavaBreakpointType
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpointType
import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.idea.debugger.core.KotlinDebuggerCoreBundle
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.*
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.dialog.AddFieldBreakpointDialog
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtDeclarationContainer
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import javax.swing.Icon
import javax.swing.JComponent
class KotlinFieldBreakpointType :
JavaBreakpointType<KotlinPropertyBreakpointProperties>,
XLineBreakpointType<KotlinPropertyBreakpointProperties>(
"kotlin-field", KotlinDebuggerCoreBundle.message("property.watchpoint.tab.title")
),
KotlinBreakpointType
{
override fun createJavaBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
): Breakpoint<KotlinPropertyBreakpointProperties> {
return KotlinFieldBreakpoint(project, breakpoint)
}
override fun canPutAt(file: VirtualFile, line: Int, project: Project): Boolean {
return isBreakpointApplicable(file, line, project) { element ->
when (element) {
is KtProperty -> ApplicabilityResult.definitely(!element.isLocal)
is KtParameter -> ApplicabilityResult.definitely(element.hasValOrVar())
else -> ApplicabilityResult.UNKNOWN
}
}
}
override fun getPriority() = 120
override fun createBreakpointProperties(file: VirtualFile, line: Int): KotlinPropertyBreakpointProperties {
return KotlinPropertyBreakpointProperties()
}
override fun addBreakpoint(project: Project, parentComponent: JComponent?): XLineBreakpoint<KotlinPropertyBreakpointProperties>? {
var result: XLineBreakpoint<KotlinPropertyBreakpointProperties>? = null
val dialog = object : AddFieldBreakpointDialog(project) {
override fun validateData(): Boolean {
val className = className
if (className.isEmpty()) {
reportError(project, JavaDebuggerBundle.message("error.field.breakpoint.class.name.not.specified"))
return false
}
val psiClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project))
if (psiClass !is KtLightClass) {
reportError(project, KotlinDebuggerCoreBundle.message("property.watchpoint.error.couldnt.find.0.class", className))
return false
}
val fieldName = fieldName
if (fieldName.isEmpty()) {
reportError(project, JavaDebuggerBundle.message("error.field.breakpoint.field.name.not.specified"))
return false
}
result = when (psiClass) {
is KtLightClassForFacade -> psiClass.files.asSequence().mapNotNull {
createBreakpointIfPropertyExists(it, it, className, fieldName)
}.firstOrNull()
is KtLightClassForSourceDeclaration -> {
val ktClassOrObject = psiClass.kotlinOrigin
createBreakpointIfPropertyExists(ktClassOrObject, ktClassOrObject.containingKtFile, className, fieldName)
}
else -> null
}
if (result == null) {
reportError(
project,
JavaDebuggerBundle.message("error.field.breakpoint.field.not.found", className, fieldName, fieldName)
)
}
return result != null
}
}
dialog.show()
return result
}
private fun createBreakpointIfPropertyExists(
declaration: KtDeclarationContainer,
file: KtFile,
className: String,
fieldName: String
): XLineBreakpoint<KotlinPropertyBreakpointProperties>? {
val project = file.project
val property = declaration.declarations.firstOrNull { it is KtProperty && it.name == fieldName } ?: return null
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return null
val line = document.getLineNumber(property.textOffset)
return runWriteAction {
XDebuggerManager.getInstance(project).breakpointManager.addLineBreakpoint(
this,
file.virtualFile.url,
line,
KotlinPropertyBreakpointProperties(fieldName, className)
)
}
}
private fun reportError(project: Project, @NlsContexts.DialogMessage message: String) {
Messages.showMessageDialog(project, message, JavaDebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon())
}
override fun isAddBreakpointButtonVisible() = true
override fun getMutedEnabledIcon(): Icon = AllIcons.Debugger.Db_muted_field_breakpoint
override fun getDisabledIcon(): Icon = AllIcons.Debugger.Db_disabled_field_breakpoint
override fun getEnabledIcon(): Icon = AllIcons.Debugger.Db_field_breakpoint
override fun getMutedDisabledIcon(): Icon = AllIcons.Debugger.Db_muted_disabled_field_breakpoint
override fun canBeHitInOtherPlaces() = true
override fun getShortText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String {
val properties = breakpoint.properties
val className = properties.myClassName
@Suppress("HardCodedStringLiteral")
return if (className.isNotEmpty()) className + "." + properties.myFieldName else properties.myFieldName
}
override fun createProperties(): KotlinPropertyBreakpointProperties = KotlinPropertyBreakpointProperties()
override fun createCustomPropertiesPanel(project: Project): XBreakpointCustomPropertiesPanel<XLineBreakpoint<KotlinPropertyBreakpointProperties>> {
return KotlinFieldBreakpointPropertiesPanel()
}
override fun getDisplayText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String? {
val kotlinBreakpoint = BreakpointManager.getJavaBreakpoint(breakpoint) as? BreakpointWithHighlighter
return kotlinBreakpoint?.description ?: super.getDisplayText(breakpoint)
}
override fun getEditorsProvider(
breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>,
project: Project,
): XDebuggerEditorsProvider? = null
override fun createCustomRightPropertiesPanel(project: Project): XBreakpointCustomPropertiesPanel<XLineBreakpoint<KotlinPropertyBreakpointProperties>> {
return KotlinBreakpointFiltersPanel(project)
}
override fun isSuspendThreadSupported() = true
}
| apache-2.0 | d12b505f7e58b60e6e4346e5dd85c164 | 44.375 | 156 | 0.718888 | 5.75 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.