repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
AndroidX/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/LongPressTextDragObserver.kt
3
3920
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.util.fastAny import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch internal interface TextDragObserver { /** * Called as soon as a down event is received. If the pointer eventually moves while remaining * down, a drag gesture may be started. After this method: * - [onUp] will always be called eventually, once the pointer is released. * - [onStart] _may_ be called, if there is a drag that exceeds touch slop. * * This method will not be called before [onStart] in the case when a down event happens that * may not result in a drag, e.g. on the down before a long-press that starts a selection. */ fun onDown(point: Offset) /** * Called after [onDown] if an up event is received without dragging. */ fun onUp() /** * Called once a drag gesture has started, which means touch slop has been exceeded. * [onDown] _may_ be called before this method if the down event could not have * started a different gesture. */ fun onStart(startPoint: Offset) fun onDrag(delta: Offset) fun onStop() fun onCancel() } internal suspend fun PointerInputScope.detectDragGesturesAfterLongPressWithObserver( observer: TextDragObserver ) = detectDragGesturesAfterLongPress( onDragEnd = { observer.onStop() }, onDrag = { _, offset -> observer.onDrag(offset) }, onDragStart = { observer.onStart(it) }, onDragCancel = { observer.onCancel() } ) /** * Detects gesture events for a [TextDragObserver], including both initial down events and drag * events. */ internal suspend fun PointerInputScope.detectDownAndDragGesturesWithObserver( observer: TextDragObserver ) { coroutineScope { launch { detectPreDragGesturesWithObserver(observer) } launch { detectDragGesturesWithObserver(observer) } } } /** * Detects initial down events and calls [TextDragObserver.onDown] and * [TextDragObserver.onUp]. */ private suspend fun PointerInputScope.detectPreDragGesturesWithObserver( observer: TextDragObserver ) { awaitEachGesture { val down = awaitFirstDown() observer.onDown(down.position) // Wait for that pointer to come up. do { val event = awaitPointerEvent() } while (event.changes.fastAny { it.id == down.id && it.pressed }) observer.onUp() } } /** * Detects drag gestures for a [TextDragObserver]. */ private suspend fun PointerInputScope.detectDragGesturesWithObserver( observer: TextDragObserver ) { detectDragGestures( onDragEnd = { observer.onStop() }, onDrag = { _, offset -> observer.onDrag(offset) }, onDragStart = { observer.onStart(it) }, onDragCancel = { observer.onCancel() } ) }
apache-2.0
70c005d029c30d2fcc7a9b614f1a7054
30.620968
98
0.697449
4.655582
false
false
false
false
codeka/wwmmo
common/src/test/kotlin/au/com/codeka/warworlds/common/sim/Helpers.kt
1
1717
package au.com.codeka.warworlds.common.sim import au.com.codeka.warworlds.common.proto.* import com.google.common.collect.Lists import java.util.ArrayList /** * Helper for making a star proto with default options if we don't care about all the required * fields. Only the ID is required here. */ fun makeStar( id: Long, name: String = "Test star", classification: Star.Classification = Star.Classification.BLUE, size: Int = 1, offset_x: Int = 0, offset_y: Int = 0, sector_x: Long = 0L, sector_y: Long = 0L, planets: List<Planet> = ArrayList<Planet>(), fleets: List<Fleet> = ArrayList<Fleet>(), empire_stores: List<EmpireStorage> = ArrayList<EmpireStorage>() ): Star { return Star( id, name = name, classification = classification, size = size, offset_x = offset_x, offset_y = offset_y, sector_x = sector_x, sector_y = sector_y, planets = planets, fleets = fleets, empire_stores = empire_stores) } /** * Initializes some designs. */ fun initDesign() { DesignDefinitions.init( Designs( designs = Lists.newArrayList( Design( type = Design.DesignType.COLONY_SHIP, design_kind = Design.DesignKind.SHIP, display_name = "Colony ship", description = "A colony ship", image_url = "", fuel_size = 800, build_cost = Design.BuildCost( minerals = 100f, population = 120f)), Design( type = Design.DesignType.SCOUT, design_kind = Design.DesignKind.SHIP, display_name = "Scout ship", description = "A scout ship", image_url = "", fuel_size = 100, build_cost = Design.BuildCost( minerals = 10f, population = 12f)) )) ) }
mit
5b736eb7a883b7c622c86738db7a02e1
30.796296
94
0.634246
3.67666
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsSyntaxErrorsAnnotator.kt
2
17183
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.util.InspectionMessage import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.annotator.fixes.AddTypeFix import org.rust.ide.inspections.fixes.SubstituteTextFix import org.rust.lang.core.CompilerFeature.Companion.C_VARIADIC import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.type import org.rust.lang.utils.RsDiagnostic import org.rust.lang.utils.addToHolder import org.rust.openapiext.forEachChild import org.rust.stdext.capitalized import org.rust.stdext.pluralize import java.lang.Integer.max class RsSyntaxErrorsAnnotator : AnnotatorBase() { override fun annotateInternal(element: PsiElement, holder: AnnotationHolder) { when (element) { is RsExternAbi -> checkExternAbi(holder, element) is RsItemElement -> { checkItem(holder, element) when (element) { is RsFunction -> checkFunction(holder, element) is RsStructItem -> checkStructItem(holder, element) is RsTypeAlias -> checkTypeAlias(holder, element) is RsConstant -> checkConstant(holder, element) is RsModItem -> checkModItem(holder, element) is RsModDeclItem -> checkModDeclItem(holder, element) is RsForeignModItem -> checkForeignModItem(holder, element) } } is RsMacro -> checkMacro(holder, element) is RsMacroCall -> checkMacroCall(holder, element) is RsValueParameterList -> checkValueParameterList(holder, element) is RsValueParameter -> checkValueParameter(holder, element) is RsTypeParameterList -> checkTypeParameterList(holder, element) is RsTypeArgumentList -> checkTypeArgumentList(holder, element) is RsLetExpr -> checkLetExpr(holder, element) } } } private fun checkItem(holder: AnnotationHolder, item: RsItemElement) { checkItemOrMacro(item, item.itemKindName.pluralize().capitalized(), item.itemDefKeyword, holder) } private fun checkMacro(holder: AnnotationHolder, element: RsMacro) = checkItemOrMacro(element, "Macros", element.macroRules, holder) private fun checkItemOrMacro(item: RsElement, itemName: String, highlightElement: PsiElement, holder: AnnotationHolder) { if (item !is RsAbstractable) { val parent = item.context val owner = if (parent is RsMembers) parent.context else parent if (owner is RsItemElement && (owner is RsForeignModItem || owner is RsTraitOrImpl)) { holder.newAnnotation(HighlightSeverity.ERROR, "$itemName are not allowed inside ${owner.article} ${owner.itemKindName}") .range(highlightElement).create() } } if (item !is RsAbstractable && item !is RsTraitOrImpl) { denyDefaultKeyword(item, holder, itemName) } } private fun denyDefaultKeyword(item: RsElement, holder: AnnotationHolder, itemName: String) { deny( item.node.findChildByType(RsElementTypes.DEFAULT)?.psi, holder, "$itemName cannot have the `default` qualifier" ) } private fun checkMacroCall(holder: AnnotationHolder, element: RsMacroCall) { denyDefaultKeyword(element, holder, "Macro invocations") } private fun checkFunction(holder: AnnotationHolder, fn: RsFunction) { when (fn.owner) { is RsAbstractableOwner.Free -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") } is RsAbstractableOwner.Trait -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.vis, holder, "${fn.title} cannot have the `pub` qualifier") fn.const?.let { RsDiagnostic.ConstTraitFnError(it).addToHolder(holder) } } is RsAbstractableOwner.Impl -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) if (fn.default != null) { deny(fn.vis, holder, "Default ${fn.title.firstLower} cannot have the `pub` qualifier") } } is RsAbstractableOwner.Foreign -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.block, holder, "${fn.title} cannot have a body") deny(fn.const, holder, "${fn.title} cannot have the `const` qualifier") deny(fn.unsafe, holder, "${fn.title} cannot have the `unsafe` qualifier") deny(fn.externAbi, holder, "${fn.title} cannot have an extern ABI") } } } private fun checkStructItem(holder: AnnotationHolder, struct: RsStructItem) { if (struct.kind == RsStructKind.UNION && struct.tupleFields != null) { deny(struct.tupleFields, holder, "Union cannot be tuple-like") } } private fun checkTypeAlias(holder: AnnotationHolder, ta: RsTypeAlias) { val title = "Type `${ta.identifier.text}`" when (val owner = ta.owner) { is RsAbstractableOwner.Free -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") require(ta.typeReference, holder, "$title should have a body`", ta) } is RsAbstractableOwner.Trait -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") } is RsAbstractableOwner.Impl -> { if (owner.isInherent) { deny(ta.default, holder, "$title cannot have the `default` qualifier") } deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") require(ta.typeReference, holder, "$title should have a body", ta) } RsAbstractableOwner.Foreign -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.typeParameterList, holder, "$title cannot have generic parameters") deny(ta.whereClause, holder, "$title cannot have `where` clause") deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") deny(ta.typeReference, holder, "$title cannot have a body", ta) } } } private fun checkConstant(holder: AnnotationHolder, const: RsConstant) { val name = const.nameLikeElement.text val title = if (const.static != null) "Static constant `$name`" else "Constant `$name`" when (const.owner) { is RsAbstractableOwner.Free -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.expr, holder, "$title must have a value", const) } is RsAbstractableOwner.Foreign -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.static, holder, "Only static constants are allowed in extern blocks", const.const) deny(const.expr, holder, "Static constants in extern blocks cannot have values", const.eq, const.expr) } is RsAbstractableOwner.Trait -> { deny(const.vis, holder, "$title cannot have the `pub` qualifier") deny(const.default, holder, "$title cannot have the `default` qualifier") deny(const.static, holder, "Static constants are not allowed in traits") } is RsAbstractableOwner.Impl -> { deny(const.static, holder, "Static constants are not allowed in impl blocks") require(const.expr, holder, "$title must have a value", const) } } checkConstantType(holder, const) } private fun checkConstantType(holder: AnnotationHolder, element: RsConstant) { if (element.colon == null && element.typeReference == null) { val typeText = if (element.isConst) { "const" } else { "static" } val message = "Missing type for `$typeText` item" val annotation = holder.newAnnotation(HighlightSeverity.ERROR, message) .range(element.textRange) val expr = element.expr if (expr != null) { annotation.withFix(AddTypeFix(element.nameLikeElement, expr.type)) } annotation.create() } } private fun checkValueParameterList(holder: AnnotationHolder, params: RsValueParameterList) { val fn = params.parent as? RsFunction ?: return when (fn.owner) { is RsAbstractableOwner.Free -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") checkVariadic(holder, fn, params.variadic?.dotdotdot) } is RsAbstractableOwner.Trait, is RsAbstractableOwner.Impl -> { deny(params.variadic?.dotdotdot, holder, "${fn.title} cannot be variadic") } RsAbstractableOwner.Foreign -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") checkDot3Parameter(holder, params.variadic?.dotdotdot) } } } private fun checkVariadic(holder: AnnotationHolder, fn: RsFunction, dot3: PsiElement?) { if (dot3 == null) return if (fn.isUnsafe && fn.abiName == "C") { C_VARIADIC.check(holder, dot3, "C-variadic functions") } else { deny(dot3, holder, "${fn.title} cannot be variadic") } } private fun checkDot3Parameter(holder: AnnotationHolder, dot3: PsiElement?) { if (dot3 == null) return dot3.rightVisibleLeaves .first { if (it.text != ")") { holder.newAnnotation(HighlightSeverity.ERROR, "`...` must be last in argument list for variadic function") .range(it).create() } return } } private fun checkValueParameter(holder: AnnotationHolder, param: RsValueParameter) { val fn = param.parent.parent as? RsFunction ?: return when (fn.owner) { is RsAbstractableOwner.Free, is RsAbstractableOwner.Impl, is RsAbstractableOwner.Foreign -> { require(param.pat, holder, "${fn.title} cannot have anonymous parameters", param) } is RsAbstractableOwner.Trait -> { denyType<RsPatTup>(param.pat, holder, "${fn.title} cannot have tuple parameters", param) if (param.pat == null) { val message = "Anonymous functions parameters are deprecated (RFC 1685)" val annotation = holder.newAnnotation(HighlightSeverity.WARNING, message) val fix = SubstituteTextFix.replace( "Add dummy parameter name", param.containingFile, param.textRange, "_: ${param.text}" ) val descriptor = InspectionManager.getInstance(param.project) .createProblemDescriptor(param, message, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true) annotation.newLocalQuickFix(fix, descriptor).registerFix().create() } } } } private fun checkTypeParameterList(holder: AnnotationHolder, element: RsTypeParameterList) { if (element.parent is RsImplItem || element.parent is RsFunction) { element.typeParameterList .mapNotNull { it.typeReference } .forEach { holder.newAnnotation( HighlightSeverity.ERROR, "Defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions" ).range(it).create() } } else { val lastNotDefaultIndex = max(element.typeParameterList.indexOfLast { it.typeReference == null }, 0) element.typeParameterList .take(lastNotDefaultIndex) .filter { it.typeReference != null } .forEach { holder.newAnnotation(HighlightSeverity.ERROR, "Type parameters with a default must be trailing") .range(it).create() } } checkTypeList(element, "parameters", holder) } private fun checkTypeArgumentList(holder: AnnotationHolder, args: RsTypeArgumentList) { checkTypeList(args, "arguments", holder) val startOfAssocTypeBindings = args.assocTypeBindingList.firstOrNull()?.textOffset ?: return for (generic in args.lifetimeList + args.typeReferenceList + args.exprList) { if (generic.textOffset > startOfAssocTypeBindings) { holder.newAnnotation(HighlightSeverity.ERROR, "Generic arguments must come before the first constraint") .range(generic).create() } } } private fun checkTypeList(typeList: PsiElement, elementsName: String, holder: AnnotationHolder) { var kind = TypeKind.LIFETIME typeList.forEachChild { child -> val newKind = TypeKind.forType(child) ?: return@forEachChild if (newKind.canStandAfter(kind)) { kind = newKind } else { val newStateName = newKind.presentableName.capitalized() holder.newAnnotation( HighlightSeverity.ERROR, "$newStateName $elementsName must be declared prior to ${kind.presentableName} $elementsName" ).range(child).create() } } } private fun checkExternAbi(holder: AnnotationHolder, element: RsExternAbi) { val litExpr = element.litExpr ?: return val abyLiteralKind = litExpr.kind ?: return if (abyLiteralKind !is RsLiteralKind.String) { holder.newAnnotation(HighlightSeverity.ERROR, "Non-string ABI literal").range(litExpr).create() } } private fun checkModDeclItem(holder: AnnotationHolder, element: RsModDeclItem) { checkInvalidUnsafe(holder, element.unsafe, "Module") } private fun checkModItem(holder: AnnotationHolder, element: RsModItem) { checkInvalidUnsafe(holder, element.unsafe, "Module") } private fun checkForeignModItem(holder: AnnotationHolder, element: RsForeignModItem) { checkInvalidUnsafe(holder, element.unsafe, "Extern block") } private fun checkInvalidUnsafe(holder: AnnotationHolder, unsafe: PsiElement?, itemName: String) { if (unsafe != null) { holder.newAnnotation(HighlightSeverity.ERROR, "$itemName cannot be declared unsafe").range(unsafe).create() } } private fun checkLetExpr(holder: AnnotationHolder, element: RsLetExpr) { var ancestor = element.parent while (when (ancestor) { is RsCondition, is RsMatchArmGuard -> return is RsBinaryExpr -> ancestor.binaryOp.andand != null else -> false }) { ancestor = ancestor.parent } deny(element, holder, "`let` expressions are not supported here") } private enum class TypeKind { LIFETIME, TYPE, CONST; val presentableName: String get() = name.lowercase() fun canStandAfter(prev: TypeKind): Boolean = this !== LIFETIME || prev === LIFETIME companion object { fun forType(seekingElement: PsiElement): TypeKind? = when (seekingElement) { is RsLifetimeParameter, is RsLifetime -> LIFETIME is RsTypeParameter, is RsTypeReference -> TYPE is RsConstParameter, is RsExpr -> CONST else -> null } } } private fun require(el: PsiElement?, holder: AnnotationHolder, message: String, vararg highlightElements: PsiElement?): Unit? = if (el != null || highlightElements.combinedRange == null) null else { holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange!!).create() } private fun deny( el: PsiElement?, holder: AnnotationHolder, @InspectionMessage message: String, vararg highlightElements: PsiElement? ) { if (el == null) return holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange ?: el.textRange).create() } private inline fun <reified T : RsElement> denyType( el: PsiElement?, holder: AnnotationHolder, @InspectionMessage message: String, vararg highlightElements: PsiElement? ) { if (el !is T) return holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange ?: el.textRange).create() } private val Array<out PsiElement?>.combinedRange: TextRange? get() = if (isEmpty()) null else filterNotNull() .map { it.textRange } .reduce(TextRange::union) private val PsiElement.rightVisibleLeaves: Sequence<PsiElement> get() = generateSequence(PsiTreeUtil.nextVisibleLeaf(this)) { el -> PsiTreeUtil.nextVisibleLeaf(el) } private val String.firstLower: String get() = if (isEmpty()) this else this[0].lowercaseChar() + substring(1)
mit
4531e71fc5936c62ec07a8e58d115843
40.305288
132
0.653029
4.595614
false
false
false
false
google/dokka
runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AbstractDokkaAndroidGradleTest.kt
2
1872
package org.jetbrains.dokka.gradle import org.junit.BeforeClass import java.io.File abstract class AbstractDokkaAndroidGradleTest : AbstractDokkaGradleTest() { override val pluginClasspath: List<File> = androidPluginClasspathData.toFile().readLines().map { File(it) } companion object { @JvmStatic @BeforeClass fun acceptAndroidSdkLicenses() { val sdkDir = androidLocalProperties?.toFile()?.let { val lines = it.readLines().map { it.trim() } val sdkDirLine = lines.firstOrNull { "sdk.dir" in it } sdkDirLine?.substringAfter("=")?.trim() } ?: System.getenv("ANDROID_HOME") if (sdkDir == null || sdkDir.isEmpty()) { error("Android SDK home not set, " + "try setting \$ANDROID_HOME " + "or sdk.dir in runners/gradle-integration-tests/testData/android.local.properties") } val sdkDirFile = File(sdkDir) if (!sdkDirFile.exists()) error("\$ANDROID_HOME and android.local.properties points to non-existing location") val sdkLicensesDir = sdkDirFile.resolve("licenses") val acceptedLicenses = File("android-licenses") acceptedLicenses.listFiles().forEach { licenseFile -> val target = sdkLicensesDir.resolve(licenseFile.name) if(!target.exists() || target.readText() != licenseFile.readText()) { val overwrite = System.getProperty("android.licenses.overwrite", "false").toBoolean() if (!target.exists() || overwrite) { licenseFile.copyTo(target, true) println("Accepted ${licenseFile.name}, by copying $licenseFile to $target") } } } } } }
apache-2.0
1d770d2e0b9fd5271ae1587f5a493cf0
40.622222
122
0.576923
4.965517
false
true
false
false
physphil/UnitConverterUltimate
v6000/src/main/java/com/physphil/android/unitconverterultimate/data/TemperatureConverter.kt
1
6112
package com.physphil.android.unitconverterultimate.data import com.physphil.android.unitconverterultimate.models.Temperature import java.math.BigDecimal import java.math.RoundingMode object TemperatureConverter : Converter<Temperature> { override fun convert(value: BigDecimal, initial: Temperature, final: Temperature): BigDecimal = when (final) { Temperature.Celsius -> value.toCelsius(initial) Temperature.Fahrenheit -> value.toFahrenheit(initial) Temperature.Kelvin -> value.toKelvin(initial) Temperature.Rankine -> value.toRankine(initial) Temperature.Delisle -> value.toDelisle(initial) Temperature.Newton -> value.toNewton(initial) Temperature.Reaumur -> value.toReaumur(initial) Temperature.Romer -> value.toRomer(initial) } private fun BigDecimal.toCelsius(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this Temperature.Fahrenheit -> (this - 32) * 5 / 9 Temperature.Kelvin -> this - 273.15 Temperature.Rankine -> (this - 491.67) * 5 / 9 Temperature.Delisle -> 100 - this * 2 / 3 Temperature.Newton -> this * 100 / 33 Temperature.Reaumur -> this * 5 / 4 Temperature.Romer -> (this - 7.5) * 40 / 21 } private fun BigDecimal.toFahrenheit(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 9 / 5 + 32 Temperature.Fahrenheit -> this Temperature.Kelvin -> this * 9 / 5 - 459.67 Temperature.Rankine -> this - 459.67 Temperature.Delisle -> 212 - this * 6 / 5 Temperature.Newton -> this * 60 / 11 + 32 Temperature.Reaumur -> this * 9 / 4 + 32 Temperature.Romer -> (this - 7.5) * 24 / 7 + 32 } private fun BigDecimal.toKelvin(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this + 273.15 Temperature.Fahrenheit -> (this + 459.67) * 5 / 9 Temperature.Kelvin -> this Temperature.Rankine -> this * 5 / 9 Temperature.Delisle -> 373.15 - this * 2 / 3 Temperature.Newton -> this * 100 / 33 + 273.15 Temperature.Reaumur -> this * 5 / 4 + 273.15 Temperature.Romer -> (this - 7.5) * 40 / 21 + 273.15 } private fun BigDecimal.toRankine(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> (this + 273.15) * 9 / 5 Temperature.Fahrenheit -> this + 459.67 Temperature.Kelvin -> this * 9 / 5 Temperature.Rankine -> this Temperature.Delisle -> 671.67 - this * 6 / 5 Temperature.Newton -> this * 60 / 11 + 491.67 Temperature.Reaumur -> this * 9 / 4 + 491.67 Temperature.Romer -> (this - 7.5) * 24 / 7 + 491.67 } private fun BigDecimal.toDelisle(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> (100 - this) * 1.5 Temperature.Fahrenheit -> (212 - this) * 5 / 6 Temperature.Kelvin -> (373.15 - this) * 1.5 Temperature.Rankine -> (671.67 - this) * 5 / 6 Temperature.Delisle -> this Temperature.Newton -> (33 - this) * 50 / 11 Temperature.Reaumur -> (80 - this) * 1.875 Temperature.Romer -> (60 - this) * 20 / 7 } private fun BigDecimal.toNewton(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 33 / 100 Temperature.Fahrenheit -> (this - 32) * 11 / 60 Temperature.Kelvin -> (this - 273.15) * 33 / 100 Temperature.Rankine -> (this - 491.67) * 11 / 60 Temperature.Delisle -> 33 - this * 11 / 50 Temperature.Newton -> this Temperature.Reaumur -> this * 33 / 80 Temperature.Romer -> (this - 7.5) * 22 / 35 } private fun BigDecimal.toReaumur(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 4 / 5 Temperature.Fahrenheit -> (this - 32) * 4 / 9 Temperature.Kelvin -> (this - 273.15) * 4 / 5 Temperature.Rankine -> (this - 491.67) * 4 / 9 Temperature.Delisle -> 80 - this * 8 / 15 Temperature.Newton -> this * 80 / 33 Temperature.Reaumur -> this Temperature.Romer -> (this - 7.5) * 32 / 21 } private fun BigDecimal.toRomer(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 21 / 40 + 7.5 Temperature.Fahrenheit -> (this - 32) * 7 / 24 + 7.5 Temperature.Kelvin -> (this - 273.15) * 21 / 40 + 7.5 Temperature.Rankine -> (this - 491.67) * 7 / 24 + 7.5 Temperature.Delisle -> 60 - this * 7 / 20 Temperature.Newton -> this * 35 / 22 + 7.5 Temperature.Reaumur -> this * 21 / 32 + 7.5 Temperature.Romer -> this } private operator fun BigDecimal.plus(i: Int): BigDecimal = this + i.toBigDecimal() private operator fun BigDecimal.plus(d: Double): BigDecimal = this + d.toBigDecimal() private operator fun BigDecimal.minus(i: Int): BigDecimal = this - i.toBigDecimal() private operator fun BigDecimal.minus(d: Double): BigDecimal = this - d.toBigDecimal() private operator fun BigDecimal.times(i: Int): BigDecimal = this * i.toBigDecimal() private operator fun BigDecimal.times(d: Double): BigDecimal = this * d.toBigDecimal() private operator fun BigDecimal.div(i: Int): BigDecimal = this.divide(i.toBigDecimal(), SCALE_RESULT, RoundingMode.HALF_UP) private operator fun Int.minus(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() - bigDecimal private operator fun Int.times(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() * bigDecimal private operator fun Double.minus(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() - bigDecimal }
apache-2.0
fd8bd55edac0ef607b3622c3a9e287f3
46.387597
127
0.585242
4.378223
false
false
false
false
willjgriff/android-ethereum-wallet
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/nodedetails/NodeDetailsController.kt
1
4083
package com.github.willjgriff.ethereumwallet.ui.screens.nodedetails import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.github.willjgriff.ethereumwallet.R import com.github.willjgriff.ethereumwallet.di.AppInjector import com.github.willjgriff.ethereumwallet.mvp.BaseMvpControllerKotlin import com.github.willjgriff.ethereumwallet.ui.navigation.NavigationToolbarListener import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.di.DaggerNodeDetailsComponent import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsHeadersAdapter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsHeadersAdapter.NodeStatusHeadersAdapterListener import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsPeersAdapter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.mvp.NodeDetailsPresenter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.mvp.NodeDetailsView import com.github.willjgriff.ethereumwallet.ui.utils.inflate import kotlinx.android.synthetic.main.controller_node_status.view.* import javax.inject.Inject /** * Created by Will on 20/03/2017. */ class NodeDetailsController : BaseMvpControllerKotlin<NodeDetailsView, NodeDetailsPresenter>(), NodeDetailsView, NodeStatusHeadersAdapterListener { override val mvpView: NodeDetailsView get() = this @Inject lateinit override var presenter: NodeDetailsPresenter private lateinit var nodeDetails: TextView private lateinit var syncProgress: TextView private lateinit var peers: TextView private lateinit var peersInfo: RecyclerView private lateinit var headers: RecyclerView private val mPeersAdapter: NodeDetailsPeersAdapter = NodeDetailsPeersAdapter() private val mHeadersAdapter: NodeDetailsHeadersAdapter = NodeDetailsHeadersAdapter(this) init { DaggerNodeDetailsComponent.builder() .appComponent(AppInjector.appComponent) .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_node_status) setupToolbarTitle() bindViews(view) setupRecyclerViews() return view } private fun setupToolbarTitle() { if (targetController is NavigationToolbarListener) { (targetController as NavigationToolbarListener) .setToolbarTitle(applicationContext!!.getString(R.string.controller_node_details_title)) } } private fun bindViews(view: View) { peers = view.controller_node_status_peers peersInfo = view.controller_node_status_peers_list headers = view.controller_node_status_headers_list nodeDetails = view.controller_node_status_node_details syncProgress = view.controller_node_status_sync_progress } private fun setupRecyclerViews() { headers.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = mHeadersAdapter } peersInfo.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = mPeersAdapter } } override fun headerInserted(position: Int) { headers.scrollToPosition(position) } override fun newHeaderHash(headerHash: String) { mHeadersAdapter.addHeaderHash(headerHash) } override fun updateNumberOfPeers(numberOfPeers: Long) { peers.text = "Peers: $numberOfPeers" } override fun setNodeDetails(nodeInfoString: String) { nodeDetails.text = nodeInfoString } override fun setSyncProgress(syncProgressString: String) { syncProgress.text = syncProgressString } override fun setPeerStrings(peers: List<String>) { mPeersAdapter.peers = peers } }
apache-2.0
cf4b948a3443fd6f03ab1ce25a08a68b
37.518868
130
0.750184
4.979268
false
false
false
false
sebasjm/deepdiff
src/test/java/diff/equality/strategies/OrderedMapEqualityStrategyTest.kt
1
1903
package diff.equality.strategies import diff.equality.EqualityStrategy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import java.util.* /** * Created by sebasjm on 07/07/17. */ class OrderedMapEqualityStrategyTest { @Test fun shouldReturnEqualsWhenComparingTwoEmptyTreeMaps() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> val compare = OrderedMapEqualityStrategy().compare(before, after) assert( compare == EqualityStrategy.CompareResult.EQUALS ) } @Test fun shouldReturnUndecidibleWhenMapsHasContents() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> before.put("1","something") before.put("2","something") val compare = OrderedMapEqualityStrategy().compare(before, after) as? EqualityStrategy.UndecidibleMoreToCompare<*> ?: throw AssertionError("Assertion failed") assertEquals( compare.result.size, before.size * 2 ) } @Test fun shouldQueueOrderComparisonAndKeyComparisonForOrderedMaps() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> before.put("1","something") before.put("2","something") val compare = OrderedMapEqualityStrategy().compare(before, after) as? EqualityStrategy.UndecidibleMoreToCompare<*> ?: throw AssertionError("Assertion failed") assertEquals( compare.result.size, before.size * 2 ) } @Test fun shouldCompareTreeMap() { val map = TreeMap<String,String>() as SortedMap<Any,Any> assertTrue( OrderedMapEqualityStrategy().shouldUseThisStrategy(map.javaClass) ) } }
apache-2.0
1afdc80525392dc30659a7e1e9ca3999
33.618182
104
0.699422
4.596618
false
true
false
false
hpedrorodrigues/GZMD
app/src/main/kotlin/com/hpedrorodrigues/gzmd/adapter/PreviewAdapter.kt
1
2092
/* * Copyright 2016 Pedro Rodrigues * * 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.hpedrorodrigues.gzmd.adapter import android.view.LayoutInflater import android.view.ViewGroup import com.hpedrorodrigues.gzmd.R import com.hpedrorodrigues.gzmd.entity.Preview import com.hpedrorodrigues.gzmd.adapter.holder.PreviewHolder import com.squareup.picasso.Picasso import javax.inject.Inject class PreviewAdapter : BaseAdapter<Preview, PreviewHolder> { @Inject lateinit var inflater: LayoutInflater @Inject constructor() : super() var onPreviewClick: OnPreviewClick? = null override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PreviewHolder? { return PreviewHolder(inflater.inflate(R.layout.preview, parent, false)) } override fun onBindViewHolder(holder: PreviewHolder, position: Int) { val preview = content[position] holder.title.text = preview.title holder.authorName.text = preview.authorName holder.postedAt.text = preview.postedAt holder.sharesCount.text = preview.sharesCount.toString() holder.commentsCount.text = preview.commentsCount.toString() holder.image.labelText = preview.tagName.toUpperCase() holder.view.setOnClickListener { onPreviewClick?.onClick(preview) } Picasso.with(holder.image.context) .load(preview.imageUrl) .placeholder(R.drawable.preview_background) .into(holder.image) } interface OnPreviewClick { fun onClick(preview: Preview) } }
apache-2.0
bcf346055a56ef5a8f21fb6980b6e126
31.703125
88
0.722753
4.470085
false
false
false
false
tasomaniac/OpenLinkWith
redirect/src/main/kotlin/com/tasomaniac/openwith/redirect/RedirectFixActivity.kt
1
2941
package com.tasomaniac.openwith.redirect import android.app.Activity import android.content.ComponentName import android.content.Intent import android.net.Uri import android.os.Bundle import com.tasomaniac.android.widget.DelayedProgressBar import com.tasomaniac.openwith.resolver.ResolverActivity import com.tasomaniac.openwith.rx.SchedulingStrategy import dagger.android.support.DaggerAppCompatActivity import io.reactivex.Maybe import io.reactivex.MaybeTransformer import io.reactivex.Single import io.reactivex.disposables.Disposable import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import javax.inject.Inject class RedirectFixActivity : DaggerAppCompatActivity() { @Inject lateinit var browserIntentChecker: BrowserIntentChecker @Inject lateinit var redirectFixer: RedirectFixer @Inject lateinit var urlFix: UrlFix @Inject lateinit var schedulingStrategy: SchedulingStrategy private var disposable: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.redirect_activity) val progress = findViewById<DelayedProgressBar>(R.id.resolver_progress) progress.show(true) val source = Intent(intent).apply { component = null } disposable = Single.just(source) .filter { browserIntentChecker.hasOnlyBrowsers(it) } .map { urlFix.fixUrls(it.dataString!!) } .flatMap { Maybe.fromCallable<HttpUrl> { it.toHttpUrlOrNull() } } .compose(redirectTransformer) .map(HttpUrl::toString) .toSingle(source.dataString!!) // fall-back to original data if anything goes wrong .map(urlFix::fixUrls) // fix again after potential redirect .map { source.withUrl(it) } .compose(schedulingStrategy.forSingle()) .subscribe { intent -> intent.component = ComponentName(this, ResolverActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT) startActivity(intent) finish() } } private val redirectTransformer = MaybeTransformer<HttpUrl, HttpUrl> { source -> source.flatMap { httpUrl -> redirectFixer .followRedirects(httpUrl) .toMaybe() } } override fun onDestroy() { disposable?.dispose() super.onDestroy() } companion object { @JvmStatic fun createIntent(activity: Activity, foundUrl: String): Intent { return Intent(activity, RedirectFixActivity::class.java) .putExtras(activity.intent) .setAction(Intent.ACTION_VIEW) .setData(Uri.parse(foundUrl)) } private fun Intent.withUrl(url: String): Intent = setData(Uri.parse(url)) } }
apache-2.0
3b9c6a46fc696dc7055ad8b16859ff8a
34.011905
95
0.66984
4.91806
false
false
false
false
wax911/AniTrendApp
app/src/main/java/com/mxt/anitrend/worker/AuthenticatorWorker.kt
1
3337
package com.mxt.anitrend.worker import android.content.Context import android.net.Uri import android.text.TextUtils import androidx.work.Data import androidx.work.ListenableWorker import androidx.work.Worker import androidx.work.WorkerParameters import com.mxt.anitrend.BuildConfig import com.mxt.anitrend.base.custom.async.WebTokenRequest import com.mxt.anitrend.presenter.base.BasePresenter import com.mxt.anitrend.util.KeyUtil import org.koin.core.KoinComponent import org.koin.core.inject import timber.log.Timber import java.util.concurrent.ExecutionException class AuthenticatorWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams), KoinComponent { private val presenter by inject<BasePresenter>() private val authenticatorUri: Uri by lazy(LazyThreadSafetyMode.NONE) { Uri.parse(workerParams.inputData .getString(KeyUtil.arg_model)) } /** * Override this method to do your actual background processing. This method is called on a * background thread - you are required to **synchronously** do your work and return the * [Result] from this method. Once you return from this * method, the Worker is considered to have finished what its doing and will be destroyed. If * you need to do your work asynchronously on a thread of your own choice, see * [ListenableWorker]. * * * A Worker is given a maximum of ten minutes to finish its execution and return a * [Result]. After this time has expired, the Worker will * be signalled to stop. * * @return The [Result] of the computation; note that * dependent work will not execute if you use * [Result.failure] or * [Result.failure] */ override fun doWork(): Result { val errorDataBuilder = Data.Builder() try { val authorizationCode = authenticatorUri.getQueryParameter(BuildConfig.RESPONSE_TYPE) if (!TextUtils.isEmpty(authorizationCode)) { val isSuccess = WebTokenRequest.getToken(authorizationCode) presenter.settings.isAuthenticated = isSuccess val outputData = Data.Builder() .putBoolean(KeyUtil.arg_model, isSuccess) .build() return Result.success(outputData) } else Timber.tag(TAG).e("Authorization authenticatorUri was empty or null, cannot authenticate with the current state") } catch (e: ExecutionException) { e.printStackTrace() errorDataBuilder.putString(KeyUtil.arg_exception_error, e.message) } catch (e: InterruptedException) { e.printStackTrace() errorDataBuilder.putString(KeyUtil.arg_exception_error, e.message) } val workerErrorOutputData = errorDataBuilder .putString(KeyUtil.arg_uri_error, authenticatorUri .getQueryParameter(KeyUtil.arg_uri_error)) .putString(KeyUtil.arg_uri_error_description, authenticatorUri .getQueryParameter(KeyUtil.arg_uri_error_description)) .build() return Result.failure(workerErrorOutputData) } companion object { private val TAG = AuthenticatorWorker::class.java.simpleName } }
lgpl-3.0
a3fd22fe236db7554c12d9f9c46447dd
41.240506
129
0.680851
4.892962
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/utils/WorldStateSerialization.kt
1
3185
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.habitrpg.android.habitica.extensions.getAsString import com.habitrpg.android.habitica.models.WorldState import com.habitrpg.android.habitica.models.WorldStateEvent import com.habitrpg.android.habitica.models.inventory.QuestProgress import com.habitrpg.android.habitica.models.inventory.QuestRageStrike import io.realm.RealmList import java.lang.reflect.Type class WorldStateSerialization : JsonDeserializer<WorldState> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): WorldState { val state = WorldState() val obj = json?.asJsonObject ?: return state val worldBossObject = obj.get("worldBoss")?.asJsonObject if (worldBossObject != null) { if (worldBossObject.has("active") && !worldBossObject["active"].isJsonNull) { state.worldBossActive = worldBossObject["active"].asBoolean } if (worldBossObject.has("key") && !worldBossObject["key"].isJsonNull) { state.worldBossKey = worldBossObject["key"].asString } if (worldBossObject.has("progress")) { val progress = QuestProgress() val progressObj = worldBossObject.getAsJsonObject("progress") if (progressObj.has("hp")) { progress.hp = progressObj["hp"].asDouble } if (progressObj.has("rage")) { progress.rage = progressObj["rage"].asDouble } state.progress = progress } if (worldBossObject.has("extra")) { val extra = worldBossObject["extra"].asJsonObject if (extra.has("worldDmg")) { val worldDmg = extra["worldDmg"].asJsonObject state.rageStrikes = RealmList() worldDmg.entrySet().forEach { (key, value) -> val strike = QuestRageStrike(key, value.asBoolean) state.rageStrikes?.add(strike) } } } } state.npcImageSuffix = obj.getAsString("npcImageSuffix") try { if (obj.has("currentEvent") && obj.get("currentEvent")?.isJsonObject == true) { val event = obj.getAsJsonObject("currentEvent") if (event != null) { state.currentEvent = context?.deserialize(event, WorldStateEvent::class.java) } if (obj.has("currentEventList")) { val events = RealmList<WorldStateEvent>() for (element in obj.getAsJsonArray("currentEventList")) { context?.deserialize<WorldStateEvent>(element, WorldStateEvent::class.java)?.let { events.add(it) } } state.events = events } } } catch (e: Exception) { } return state } }
gpl-3.0
9bff8ade5523984022e8339b0761b43e
40.907895
123
0.578964
5.255776
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/gistlist/GistListPresenter.kt
1
6973
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.gistlist import giuliolodi.gitnav.data.DataManager import giuliolodi.gitnav.ui.base.BasePresenter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.eclipse.egit.github.core.Gist import timber.log.Timber import javax.inject.Inject /** * Created by giulio on 23/05/2017. */ class GistListPresenter<V: GistListContract.View> : BasePresenter<V>, GistListContract.Presenter<V> { private val TAG = "GistListPresenter" private var mGistList: MutableList<Gist> = mutableListOf() private var PAGE_N = 1 private var ITEMS_PER_PAGE = 20 private var LOADING: Boolean = false private var LOADING_LIST: Boolean = false private var MINE_STARRED: String = "mine" private var NO_SHOWING: Boolean = false @Inject constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager) override fun subscribe(isNetworkAvailable: Boolean) { if (!mGistList.isEmpty()) getView().showGists(mGistList) else if (LOADING) getView().showLoading() else if (NO_SHOWING) getView().showNoGists(MINE_STARRED) else { if (isNetworkAvailable) { LOADING = true getView().showLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else { getView().showNoConnectionError() getView().hideLoading() LOADING = false } } } override fun getMineGists() { getCompositeDisposable().add(getDataManager().pageGists(null, PAGE_N, ITEMS_PER_PAGE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { gistList -> getView().hideLoading() getView().hideListLoading() mGistList.addAll(gistList) getView().showGists(gistList) if (PAGE_N == 1 && gistList.isEmpty()) { getView().showNoGists(MINE_STARRED) NO_SHOWING = true } PAGE_N += 1 LOADING = false LOADING_LIST = false }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() getView().hideListLoading() Timber.e(throwable) LOADING = false LOADING_LIST = false } )) } override fun getStarredGists() { getCompositeDisposable().add(getDataManager().pageStarredGists(PAGE_N, ITEMS_PER_PAGE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { gistList -> mGistList.addAll(gistList) getView().showGists(gistList) getView().hideLoading() getView().hideListLoading() if (PAGE_N == 1 && gistList.isEmpty()) { getView().showNoGists(MINE_STARRED) NO_SHOWING = true } PAGE_N += 1 LOADING = false LOADING_LIST = false }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() getView().hideListLoading() Timber.e(throwable) LOADING = false LOADING_LIST = false } )) } override fun onSwipeToRefresh(isNetworkAvailable: Boolean) { if (isNetworkAvailable) { getView().hideNoGists() NO_SHOWING = false PAGE_N = 1 getView().clearAdapter() mGistList.clear() LOADING = true getView().showLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else { getView().showNoConnectionError() getView().hideLoading() } } override fun onLastItemVisible(isNetworkAvailable: Boolean, dy: Int) { if (LOADING_LIST) return if (isNetworkAvailable) { LOADING_LIST = true getView().showListLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else if (dy > 0) { getView().showNoConnectionError() getView().hideLoading() } } override fun onBottomViewMineGistClick(isNetworkAvailable: Boolean) { getView().showLoading() getView().hideNoGists() NO_SHOWING = false getView().clearAdapter() mGistList.clear() getView().setAdapterAndClickListener() PAGE_N = 1 MINE_STARRED = "mine" getMineGists() } override fun onBottomViewStarredGistClick(isNetworkAvailable: Boolean) { getView().showLoading() getView().hideNoGists() NO_SHOWING = false getView().clearAdapter() mGistList.clear() getView().setAdapterAndClickListener() PAGE_N = 1 MINE_STARRED = "starred" getStarredGists() } override fun onGistClick(gistId: String) { getView().intentToGistActivitiy(gistId) } override fun unsubscribe() { if (getCompositeDisposable().size() != 0) getCompositeDisposable().clear() } }
apache-2.0
39a42afcc9de69ede99106a661738b58
34.948454
129
0.521727
5.618856
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListPopularFragment.kt
1
8412
package org.stepik.android.view.course_list.ui.fragment import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_course_list.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.util.CoursesSnapHelper import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_list.model.CourseListQuery import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper import org.stepik.android.domain.filter.model.CourseListFilterQuery import org.stepik.android.domain.last_step.model.LastStep import org.stepik.android.model.Course import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource import org.stepik.android.presentation.course_list.CourseListQueryPresenter import org.stepik.android.presentation.course_list.CourseListQueryView import org.stepik.android.presentation.course_list.CourseListView import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager import org.stepik.android.view.course.mapper.DisplayPriceMapper import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate import org.stepik.android.view.course_list.delegate.CourseListViewDelegate import org.stepik.android.view.course_list.resolver.TableLayoutHorizontalSpanCountResolver import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.view.base.ui.extension.setOnPaginationListener import javax.inject.Inject class CourseListPopularFragment : Fragment(R.layout.item_course_list), CourseListQueryView { companion object { fun newInstance(): Fragment = CourseListPopularFragment() } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper @Inject internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper @Inject internal lateinit var displayPriceMapper: DisplayPriceMapper @Inject internal lateinit var tableLayoutHorizontalSpanCountResolver: TableLayoutHorizontalSpanCountResolver private lateinit var courseListViewDelegate: CourseListViewDelegate private val courseListQueryPresenter: CourseListQueryPresenter by viewModels { viewModelFactory } private lateinit var tableLayoutManager: TableLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) containerCarouselCount.isVisible = false containerTitle.text = resources.getString(R.string.course_list_popular_toolbar_title) val rowCount = resources.getInteger(R.integer.course_list_rows) val columnsCount = resources.getInteger(R.integer.course_list_columns) tableLayoutManager = TableLayoutManager(requireContext(), columnsCount, rowCount, RecyclerView.HORIZONTAL, false) with(courseListCoursesRecycler) { layoutManager = tableLayoutManager itemAnimator?.changeDuration = 0 val snapHelper = CoursesSnapHelper(rowCount) snapHelper.attachToRecyclerView(this) setOnPaginationListener { pageDirection -> if (pageDirection == PaginationDirection.NEXT) { courseListQueryPresenter.fetchNextPage() } } } val courseListQuery = CourseListQuery( page = 1, order = CourseListQuery.Order.ACTIVITY_DESC, isCataloged = true, filterQuery = CourseListFilterQuery(language = sharedPreferenceHelper.languageForFeatured) ) catalogBlockContainer.setOnClickListener { screenManager.showCoursesByQuery( requireContext(), resources.getString(R.string.course_list_popular_toolbar_title), courseListQuery ) } courseListPlaceholderEmpty.setOnClickListener { screenManager.showCatalog(requireContext()) } courseListPlaceholderEmpty.setPlaceholderText(R.string.empty_courses_popular) courseListPlaceholderNoConnection.setOnClickListener { courseListQueryPresenter.fetchCourses(courseListQuery = courseListQuery, forceUpdate = true) } courseListPlaceholderNoConnection.setText(R.string.internet_problem) val viewStateDelegate = ViewStateDelegate<CourseListView.State>() viewStateDelegate.addState<CourseListView.State.Idle>(catalogBlockContainer) viewStateDelegate.addState<CourseListView.State.Loading>(catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Content>(catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Empty>(courseListPlaceholderEmpty) viewStateDelegate.addState<CourseListView.State.NetworkError>(courseListPlaceholderNoConnection) courseListViewDelegate = CourseListViewDelegate( analytic = analytic, courseContinueViewDelegate = CourseContinueViewDelegate( activity = requireActivity(), analytic = analytic, screenManager = screenManager ), courseListTitleContainer = catalogBlockContainer, courseItemsRecyclerView = courseListCoursesRecycler, courseListViewStateDelegate = viewStateDelegate, onContinueCourseClicked = { courseListItem -> courseListQueryPresenter .continueCourse( course = courseListItem.course, viewSource = CourseViewSource.Query(courseListQuery), interactionSource = CourseContinueInteractionSource.COURSE_WIDGET ) }, defaultPromoCodeMapper = defaultPromoCodeMapper, displayPriceMapper = displayPriceMapper ) courseListQueryPresenter.fetchCourses(courseListQuery) } private fun injectComponent() { App.component() .courseListQueryComponentBuilder() .build() .inject(this) } override fun setState(state: CourseListQueryView.State) { val courseListState = (state as? CourseListQueryView.State.Data)?.courseListViewState ?: CourseListView.State.Idle if (courseListState == CourseListView.State.Empty) { analytic.reportEvent(Analytic.Error.FEATURED_EMPTY) } if (courseListState is CourseListView.State.Content) { tableLayoutHorizontalSpanCountResolver.resolveSpanCount(courseListState.courseListDataItems.size).let { resolvedSpanCount -> if (tableLayoutManager.spanCount != resolvedSpanCount) { tableLayoutManager.spanCount = resolvedSpanCount } } } courseListViewDelegate.setState(courseListState) } override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) { courseListViewDelegate.showCourse(course, source, isAdaptive) } override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) { courseListViewDelegate.showSteps(course, source, lastStep) } override fun setBlockingLoading(isLoading: Boolean) { courseListViewDelegate.setBlockingLoading(isLoading) } override fun showNetworkError() { courseListViewDelegate.showNetworkError() } override fun onStart() { super.onStart() courseListQueryPresenter.attachView(this) } override fun onStop() { courseListQueryPresenter.detachView(this) super.onStop() } }
apache-2.0
70da7ed5f706acf0fd23d70ae2806002
42.14359
157
0.735616
5.653226
false
false
false
false
enihsyou/Sorting-algorithm
CodeForces/908A.kt
1
602
import java.util.* fun main(args: Array<String>) { val vowels = listOf('a', 'e', 'i', 'o', 'u') val digits = "1234567890".toList() val s = Scanner(System.`in`) with(s) { var total = 0 nextLine() .forEach { when (it) { in vowels -> { total++ } in digits -> { if (it.toInt() % 2 == 1) { total++ } } } } println(total) } }
mit
30bb69f5c48f3a018c9f14e9a74f5d90
23.08
50
0.305648
4.666667
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectSimpleAnimation/app/src/main/java/me/liuqingwen/android/projectsimpleanimation/MainActivity.kt
1
2924
package me.liuqingwen.android.projectsimpleanimation import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.animation.DecelerateInterpolator import kotlinx.android.synthetic.main.layout_activity_main.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.displayMetrics class MainActivity : AppCompatActivity(), AnkoLogger { private var sunYStart = 0f private var sunYEnd = 0f private var duration = 10000L private var sunSetDelay = 2000L override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.init() } private fun init() { //this.skyView.translationY = - this.skyView.height.toFloat() this.sunYStart = this.sunView.top.toFloat() this.sunYEnd = this.displayMetrics.heightPixels.toFloat() this.skyView.alpha = 0.0f this.sunSet() } private fun sunSet() { val animSun = ObjectAnimator.ofFloat(this.sunView, "y", this.sunYStart, this.sunYEnd).setDuration(this.duration) animSun.interpolator = DecelerateInterpolator() val animSky = ObjectAnimator.ofFloat(this.skyView, "alpha", 0.0f, 1.0f).setDuration(this.duration - 2000) val animSet = AnimatorSet() animSet.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { [email protected]() } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) animSet.play(animSun).with(animSky) animSet.startDelay = this.sunSetDelay animSet.start() } private fun sunRise() { val animSun = ObjectAnimator.ofFloat(this.sunView, "y", this.sunYEnd, this.sunYStart).setDuration(this.duration) //anim.interpolator = DecelerateInterpolator() val animSky = ObjectAnimator.ofFloat(this.skyView, "alpha", 1.0f, 0.0f).setDuration(this.duration - 2000) val animSet = AnimatorSet() animSet.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { [email protected]() } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) animSet.play(animSun).with(animSky) animSet.start() } }
mit
55b9cd29f27bae98a2934de7caf36183
33
120
0.651505
4.793443
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopShouldStartLoadWithRequestEvent.kt
2
991
package abi42_0_0.host.exp.exponent.modules.api.components.webview.events import abi42_0_0.com.facebook.react.bridge.WritableMap import abi42_0_0.com.facebook.react.uimanager.events.Event import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when shouldOverrideUrlLoading is called */ class TopShouldStartLoadWithRequestEvent(viewId: Int, private val mData: WritableMap) : Event<TopShouldStartLoadWithRequestEvent>(viewId) { companion object { const val EVENT_NAME = "topShouldStartLoadWithRequest" } init { mData.putString("navigationType", "other") // Android does not raise shouldOverrideUrlLoading for inner frames mData.putBoolean("isTopFrame", true) } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, mData) }
bsd-3-clause
3c7d9fd80d5ffab9d29619b4f655ae55
33.172414
139
0.775984
4.217021
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/unknowntypes/test/api/UnknownFieldEntityImpl.kt
3
5678
package com.intellij.workspaceModel.storage.entities.unknowntypes.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import java.util.Date import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class UnknownFieldEntityImpl: UnknownFieldEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: Date? = null override val data: Date get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: UnknownFieldEntityData?): ModifiableWorkspaceEntityBase<UnknownFieldEntity>(), UnknownFieldEntity.Builder { constructor(): this(UnknownFieldEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity UnknownFieldEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isDataInitialized()) { error("Field UnknownFieldEntity#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field UnknownFieldEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: Date get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): UnknownFieldEntityData = result ?: super.getEntityData() as UnknownFieldEntityData override fun getEntityClass(): Class<UnknownFieldEntity> = UnknownFieldEntity::class.java } } class UnknownFieldEntityData : WorkspaceEntityData<UnknownFieldEntity>() { lateinit var data: Date fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<UnknownFieldEntity> { val modifiable = UnknownFieldEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): UnknownFieldEntity { val entity = UnknownFieldEntityImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return UnknownFieldEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as UnknownFieldEntityData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as UnknownFieldEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
apache-2.0
8f70b0c67bf57ae30ca3aee589936ad6
33.840491
137
0.644769
6.118534
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/simple/SimpleRecurrentBackwardHelper.kt
1
2982
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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 com.kotlinnlp.simplednn.core.layers.models.recurrent.simple import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.core.arrays.getInputErrors import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the backward on a [layer]. * * @property layer the [SimpleRecurrentLayer] in which the backward is executed */ internal class SimpleRecurrentBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: SimpleRecurrentLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { val prevStateLayer = this.layer.layersWindow.getPrevState() val nextStateLayer = this.layer.layersWindow.getNextState() if (nextStateLayer != null) { this.addLayerRecurrentGradients(nextStateLayer as SimpleRecurrentLayer<*>) } this.layer.applyOutputActivationDeriv() // must be applied AFTER having added the recurrent contribution this.assignParamsGradients(prevStateLayer?.outputArray) if (propagateToInput) { this.assignLayerGradients() } } /** * gb = gy * 1 * gw = gb (dot) x * gwRec = gy (dot) yPrev * * @param prevStateOutput the output array in the previous state */ private fun assignParamsGradients(prevStateOutput: AugmentedArray<DenseNDArray>?) { this.layer.outputArray.assignParamsGradients( gw = this.layer.params.unit.weights.errors.values, gb = this.layer.params.unit.biases.errors.values, gwRec = this.layer.params.unit.recurrentWeights.errors.values, x = this.layer.inputArray.values, yPrev = prevStateOutput?.values) } /** * gx = gb (dot) w */ private fun assignLayerGradients() { this.layer.inputArray.assignErrors(this.layer.outputArray.getInputErrors(w = this.layer.params.unit.weights.values)) } /** * gy += gyNext (dot) wRec */ private fun addLayerRecurrentGradients(nextStateLayer: SimpleRecurrentLayer<*>) { val gy: DenseNDArray = this.layer.outputArray.errors val gRec: DenseNDArray = nextStateLayer.outputArray.getRecurrentErrors(parameters = this.layer.params.unit) gy.assignSum(gRec) } }
mpl-2.0
541f76b29fc7b28f08dbca12c63bc830
34.5
120
0.727029
4.511346
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/compose/components/SecondaryButton.kt
1
1553
package org.wordpress.android.ui.main.jetpack.migration.compose.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.dp import org.wordpress.android.R @Composable fun SecondaryButton( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true ) { Button( onClick = onClick, enabled = enabled, elevation = ButtonDefaults.elevation( defaultElevation = 0.dp, pressedElevation = 0.dp, ), colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = MaterialTheme.colors.primary, disabledBackgroundColor = Color.Transparent, disabledContentColor = MaterialTheme.colors.primary, ), modifier = modifier .padding(bottom = 10.dp) .padding(horizontal = dimensionResource(R.dimen.jp_migration_buttons_padding_horizontal)) .fillMaxWidth() ) { Text(text = text) } }
gpl-2.0
87b15ac3daba2d18ab2fab759d87ae74
35.116279
109
0.661301
4.993569
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/IndexHelper.kt
1
4040
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.fir import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.impl.search.AllClassesSearchExecutor import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StringStubIndexExtension import org.jetbrains.kotlin.analysis.project.structure.allDirectDependencies import org.jetbrains.kotlin.analysis.project.structure.getKtModule import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.base.utils.fqname.isJavaClassNotToBeUsedInKotlin import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.idea.util.isSyntheticKotlinClass import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration /* * Move to another module */ class HLIndexHelper(val project: Project, private val scope: GlobalSearchScope) { fun getTopLevelCallables(nameFilter: (Name) -> Boolean): Collection<KtCallableDeclaration> { fun sequenceOfElements(index: StringStubIndexExtension<out KtCallableDeclaration>): Sequence<KtCallableDeclaration> = index.getAllKeys(project).asSequence() .onEach { ProgressManager.checkCanceled() } .filter { fqName -> nameFilter(getShortName(fqName)) } .flatMap { fqName -> index[fqName, project, scope] } .filter { it.receiverTypeReference == null } val functions = sequenceOfElements(KotlinTopLevelFunctionFqnNameIndex) val properties = sequenceOfElements(KotlinTopLevelPropertyFqnNameIndex) return (functions + properties).toList() } fun getTopLevelExtensions(nameFilter: (Name) -> Boolean, receiverTypeNames: Set<String>): Collection<KtCallableDeclaration> { val index = KotlinTopLevelExtensionsByReceiverTypeIndex return index.getAllKeys(project).asSequence() .onEach { ProgressManager.checkCanceled() } .filter { KotlinTopLevelExtensionsByReceiverTypeIndex.receiverTypeNameFromKey(it) in receiverTypeNames } .filter { nameFilter(Name.identifier(KotlinTopLevelExtensionsByReceiverTypeIndex.callableNameFromKey(it))) } .flatMap { key -> index[key, project, scope] } .toList() } fun getPossibleTypeAliasExpansionNames(originalTypeName: String): Set<String> { val index = KotlinTypeAliasByExpansionShortNameIndex val out = mutableSetOf<String>() fun searchRecursively(typeName: String) { ProgressManager.checkCanceled() index[typeName, project, scope].asSequence() .mapNotNull { it.name } .filter { out.add(it) } .forEach(::searchRecursively) } searchRecursively(originalTypeName) return out } companion object { private fun FqName.asStringForIndexes(): String = asString().replace('/', '.') private fun ClassId.asStringForIndexes(): String = asSingleFqName().asStringForIndexes() private fun getShortName(fqName: String) = Name.identifier(fqName.substringAfterLast('.')) @OptIn(ExperimentalStdlibApi::class) fun createForPosition(position: PsiElement): HLIndexHelper { val module = position.getKtModule() val allScopes = module.allDirectDependencies().mapTo(mutableSetOf()) { it.contentScope } allScopes.add(module.contentScope) return HLIndexHelper(position.project, GlobalSearchScope.union(allScopes)) } } }
apache-2.0
1e2682dd1a91c9517f26e3942f553875
44.393258
129
0.729208
5.186136
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryExternalSystemIdEntityImpl.kt
1
9623
// 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.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class LibraryExternalSystemIdEntityImpl : LibraryExternalSystemIdEntity, WorkspaceEntityBase() { companion object { internal val LIBRARY_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, LibraryExternalSystemIdEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( LIBRARY_CONNECTION_ID, ) } @JvmField var _externalSystemId: String? = null override val externalSystemId: String get() = _externalSystemId!! override val library: LibraryEntity get() = snapshot.extractOneToOneParent(LIBRARY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: LibraryExternalSystemIdEntityData?) : ModifiableWorkspaceEntityBase<LibraryExternalSystemIdEntity>(), LibraryExternalSystemIdEntity.Builder { constructor() : this(LibraryExternalSystemIdEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity LibraryExternalSystemIdEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isExternalSystemIdInitialized()) { error("Field LibraryExternalSystemIdEntity#externalSystemId should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(LIBRARY_CONNECTION_ID, this) == null) { error("Field LibraryExternalSystemIdEntity#library should be initialized") } } else { if (this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] == null) { error("Field LibraryExternalSystemIdEntity#library 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 LibraryExternalSystemIdEntity this.entitySource = dataSource.entitySource this.externalSystemId = dataSource.externalSystemId if (parents != null) { this.library = parents.filterIsInstance<LibraryEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var externalSystemId: String get() = getEntityData().externalSystemId set(value) { checkModificationAllowed() getEntityData().externalSystemId = value changedProperty.add("externalSystemId") } override var library: LibraryEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(LIBRARY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity } else { this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneParentOfChild(LIBRARY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] = value } changedProperty.add("library") } override fun getEntityData(): LibraryExternalSystemIdEntityData = result ?: super.getEntityData() as LibraryExternalSystemIdEntityData override fun getEntityClass(): Class<LibraryExternalSystemIdEntity> = LibraryExternalSystemIdEntity::class.java } } class LibraryExternalSystemIdEntityData : WorkspaceEntityData<LibraryExternalSystemIdEntity>() { lateinit var externalSystemId: String fun isExternalSystemIdInitialized(): Boolean = ::externalSystemId.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryExternalSystemIdEntity> { val modifiable = LibraryExternalSystemIdEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): LibraryExternalSystemIdEntity { val entity = LibraryExternalSystemIdEntityImpl() entity._externalSystemId = externalSystemId entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return LibraryExternalSystemIdEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return LibraryExternalSystemIdEntity(externalSystemId, entitySource) { this.library = parents.filterIsInstance<LibraryEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(LibraryEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryExternalSystemIdEntityData if (this.entitySource != other.entitySource) return false if (this.externalSystemId != other.externalSystemId) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryExternalSystemIdEntityData if (this.externalSystemId != other.externalSystemId) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + externalSystemId.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + externalSystemId.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
6f54c9138df0ab5367b26b2146c69b5a
37.035573
169
0.711317
5.731388
false
false
false
false
FlexSeries/FlexLib
src/main/kotlin/me/st28/flexseries/flexlib/command/FlexCommandMap.kt
1
7092
/** * Copyright 2016 Stealth2800 <http://stealthyone.com/> * Copyright 2016 Contributors <https://github.com/FlexSeries> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.st28.flexseries.flexlib.command import me.st28.flexseries.flexlib.logging.LogHelper import me.st28.flexseries.flexlib.plugin.FlexPlugin import org.bukkit.Bukkit import org.bukkit.command.CommandMap import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.util.* import kotlin.reflect.KFunction import kotlin.reflect.declaredMemberFunctions import kotlin.reflect.defaultType /** * Handles command registration for a [FlexPlugin]. */ class FlexCommandMap(val plugin: FlexPlugin) { internal companion object { val bukkit_commandMap: CommandMap //val bukkit_registerMethod: Method init { val pluginManager = Bukkit.getPluginManager() val commandMap = pluginManager.javaClass.getDeclaredField("commandMap") commandMap.isAccessible = true bukkit_commandMap = commandMap.get(pluginManager) as CommandMap //bukkit_registerMethod = bukkit_commandMap.javaClass.getDeclaredMethod("register", String::class.java, Command::class.java) } /** * Registers a FlexCommand's Bukkit command with Bukkit's plugin manager via reflection. */ private fun registerBukkitCommand(plugin: FlexPlugin, command: FlexCommand) { try { //bukkit_registerMethod.invoke(bukkit_commandMap, plugin.name.toLowerCase(), command.bukkitCommand) bukkit_commandMap.register(plugin.name.toLowerCase(), command.bukkitCommand) } catch (ex: Exception) { LogHelper.severe(plugin, "An exception occurred while registering command with Bukkit", ex) } } } /** * Registers an object containing methods annotated with [CommandHandler] that represent * command handlers. */ fun register(obj: Any) { val commandModule = FlexPlugin.getGlobalModule(CommandModule::class)!! outer@ for (f in obj.javaClass.kotlin.declaredMemberFunctions) { val meta: CommandHandler = f.annotations.find { it is CommandHandler } as CommandHandler? ?: continue // Parameter 0 of the function is the instance of the class (object in this case) // 1) Determine if function is player only based on the first parameter. // 2) Determine if function is player only based on the first parameter. Otherwise, it // must be a CommandSender. val playerOnly: Boolean = when (f.parameters[1].type) { Player::class.defaultType -> true CommandSender::class.defaultType -> false else -> { LogHelper.severe(plugin, "Invalid command handler '${f.name}': first parameter is not a CommandSender or Player") continue@outer } } // 3) Get base command (or create and register it if it doesn't exist) val commandPath: Stack<String> = Stack() commandPath.addAll(meta.command.split(" ").reversed()) if (commandPath.peek() == "%") { LogHelper.severe(plugin, "Base command can not have reversed arguments") continue@outer } val baseLabel = commandPath.pop() var base = commandModule.getBaseCommand(plugin.javaClass.kotlin, baseLabel) if (base == null) { // Base doesn't exist, create and register it with the command module. base = FlexCommand(plugin, baseLabel) commandModule.registerCommand(base) registerBukkitCommand(plugin, base) } // 2) Iterate through labels until subcommand is found (creating along the way) var subcmd: BasicCommand = base var offset = 0 while (commandPath.isNotEmpty()) { val curLabel = commandPath.pop() // Check for reverse subcommands if (curLabel == "%") { // Find offset while (commandPath.peek() == "%") { ++offset commandPath.pop() } val newLabel = commandPath.pop() // Look for reverse subcommand var temp: BasicCommand? = null for (entry in subcmd.reverseSubcommands) { if (entry.first == offset && entry.second == newLabel) { // Found existing //subcmd = entry.third temp = entry.third break } } if (temp == null) { // Command not found, create it temp = BasicCommand(plugin, newLabel) subcmd.reverseSubcommands.add(Triple(offset, newLabel, BasicCommand(plugin, newLabel))) } subcmd = temp continue } /* No reverse subcommand, look for normal subcommands */ offset = 0 var temp: BasicCommand? = subcmd.subcommands[curLabel] if (temp == null) { // Subcommand doesn't exist, create it now temp = BasicCommand(plugin, curLabel) subcmd.registerSubcommand(temp) } subcmd = temp } // 3) Set command executor //subcmd.setMeta(meta, playerOnly, obj, f as KFunction<Any>) subcmd.executors.add(CommandExecutor(meta, playerOnly, subcmd, obj, f as KFunction<Any>, offset)) // 4) Set default if (meta.isDefault) { subcmd.parent?.defaultSubcommand = subcmd.label } } } fun getCommand(path: String): BasicCommand? { val split = ("${plugin.name.toLowerCase()}:$path").split(" ") var found: BasicCommand = (bukkit_commandMap.getCommand(split[0]) as? FlexCommand.WrappedBukkitCommand)?.flexCommand ?: return null for ((index, name) in split.withIndex()) { if (index == 0) { continue } found = found.subcommands[name] ?: return null } return found } }
apache-2.0
7188b253ced93d88a1e2388edc269598
38.4
136
0.579244
5.199413
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/safeCall/changeThisSafeCallWithValue3Runtime.kt
9
403
// "Replace with 'c1.newFun(this, c2)'" "true" // WITH_STDLIB class X { @Deprecated("", ReplaceWith("c1.newFun(this, c2)")) fun oldFun(c1: Char, c2: Char): Char = c1.newFun(this, c2) val c: Char = 'a' } fun Char.newFun(x: X, c: Char): Char = this fun foo(s: String, x: X) { val chars = s.filter { O.x?.<caret>oldFun(it, x.c) != 'a' } } object O { var x: X? = null }
apache-2.0
72d77116407e6235f63373d62ca83b53
18.190476
62
0.545906
2.51875
false
false
false
false
walleth/kethereum
erc681/src/main/kotlin/org/kethereum/erc681/ERC681Detector.kt
1
277
package org.kethereum.erc681 import org.kethereum.erc831.ERC831 import org.kethereum.erc831.toERC831 import org.kethereum.model.EthereumURI fun ERC831.isERC681() = scheme == "ethereum" && (prefix == null || prefix == "pay") fun EthereumURI.isERC681() = toERC831().isERC681()
mit
099e5f8cb4c6041e5bd906f6ee87a4bc
33.625
83
0.754513
3.183908
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/data/timer/retrofit/TimerConverterFactory.kt
1
1493
package org.dvbviewer.controller.data.timer.retrofit import com.google.gson.reflect.TypeToken import okhttp3.RequestBody import okhttp3.ResponseBody import org.dvbviewer.controller.data.entities.Timer import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type /** * A [converter][Converter.Factory] for the ffmpegprefs.ini files. * * * This converter only applies for class FFMpegPresetList. * */ class TimerConverterFactory private constructor() : Converter.Factory() { private val timerList: Type init { val typeToken = TypeToken.getParameterized(List::class.java, Timer::class.java) timerList = typeToken.type } override fun responseBodyConverter(type: Type, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, List<Timer>>? { return if (type == timerList) { TimerPresetResponseBodyConverter() } else null } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>?, methodAnnotations: Array<Annotation>?, retrofit: Retrofit?): Converter<List<Timer>, RequestBody>? { return if (type == timerList) { TimerRequestBodyConverter() } else null } companion object { /** Create an instance conversion. */ fun create(): TimerConverterFactory { return TimerConverterFactory() } } }
apache-2.0
c1f74d02d93dfbf91cd97c58ab04b35a
28.88
179
0.666443
4.895082
false
false
false
false
ktorio/ktor
buildSrc/src/main/kotlin/test/server/ServerUtils.kt
1
1560
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package test.server import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* fun makeArray(size: Int): ByteArray = ByteArray(size) { it.toByte() } fun makeString(size: Int): String = CharArray(size) { it.toChar() }.concatToString().encodeBase64().take(size) fun List<PartData>.makeString(): String = buildString { val list = this@makeString list.forEach { append("${it.name!!}\n") val content = when (it) { is PartData.FileItem -> filenameContentTypeAndContentString(it.provider, it.headers) is PartData.FormItem -> it.value is PartData.BinaryItem -> filenameContentTypeAndContentString(it.provider, it.headers) is PartData.BinaryChannelItem -> error("Not implemented") } append(content) } } private fun filenameContentTypeAndContentString(provider: () -> Input, headers: Headers): String { val dispositionHeader: String = headers.getAll(HttpHeaders.ContentDisposition)!!.joinToString(";") val disposition: ContentDisposition = ContentDisposition.parse(dispositionHeader) val filename: String = disposition.parameter("filename") ?: "" val contentType = headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } ?: "" val content: String = provider().readText(Charsets.ISO_8859_1) return "$filename$contentType$content" }
apache-2.0
7d8116a68d70a1ba6b49daff775804c1
39
119
0.703205
4.08377
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/provider/GHPRStateDataProviderImpl.kt
10
4749
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.provider import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt import com.intellij.openapi.Disposable import com.intellij.openapi.progress.ProgressIndicator import com.intellij.util.messages.MessageBus import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityState import org.jetbrains.plugins.github.pullrequest.data.service.GHPRStateService import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue import java.util.concurrent.CompletableFuture class GHPRStateDataProviderImpl(private val stateService: GHPRStateService, private val pullRequestId: GHPRIdentifier, private val messageBus: MessageBus, private val detailsData: GHPRDetailsDataProvider) : GHPRStateDataProvider, Disposable { private var lastKnownBaseBranch: String? = null private var lastKnownBaseSha: String? = null private var lastKnownHeadSha: String? = null init { detailsData.addDetailsLoadedListener(this) { val details = detailsData.loadedDetails ?: return@addDetailsLoadedListener if (lastKnownBaseBranch != null && lastKnownBaseBranch != details.baseRefName) { baseBranchProtectionRulesRequestValue.drop() reloadMergeabilityState() } lastKnownBaseBranch = details.baseRefName if (lastKnownBaseSha != null && lastKnownBaseSha != details.baseRefOid && lastKnownHeadSha != null && lastKnownHeadSha != details.headRefOid) { reloadMergeabilityState() } lastKnownBaseSha = details.baseRefOid lastKnownHeadSha = details.headRefOid } } private val baseBranchProtectionRulesRequestValue = LazyCancellableBackgroundProcessValue.create { indicator -> detailsData.loadDetails().thenCompose { stateService.loadBranchProtectionRules(indicator, pullRequestId, it.baseRefName) } } private val mergeabilityStateRequestValue = LazyCancellableBackgroundProcessValue.create { indicator -> val baseBranchProtectionRulesRequest = baseBranchProtectionRulesRequestValue.value detailsData.loadDetails().thenCompose { details -> baseBranchProtectionRulesRequest.thenCompose { stateService.loadMergeabilityState(indicator, pullRequestId, details.headRefOid, details.url, it) } } } override fun loadMergeabilityState(): CompletableFuture<GHPRMergeabilityState> = mergeabilityStateRequestValue.value override fun reloadMergeabilityState() { if (baseBranchProtectionRulesRequestValue.lastLoadedValue == null) baseBranchProtectionRulesRequestValue.drop() mergeabilityStateRequestValue.drop() } override fun addMergeabilityStateListener(disposable: Disposable, listener: () -> Unit) = mergeabilityStateRequestValue.addDropEventListener(disposable, listener) override fun close(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.close(progressIndicator, pullRequestId).notifyState() override fun reopen(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.reopen(progressIndicator, pullRequestId).notifyState() override fun markReadyForReview(progressIndicator: ProgressIndicator): CompletableFuture<Unit> = stateService.markReadyForReview(progressIndicator, pullRequestId).notifyState().completionOnEdt { mergeabilityStateRequestValue.drop() } override fun merge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String) : CompletableFuture<Unit> = stateService.merge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState() override fun rebaseMerge(progressIndicator: ProgressIndicator, currentHeadRef: String): CompletableFuture<Unit> = stateService.rebaseMerge(progressIndicator, pullRequestId, currentHeadRef).notifyState() override fun squashMerge(progressIndicator: ProgressIndicator, commitMessage: Pair<String, String>, currentHeadRef: String) : CompletableFuture<Unit> = stateService.squashMerge(progressIndicator, pullRequestId, commitMessage, currentHeadRef).notifyState() private fun <T> CompletableFuture<T>.notifyState(): CompletableFuture<T> = completionOnEdt { detailsData.reloadDetails() messageBus.syncPublisher(GHPRDataOperationsListener.TOPIC).onStateChanged() } override fun dispose() { mergeabilityStateRequestValue.drop() baseBranchProtectionRulesRequestValue.drop() } }
apache-2.0
758bb8d487c3050bea3e7eea88320aa8
46.5
140
0.782691
5.714801
false
false
false
false
TechzoneMC/SonarPet
api/src/main/kotlin/net/techcable/sonarpet/nms/obfuscation.kt
1
1515
package net.techcable.sonarpet.nms import net.techcable.sonarpet.utils.NmsVersion import org.objectweb.asm.Type // Method names val NmsVersion.livingUpdateMethod: String get() = getObfuscatedMethod("LIVING_UPDATE_METHOD") val NmsVersion.entityTickMethodName get() = getObfuscatedMethod("ENTITY_TICK_METHOD") val NmsVersion.entityMoveMethodName get() = getObfuscatedMethod("ENTITY_MOVE_METHOD") val NmsVersion.onStepMethodName get() = getObfuscatedMethod("ON_STEP_METHOD") val NmsVersion.onInteractMethodName get() = getObfuscatedMethod("ON_INTERACT_METHOD") val NmsVersion.proceduralAIMethodName get() = getObfuscatedMethod("ENTITY_PROCEDURAL_AI_METHOD") val NmsVersion.rabbitSetMovementSpeed get() = getObfuscatedMethod("RABBIT_SET_MOVEMENT_SPEED") // Field names val NmsVersion.sidewaysMotionField get() = getObfuscatedField("ENTITY_SIDEWAYS_MOTION_FIELD") val NmsVersion.forwardMotionField get() = getObfuscatedField("ENTITY_FORWARD_MOTION_FIELD") val NmsVersion.upwardsMotionField: String? get() = tryGetObfuscatedField("ENTITY_UPWARDS_MOTION_FIELD") // Other /** * Before 1.12, the entity move method accepted two floats for both sideways and forwards direction. * After 1.12, it also accepts an additional float for up/down movement, giving it three paramteers in total. */ val NmsVersion.entityMoveMethodParameters: Array<Type> get() { val amount = if (this >= NmsVersion.v1_12_R1) 3 else 2 return Array(amount) { Type.FLOAT_TYPE } }
gpl-3.0
c1eeeafad33fe7cdb390c0e0e6cb3dee
35.071429
109
0.763696
4.04
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersFragment.kt
1
15643
package eu.kanade.tachiyomi.ui.manga.chapter import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Intent import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.view.ActionMode import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.view.* import com.afollestad.materialdialogs.MaterialDialog import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment import eu.kanade.tachiyomi.ui.manga.MangaActivity import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.util.getCoordinates import eu.kanade.tachiyomi.util.toast import eu.kanade.tachiyomi.widget.DeletingChaptersDialog import kotlinx.android.synthetic.main.fragment_manga_chapters.* import nucleus.factory.RequiresPresenter import timber.log.Timber @RequiresPresenter(ChaptersPresenter::class) class ChaptersFragment : BaseRxFragment<ChaptersPresenter>(), ActionMode.Callback, FlexibleViewHolder.OnListItemClickListener { companion object { /** * Creates a new instance of this fragment. * * @return a new instance of [ChaptersFragment]. */ fun newInstance(): ChaptersFragment { return ChaptersFragment() } } /** * Adapter containing a list of chapters. */ private lateinit var adapter: ChaptersAdapter /** * Action mode for multiple selection. */ private var actionMode: ActionMode? = null override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_manga_chapters, container, false) } override fun onViewCreated(view: View, savedState: Bundle?) { // Init RecyclerView and adapter adapter = ChaptersAdapter(this) recycler.adapter = adapter recycler.layoutManager = LinearLayoutManager(activity) recycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) recycler.setHasFixedSize(true) swipe_refresh.setOnRefreshListener { fetchChapters() } fab.setOnClickListener { val chapter = presenter.getNextUnreadChapter() if (chapter != null) { // Create animation listener val revealAnimationListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { openChapter(chapter, true) } } // Get coordinates and start animation val coordinates = fab.getCoordinates() if (!reveal_view.showRevealEffect(coordinates.x, coordinates.y, revealAnimationListener)) { openChapter(chapter) } } else { context.toast(R.string.no_next_chapter) } } } override fun onPause() { // Stop recycler's scrolling when onPause is called. If the activity is finishing // the presenter will be destroyed, and it could cause NPE // https://github.com/inorichi/tachiyomi/issues/159 recycler.stopScroll() super.onPause() } override fun onResume() { // Check if animation view is visible if (reveal_view.visibility == View.VISIBLE) { // Show the unReveal effect val coordinates = fab.getCoordinates() reveal_view.hideRevealEffect(coordinates.x, coordinates.y, 1920) } super.onResume() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.chapters, menu) } override fun onPrepareOptionsMenu(menu: Menu) { // Initialize menu items. val menuFilterRead = menu.findItem(R.id.action_filter_read) val menuFilterUnread = menu.findItem(R.id.action_filter_unread) val menuFilterDownloaded = menu.findItem(R.id.action_filter_downloaded) val menuFilterBookmarked = menu.findItem(R.id.action_filter_bookmarked) // Set correct checkbox values. menuFilterRead.isChecked = presenter.onlyRead() menuFilterUnread.isChecked = presenter.onlyUnread() menuFilterDownloaded.isChecked = presenter.onlyDownloaded() menuFilterBookmarked.isChecked = presenter.onlyBookmarked() if (presenter.onlyRead()) //Disable unread filter option if read filter is enabled. menuFilterUnread.isEnabled = false if (presenter.onlyUnread()) //Disable read filter option if unread filter is enabled. menuFilterRead.isEnabled = false } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_display_mode -> showDisplayModeDialog() R.id.manga_download -> showDownloadDialog() R.id.action_sorting_mode -> showSortingDialog() R.id.action_filter_unread -> { item.isChecked = !item.isChecked presenter.setUnreadFilter(item.isChecked) activity.supportInvalidateOptionsMenu() } R.id.action_filter_read -> { item.isChecked = !item.isChecked presenter.setReadFilter(item.isChecked) activity.supportInvalidateOptionsMenu() } R.id.action_filter_downloaded -> { item.isChecked = !item.isChecked presenter.setDownloadedFilter(item.isChecked) } R.id.action_filter_bookmarked -> { item.isChecked = !item.isChecked presenter.setBookmarkedFilter(item.isChecked) } R.id.action_filter_empty -> { presenter.removeFilters() activity.supportInvalidateOptionsMenu() } R.id.action_sort -> presenter.revertSortOrder() else -> return super.onOptionsItemSelected(item) } return true } fun onNextManga(manga: Manga) { // Set initial values activity.supportInvalidateOptionsMenu() } fun onNextChapters(chapters: List<ChapterModel>) { // If the list is empty, fetch chapters from source if the conditions are met // We use presenter chapters instead because they are always unfiltered if (presenter.chapters.isEmpty()) initialFetchChapters() destroyActionModeIfNeeded() adapter.setItems(chapters) } private fun initialFetchChapters() { // Only fetch if this view is from the catalog and it hasn't requested previously if (isCatalogueManga && !presenter.hasRequested) { fetchChapters() } } fun fetchChapters() { swipe_refresh.isRefreshing = true presenter.fetchChaptersFromSource() } fun onFetchChaptersDone() { swipe_refresh.isRefreshing = false } fun onFetchChaptersError(error: Throwable) { swipe_refresh.isRefreshing = false context.toast(error.message) } val isCatalogueManga: Boolean get() = (activity as MangaActivity).fromCatalogue fun openChapter(chapter: Chapter, hasAnimation: Boolean = false) { val intent = ReaderActivity.newIntent(activity, presenter.manga, chapter) if (hasAnimation) { intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) } startActivity(intent) } private fun showDisplayModeDialog() { // Get available modes, ids and the selected mode val modes = intArrayOf(R.string.show_title, R.string.show_chapter_number) val ids = intArrayOf(Manga.DISPLAY_NAME, Manga.DISPLAY_NUMBER) val selectedIndex = if (presenter.manga.displayMode == Manga.DISPLAY_NAME) 0 else 1 MaterialDialog.Builder(activity) .title(R.string.action_display_mode) .items(modes.map { getString(it) }) .itemsIds(ids) .itemsCallbackSingleChoice(selectedIndex) { dialog, itemView, which, text -> // Save the new display mode presenter.setDisplayMode(itemView.id) // Refresh ui adapter.notifyItemRangeChanged(0, adapter.itemCount) true } .show() } private fun showSortingDialog() { // Get available modes, ids and the selected mode val modes = intArrayOf(R.string.sort_by_source, R.string.sort_by_number) val ids = intArrayOf(Manga.SORTING_SOURCE, Manga.SORTING_NUMBER) val selectedIndex = if (presenter.manga.sorting == Manga.SORTING_SOURCE) 0 else 1 MaterialDialog.Builder(activity) .title(R.string.sorting_mode) .items(modes.map { getString(it) }) .itemsIds(ids) .itemsCallbackSingleChoice(selectedIndex) { dialog, itemView, which, text -> // Save the new sorting mode presenter.setSorting(itemView.id) true } .show() } private fun showDownloadDialog() { // Get available modes val modes = intArrayOf(R.string.download_1, R.string.download_5, R.string.download_10, R.string.download_unread, R.string.download_all) MaterialDialog.Builder(activity) .title(R.string.manga_download) .negativeText(android.R.string.cancel) .items(modes.map { getString(it) }) .itemsCallback { dialog, view, i, charSequence -> fun getUnreadChaptersSorted() = presenter.chapters .filter { !it.read && !it.isDownloaded } .distinctBy { it.name } .sortedByDescending { it.source_order } // i = 0: Download 1 // i = 1: Download 5 // i = 2: Download 10 // i = 3: Download unread // i = 4: Download all val chaptersToDownload = when (i) { 0 -> getUnreadChaptersSorted().take(1) 1 -> getUnreadChaptersSorted().take(5) 2 -> getUnreadChaptersSorted().take(10) 3 -> presenter.chapters.filter { !it.read } 4 -> presenter.chapters else -> emptyList() } if (chaptersToDownload.isNotEmpty()) { downloadChapters(chaptersToDownload) } } .show() } fun onChapterStatusChange(download: Download) { getHolder(download.chapter)?.notifyStatus(download.status) } private fun getHolder(chapter: Chapter): ChaptersHolder? { return recycler.findViewHolderForItemId(chapter.id!!) as? ChaptersHolder } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.chapter_selection, menu) adapter.mode = FlexibleAdapter.MODE_MULTI return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.action_select_all -> selectAll() R.id.action_mark_as_read -> markAsRead(getSelectedChapters()) R.id.action_mark_as_unread -> markAsUnread(getSelectedChapters()) R.id.action_download -> downloadChapters(getSelectedChapters()) R.id.action_delete -> { MaterialDialog.Builder(activity) .content(R.string.confirm_delete_chapters) .positiveText(android.R.string.yes) .negativeText(android.R.string.no) .onPositive { dialog, action -> deleteChapters(getSelectedChapters()) } .show() } else -> return false } return true } override fun onDestroyActionMode(mode: ActionMode) { adapter.mode = FlexibleAdapter.MODE_SINGLE adapter.clearSelection() actionMode = null } fun getSelectedChapters(): List<ChapterModel> { return adapter.selectedItems.map { adapter.getItem(it) } } fun destroyActionModeIfNeeded() { actionMode?.finish() } fun selectAll() { adapter.selectAll() setContextTitle(adapter.selectedItemCount) } fun markAsRead(chapters: List<ChapterModel>) { presenter.markChaptersRead(chapters, true) if (presenter.preferences.removeAfterMarkedAsRead()) { deleteChapters(chapters) } } fun markAsUnread(chapters: List<ChapterModel>) { presenter.markChaptersRead(chapters, false) } fun markPreviousAsRead(chapter: ChapterModel) { presenter.markPreviousChaptersAsRead(chapter) } fun downloadChapters(chapters: List<ChapterModel>) { destroyActionModeIfNeeded() presenter.downloadChapters(chapters) } fun bookmarkChapters(chapters: List<ChapterModel>, bookmarked: Boolean) { destroyActionModeIfNeeded() presenter.bookmarkChapters(chapters,bookmarked) } fun deleteChapters(chapters: List<ChapterModel>) { destroyActionModeIfNeeded() DeletingChaptersDialog().show(childFragmentManager, DeletingChaptersDialog.TAG) presenter.deleteChapters(chapters) } fun onChaptersDeleted() { dismissDeletingDialog() adapter.notifyItemRangeChanged(0, adapter.itemCount) } fun onChaptersDeletedError(error: Throwable) { dismissDeletingDialog() Timber.e(error) } fun dismissDeletingDialog() { (childFragmentManager.findFragmentByTag(DeletingChaptersDialog.TAG) as? DialogFragment)?.dismiss() } override fun onListItemClick(position: Int): Boolean { val item = adapter.getItem(position) ?: return false if (actionMode != null && adapter.mode == FlexibleAdapter.MODE_MULTI) { toggleSelection(position) return true } else { openChapter(item) return false } } override fun onListItemLongClick(position: Int) { if (actionMode == null) actionMode = activity.startSupportActionMode(this) toggleSelection(position) } private fun toggleSelection(position: Int) { adapter.toggleSelection(position, false) val count = adapter.selectedItemCount if (count == 0) { actionMode?.finish() } else { setContextTitle(count) actionMode?.invalidate() } } private fun setContextTitle(count: Int) { actionMode?.title = getString(R.string.label_selected, count) } }
apache-2.0
a423689189886fdc6d3c94920f19e462
35.463869
127
0.622323
5.078896
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Node.kt
1
1904
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Instruction2 class Node : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.instanceFields.size == 3 } .and { it.instanceFields.count { it.type == LONG_TYPE } == 1 } .and { it.superType == Any::class.type } .and { c -> c.instanceFields.count { it.type == c.type } == 2 } class key : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == LONG_TYPE } } @DependsOn(next::class) class previous : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<Node>() } .and { it != field<next>() } } @DependsOn(hasNext::class) class next : UniqueMapper.InMethod.Field(hasNext::class) { override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.GETFIELD } } @MethodParameters() class hasNext : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } @MethodParameters() class remove : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } } }
mit
a795d64ae8f7b31acec161f23188a9b0
39.531915
92
0.71166
4.112311
false
false
false
false
google/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinNonSourceRootIndexFilter.kt
3
1499
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.stubindex import com.intellij.find.ngrams.TrigramIndex import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.FilenameIndex import com.intellij.util.indexing.GlobalIndexFilter import com.intellij.util.indexing.IndexId import org.jetbrains.kotlin.idea.KotlinFileType class KotlinNonSourceRootIndexFilter: GlobalIndexFilter { private val enabled = !System.getProperty("kotlin.index.non.source.roots", "true").toBoolean() override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>): Boolean = false override fun isExcludedFromIndex(virtualFile: VirtualFile, indexId: IndexId<*, *>, project: Project?): Boolean = project != null && affectsIndex(indexId) && virtualFile.extension == KotlinFileType.EXTENSION && ProjectRootManager.getInstance(project).fileIndex.getOrderEntriesForFile(virtualFile).isEmpty() && !ProjectFileIndex.getInstance(project).isInLibrary(virtualFile) override fun getVersion(): Int = 0 override fun affectsIndex(indexId: IndexId<*, *>): Boolean = enabled && (indexId !== TrigramIndex.INDEX_ID && indexId !== FilenameIndex.NAME) }
apache-2.0
13e00d4c8d10bab1c5927deca7d1ba3c
49
120
0.753836
4.743671
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/popup/list/PopupInlineActionsSupport.kt
1
1843
// 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.ui.popup.list import com.intellij.openapi.util.NlsActions.ActionText import com.intellij.ui.ExperimentalUI import com.intellij.ui.popup.ActionPopupStep import java.awt.Point import java.awt.event.InputEvent import javax.swing.JComponent import javax.swing.JList private val Empty = object : PopupInlineActionsSupport { override fun calcExtraButtonsCount(element: Any?): Int = 0 override fun calcButtonIndex(element: Any?, point: Point): Int? = null override fun getInlineAction(element: Any?, index: Int, event: InputEvent?) = InlineActionDescriptor({}, false) override fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> = emptyList() override fun getActiveButtonIndex(list: JList<*>): Int? = null override fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? = null } internal interface PopupInlineActionsSupport { fun hasExtraButtons(element: Any?): Boolean = calcExtraButtonsCount(element) > 0 fun calcExtraButtonsCount(element: Any?): Int fun calcButtonIndex(element: Any?, point: Point): Int? fun getInlineAction(element: Any?, index: Int, event: InputEvent? = null) : InlineActionDescriptor fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> @ActionText fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? fun getActiveButtonIndex(list: JList<*>): Int? companion object { fun create(popup: ListPopupImpl): PopupInlineActionsSupport { if (!ExperimentalUI.isNewUI()) return Empty if (popup.listStep is ActionPopupStep) return PopupInlineActionsSupportImpl(popup) return NonActionsPopupInlineSupport(popup) } } }
apache-2.0
5867935eec185fd8efd244b6fdf99e6d
39.977778
120
0.762887
4.367299
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/helpers/PicassoRoundedCornersTransformation.kt
2
1154
package com.simplemobiletools.gallery.pro.helpers import android.graphics.* import com.squareup.picasso.Transformation // taken from https://stackoverflow.com/a/35241525/1967672 class PicassoRoundedCornersTransformation(private val radius: Float) : Transformation { override fun transform(source: Bitmap): Bitmap { val size = Math.min(source.width, source.height) val x = (source.width - size) / 2 val y = (source.height - size) / 2 val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size) if (squaredBitmap != source) { source.recycle() } val bitmap = Bitmap.createBitmap(size, size, source.config) val canvas = Canvas(bitmap) val paint = Paint() val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true val rect = RectF(0f, 0f, source.width.toFloat(), source.height.toFloat()) canvas.drawRoundRect(rect, radius, radius, paint) squaredBitmap.recycle() return bitmap } override fun key() = "rounded_corners" }
gpl-3.0
c201cf59c7527af8135f049715be910d
35.0625
94
0.664645
4.211679
false
false
false
false
JetBrains/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaReferencesCodeVisionProvider.kt
1
1490
// 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 com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering import com.intellij.codeInsight.hints.codeVision.ReferencesCodeVisionProvider import com.intellij.java.JavaBundle import com.intellij.lang.java.JavaLanguage import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiMember import com.intellij.psi.PsiTypeParameter class JavaReferencesCodeVisionProvider : ReferencesCodeVisionProvider() { companion object{ const val ID = "java.references" } override fun acceptsFile(file: PsiFile): Boolean = file.language == JavaLanguage.INSTANCE override fun acceptsElement(element: PsiElement): Boolean = element is PsiMember && element !is PsiTypeParameter override fun getHint(element: PsiElement, file: PsiFile): String? = JavaTelescope.usagesHint(element as PsiMember, file) override fun logClickToFUS(element: PsiElement, hint: String) { JavaCodeVisionUsageCollector.USAGES_CLICKED_EVENT_ID.log(element.project) } override val name: String get() = JavaBundle.message("settings.inlay.java.usages") override val relativeOrderings: List<CodeVisionRelativeOrdering> get() = listOf(CodeVisionRelativeOrdering.CodeVisionRelativeOrderingBefore("java.inheritors")) override val id: String get() = ID }
apache-2.0
3fa880f050cb0b6c4c3e915a82b64e2e
42.852941
158
0.802013
4.613003
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.kt
7
2066
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsRoot import com.intellij.vcsUtil.VcsUtil internal class DirtBuilder { private val scopesByVcs: MutableMap<AbstractVcs, VcsDirtyScopeImpl> = mutableMapOf() var isEverythingDirty: Boolean = false private set fun markEverythingDirty() { isEverythingDirty = true scopesByVcs.clear() } fun addDirtyFiles(vcsRoot: VcsRoot, files: Collection<FilePath>, dirs: Collection<FilePath>): Boolean { if (isEverythingDirty) return true val vcs = vcsRoot.vcs val root = vcsRoot.path if (vcs != null) { val scope = scopesByVcs.computeIfAbsent(vcs) { VcsDirtyScopeImpl(it, isEverythingDirty) } for (filePath in files) { scope.addDirtyPathFast(root, filePath, false) } for (filePath in dirs) { scope.addDirtyPathFast(root, filePath, true) } } return scopesByVcs.isNotEmpty() } fun buildScopes(project: Project): List<VcsDirtyScopeImpl> { val scopes: Collection<VcsDirtyScopeImpl> if (isEverythingDirty) { val allScopes = mutableMapOf<AbstractVcs, VcsDirtyScopeImpl>() for (root in ProjectLevelVcsManager.getInstance(project).allVcsRoots) { val vcs = root.vcs val path = root.path if (vcs != null) { val scope = allScopes.computeIfAbsent(vcs) { VcsDirtyScopeImpl(it, isEverythingDirty) } scope.addDirtyPathFast(path, VcsUtil.getFilePath(path), true) } } scopes = allScopes.values } else { scopes = scopesByVcs.values } return scopes.map { it.pack() } } fun isFileDirty(filePath: FilePath): Boolean = isEverythingDirty || scopesByVcs.values.any { it.belongsTo(filePath) } }
apache-2.0
321cf209422e2d86f087a7941c6a9797
33.45
140
0.7091
4.41453
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/remote/DeferredRemoteProcess.kt
1
4732
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.remote import com.google.common.net.HostAndPort import com.intellij.openapi.diagnostic.logger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.isPending import java.io.InputStream import java.io.OutputStream import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import kotlin.math.max import kotlin.system.measureNanoTime /** * Asynchronous adapter for synchronous process callers. Intended for usage in cases when blocking calls like [ProcessBuilder.start] * are called in EDT and it's uneasy to refactor. Anyway, better to not call blocking methods in EDT rather than use this class. */ class DeferredRemoteProcess(private val promise: Promise<RemoteProcess>) : RemoteProcess() { override fun getOutputStream(): OutputStream = DeferredOutputStream() override fun getInputStream(): InputStream = DeferredInputStream { it.inputStream } override fun getErrorStream(): InputStream = DeferredInputStream { it.errorStream } override fun waitFor(): Int = get().waitFor() override fun waitFor(timeout: Long, unit: TimeUnit): Boolean { val process: RemoteProcess? val nanosSpent = measureNanoTime { process = promise.blockingGet(timeout.toInt(), unit) } val restTimeoutNanos = max(0, TimeUnit.NANOSECONDS.convert(timeout, unit) - nanosSpent) return process?.waitFor(restTimeoutNanos, TimeUnit.NANOSECONDS) ?: false } override fun exitValue(): Int = tryGet()?.exitValue() ?: throw IllegalStateException("Process is not terminated") override fun destroy() { runNowOrSchedule { it.destroy() } } override fun killProcessTree(): Boolean = runNowOrSchedule { it.killProcessTree() } ?: false override fun isDisconnected(): Boolean = tryGet()?.isDisconnected ?: false override fun getLocalTunnel(remotePort: Int): HostAndPort? = get().getLocalTunnel(remotePort) override fun destroyForcibly(): Process = runNowOrSchedule { it.destroyForcibly() } ?: this override fun supportsNormalTermination(): Boolean = true override fun isAlive(): Boolean = tryGet()?.isAlive ?: true override fun onExit(): CompletableFuture<Process> = CompletableFuture<Process>().also { promise.then(it::complete) } private fun get(): RemoteProcess = promise.blockingGet(Int.MAX_VALUE)!! private fun tryGet(): RemoteProcess? = promise.takeUnless { it.isPending }?.blockingGet(0) private fun <T> runNowOrSchedule(handler: (RemoteProcess) -> T): T? { val process = tryGet() return if (process != null) { handler(process) } else { val cause = Throwable("Initially called from this context.") promise.then { try { it?.let(handler) } catch (err: Throwable) { err.addSuppressed(cause) LOG.info("$this: Got an error that nothing could catch: ${err.message}", err) } } null } } private inner class DeferredOutputStream : OutputStream() { override fun close() { runNowOrSchedule { it.outputStream.close() } } override fun flush() { tryGet()?.outputStream?.flush() } override fun write(b: Int) { get().outputStream.write(b) } override fun write(b: ByteArray) { get().outputStream.write(b) } override fun write(b: ByteArray, off: Int, len: Int) { get().outputStream.write(b, off, len) } } private inner class DeferredInputStream(private val streamGetter: (RemoteProcess) -> InputStream) : InputStream() { override fun close() { runNowOrSchedule { streamGetter(it).close() } } override fun read(): Int = streamGetter(get()).read() override fun read(b: ByteArray): Int = streamGetter(get()).read(b) override fun read(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).read(b, off, len) override fun readAllBytes(): ByteArray = streamGetter(get()).readAllBytes() override fun readNBytes(len: Int): ByteArray = streamGetter(get()).readNBytes(len) override fun readNBytes(b: ByteArray, off: Int, len: Int): Int = streamGetter(get()).readNBytes(b, off, len) override fun skip(n: Long): Long = streamGetter(get()).skip(n) override fun available(): Int = tryGet()?.let(streamGetter)?.available() ?: 0 override fun markSupported(): Boolean = false } private companion object { private val LOG = logger<DeferredRemoteProcess>() } }
apache-2.0
e379065bf78b584336e3b54527c590af
27.341317
140
0.67519
4.580833
false
false
false
false
scenerygraphics/scenery
src/main/kotlin/graphics/scenery/volumes/SceneryContext.kt
1
25995
package graphics.scenery.volumes import graphics.scenery.textures.Texture import graphics.scenery.textures.Texture.BorderColor import graphics.scenery.textures.UpdatableTexture.TextureExtents import graphics.scenery.textures.Texture.RepeatMode import graphics.scenery.textures.UpdatableTexture.TextureUpdate import graphics.scenery.backends.ShaderType import graphics.scenery.textures.UpdatableTexture import graphics.scenery.utils.LazyLogger import net.imglib2.type.numeric.NumericType import net.imglib2.type.numeric.integer.UnsignedByteType import net.imglib2.type.numeric.integer.UnsignedShortType import net.imglib2.type.numeric.real.FloatType import org.joml.* import org.lwjgl.system.MemoryUtil import tpietzsch.backend.* import tpietzsch.cache.TextureCache import tpietzsch.example2.LookupTextureARGB import tpietzsch.shadergen.Shader import java.nio.Buffer import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer import java.util.concurrent.ConcurrentHashMap import kotlin.time.ExperimentalTime import tpietzsch.backend.Texture as BVVTexture /** * Context class for interaction with BigDataViewer-generated shaders. * * @author Ulrik Günther <[email protected]> * @author Tobias Pietzsch <[email protected]> */ open class SceneryContext(val node: VolumeManager, val useCompute: Boolean = false) : GpuContext { private val logger by LazyLogger() data class BindingState(var binding: Int, var uniformName: String?, var reallocate: Boolean = false) private val pboBackingStore = HashMap<StagingBuffer, ByteBuffer>() /** Factory for the autogenerated shaders. */ val factory = VolumeShaderFactory(useCompute) /** Reference to the currently bound texture cache. */ protected var currentlyBoundCache: Texture? = null /** Hashmap for references to the currently bound LUTs/texture atlases. */ protected var currentlyBoundTextures = ConcurrentHashMap<String, Texture>() /** Hashmap for storing associations between [Texture] objects, texture slots and uniform names. */ protected var bindings = ConcurrentHashMap<BVVTexture, BindingState>() /** Storage for deferred bindings, where the association between uniform and texture unit is not known upfront. */ protected var deferredBindings = ConcurrentHashMap<BVVTexture, (String) -> Unit>() protected var samplerKeys = listOf("volumeCache", "lutSampler", "volume_", "transferFunction_", "colorMap_") val uniformSetter = SceneryUniformSetter() /** * Uniform setter class */ inner class SceneryUniformSetter: SetUniforms { var modified: Boolean = false override fun shouldSet(modified: Boolean): Boolean = modified /** * Sets the uniform with [name] to the Integer [v0]. */ override fun setUniform1i(name: String, v0: Int) { logger.debug("Setting uniform $name to $v0") if(samplerKeys.any { name.startsWith(it) }) { val binding = bindings.entries.find { it.value.binding == v0 } if(binding != null) { bindings[binding.key] = BindingState(v0, name, binding.value.reallocate) } else { logger.warn("Binding for $name slot $v0 not found.") } } else { node.shaderProperties[name] = v0 } modified = true } /** * Sets the uniform with [name] to the Integer 2-vector [v0] and [v1]. */ override fun setUniform2i(name: String, v0: Int, v1: Int) { node.shaderProperties[name] = Vector2i(v0, v1) modified = true } /** * Sets the uniform with [name] to the Integer 3-vector [v0],[v1],[v2]. */ override fun setUniform3i(name: String, v0: Int, v1: Int, v2: Int) { node.shaderProperties[name] = Vector3i(v0, v1, v2) modified = true } /** * Sets the uniform with [name] to the Integer 4-vector [v0],[v1],[v2],[v3]. */ override fun setUniform4i(name: String, v0: Int, v1: Int, v2: Int, v3: Int) { node.shaderProperties[name] = Vector4i(v0, v1, v2, v3) modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] single values. */ override fun setUniform1iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 2-vectors. */ override fun setUniform2iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 3-vectors. * To conform with OpenGL/Vulkan UBO alignment rules, the array given will be padded to a 4-vector by zeroes. */ override fun setUniform3iv(name: String, count: Int, value: IntArray) { // in UBOs, arrays of vectors need to be padded, such that they start on // word boundaries, e.g. a 3-vector needs to start on byte 16. val padded = IntArray(4*count) var j = 0 for(i in 0 until count) { padded[j] = value[3*i] padded[j+1] = value[3*i+1] padded[j+2] = value[3*i+2] padded[j+3] = 0 j += 4 } node.shaderProperties[name] = padded modified = true } /** * Sets the uniform with [name] to the int array given by [value], containing [count] 4-vectors. */ override fun setUniform4iv(name: String, count: Int, value: IntArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float [v0]. */ override fun setUniform1f(name: String, v0: Float) { node.shaderProperties[name] = v0 modified = true } /** * Sets the uniform with [name] to the Float 2-vector [v0],[v1]. */ override fun setUniform2f(name: String, v0: Float, v1: Float) { node.shaderProperties[name] = Vector2f(v0, v1) modified = true } /** * Sets the uniform with [name] to the Float 3-vector [v0],[v1],[v2]. */ override fun setUniform3f(name: String, v0: Float, v1: Float, v2: Float) { node.shaderProperties[name] = Vector3f(v0, v1, v2) modified = true } /** * Sets the uniform with [name] to the Float 4-vector [v0],[v1],[v2],[v3]. */ override fun setUniform4f(name: String, v0: Float, v1: Float, v2: Float, v3: Float) { node.shaderProperties[name] = Vector4f(v0, v1, v2, v3) modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] single values. */ override fun setUniform1fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 2-vectors. */ override fun setUniform2fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 3-vectors. * To conform with OpenGL/Vulkan UBO alignment rules, the array given will be padded to a 4-vector by zeroes. */ override fun setUniform3fv(name: String, count: Int, value: FloatArray) { // in UBOs, arrays of vectors need to be padded, such that they start on // word boundaries, e.g. a 3-vector needs to start on byte 16. val padded = FloatArray(4*count) var j = 0 for(i in 0 until count) { padded[j] = value[3*i] padded[j+1] = value[3*i+1] padded[j+2] = value[3*i+2] padded[j+3] = 0.0f j += 4 } // value.asSequence().windowed(3, 3).forEach { // padded.addAll(it) // padded.add(0.0f) // } node.shaderProperties[name] = padded modified = true } /** * Sets the uniform with [name] to the Float array given by [value], containing [count] 4-vectors. */ override fun setUniform4fv(name: String, count: Int, value: FloatArray) { node.shaderProperties[name] = value modified = true } /** * Sets the uniform with [name] to the Float 3x3 matrix given in [value]. Set [transpose] if the matrix should * be transposed prior to setting. */ override fun setUniformMatrix3f(name: String, transpose: Boolean, value: FloatBuffer) { val matrix = value.duplicate() if(matrix.position() == matrix.capacity()) { matrix.flip() } val m = Matrix4f(matrix) if(transpose) { m.transpose() } node.shaderProperties[name] = m modified = true } /** * Sets the uniform with [name] to the Float 4x4 matrix given in [value]. Set [transpose] if the matrix should * be transposed prior to setting. */ override fun setUniformMatrix4f(name: String, transpose: Boolean, value: FloatBuffer) { val matrix = value.duplicate() if(matrix.position() == matrix.capacity()) { matrix.flip() } val m = Matrix4f(matrix) if(transpose) { m.transpose() } node.shaderProperties[name] = m modified = true } } var currentShader: Shader? = null /** * Update the shader set with the new [shader] given. */ override fun use(shader: Shader) { if(currentShader == null || currentShader != shader) { if(!useCompute) { factory.updateShaders( hashMapOf( ShaderType.VertexShader to shader, ShaderType.FragmentShader to shader)) } else { factory.updateShaders( hashMapOf(ShaderType.ComputeShader to shader), ) } currentShader = shader } } /** * Returns the uniform setter for [shader]. */ override fun getUniformSetter(shader: Shader): SetUniforms { return uniformSetter } /** * @param pbo StagingBuffer to bind * @return id of previously bound pbo */ override fun bindStagingBuffer(pbo: StagingBuffer): Int { logger.debug("Binding PBO $pbo") return 0 } /** * @param id pbo id to bind * @return id of previously bound pbo */ override fun bindStagingBufferId(id: Int): Int { logger.debug("Binding PBO $id") return id } private fun dimensionsMatch(texture: BVVTexture, current: Texture?): Boolean { if(current == null) { return false } if(texture.texWidth() == current.dimensions.x && texture.texHeight() == current.dimensions.y && texture.texDepth() == current.dimensions.z) { return true } return false } /** * @param texture texture to bind * @return id of previously bound texture */ override fun bindTexture(texture: BVVTexture): Int { logger.debug("Binding $texture and updating GT") val (channels, type: NumericType<*>, normalized) = when(texture.texInternalFormat()) { BVVTexture.InternalFormat.R8 -> Triple(1, UnsignedByteType(), true) BVVTexture.InternalFormat.R16 -> Triple(1, UnsignedShortType(), true) BVVTexture.InternalFormat.RGBA8 -> Triple(4, UnsignedByteType(), true) BVVTexture.InternalFormat.RGBA8UI -> Triple(4, UnsignedByteType(), false) BVVTexture.InternalFormat.R32F -> Triple(1, FloatType(), false) BVVTexture.InternalFormat.UNKNOWN -> TODO() else -> throw UnsupportedOperationException("Unknown internal format ${texture.texInternalFormat()}") } val repeat = when(texture.texWrap()) { BVVTexture.Wrap.CLAMP_TO_BORDER_ZERO -> RepeatMode.ClampToBorder BVVTexture.Wrap.CLAMP_TO_EDGE -> RepeatMode.ClampToEdge BVVTexture.Wrap.REPEAT -> RepeatMode.Repeat else -> throw UnsupportedOperationException("Unknown wrapping mode: ${texture.texWrap()}") } val material = node.material() if (texture is TextureCache) { if(currentlyBoundCache != null && material.textures["volumeCache"] == currentlyBoundCache && dimensionsMatch(texture, material.textures["volumeCache"])) { return 0 } // logger.warn("Binding and updating cache $texture") val gt = UpdatableTexture( Vector3i(texture.texWidth(), texture.texHeight(), texture.texDepth()), channels, type, null, repeat.all(), BorderColor.TransparentBlack, normalized, false, minFilter = Texture.FilteringMode.Linear, maxFilter = Texture.FilteringMode.Linear) material.textures["volumeCache"] = gt currentlyBoundCache = gt } else { val textureName = bindings[texture]?.uniformName logger.debug("lutName is $textureName for $texture") val db = { name: String -> /* if (!(node.material.textures[lut] != null && currentlyBoundLuts[lut] != null && node.material.textures[lut] == currentlyBoundLuts[lut])) { */ if (!(material.textures[name] != null && currentlyBoundTextures[name] != null && material.textures[name] == currentlyBoundTextures[name])) { val contents = when(texture) { is LookupTextureARGB -> null is VolumeManager.SimpleTexture2D -> texture.data else -> null } val filterLinear = when(texture) { is LookupTextureARGB -> Texture.FilteringMode.NearestNeighbour else -> Texture.FilteringMode.Linear } val gt = UpdatableTexture( Vector3i(texture.texWidth(), texture.texHeight(), texture.texDepth()), channels, type, contents, repeat.all(), BorderColor.TransparentBlack, normalized, false, minFilter = filterLinear, maxFilter = filterLinear) material.textures[name] = gt currentlyBoundTextures[name] = gt } } logger.debug("Adding deferred binding for $texture/$textureName") if(textureName == null) { deferredBindings[texture] = db return -1 } else { db.invoke(textureName) } } return 0 } /** * Runs all bindings that have been deferred to a later point. Necessary for some textures * to be compatible with the OpenGL binding model. */ fun runDeferredBindings() { val removals = ArrayList<BVVTexture>(deferredBindings.size) logger.debug("Running deferred bindings, got ${deferredBindings.size}") deferredBindings.forEach { (texture, func) -> val binding = bindings[texture] val samplerName = binding?.uniformName if(binding != null && samplerName != null) { func.invoke(samplerName) removals.add(texture) } else { if(node.readyToRender()) { logger.error("Binding for $texture not found, despite trying deferred binding. (binding=$binding/sampler=$samplerName)") } } } removals.forEach { deferredBindings.remove(it) } // val currentBindings = bindings.values.mapNotNull { it.uniformName } // logger.info("Current bindings are: ${currentBindings.joinToString(",")}") // val missingKeys = node.material.textures.filterKeys { it !in currentBindings } // missingKeys.forEach { (k, _) -> if(k.contains("_x_")) node.material.textures.remove(k) } } @Suppress("unused") fun clearCacheBindings() { val caches = bindings.filter { it is TextureCache } caches.map { bindings.remove(it.key) } currentlyBoundCache = null } fun clearBindings() { currentlyBoundTextures.clear() deferredBindings.clear() bindings.clear() cachedUpdates.clear() } /** * @param texture texture to bind * @param unit texture unit to bind to */ override fun bindTexture(texture: BVVTexture?, unit: Int) { logger.debug("Binding $texture to unit $unit") if(texture != null) { val binding = bindings[texture] if(binding != null) { bindings[texture] = BindingState(unit, binding.uniformName, binding.reallocate) } else { val prev = bindings.filter { it.value.binding == unit }.entries.firstOrNull()?.value val previousName = prev?.uniformName val previousReallocate = prev?.reallocate bindings[texture] = BindingState(unit, previousName) if(previousReallocate != null) { bindings[texture]?.reallocate = previousReallocate } } } } /** * @param id texture id to bind * @param numTexDimensions texture target: 1, 2, or 3 * @return id of previously bound texture */ override fun bindTextureId(id: Int, numTexDimensions: Int): Int { return 0 } /** * Maps a given [pbo] to a native memory-backed [ByteBuffer] and returns it. * The allocated buffers will be cached. */ override fun map(pbo: StagingBuffer): Buffer { logger.debug("Mapping $pbo... (${pboBackingStore.size} total)") return pboBackingStore.computeIfAbsent(pbo) { MemoryUtil.memAlloc(pbo.sizeInBytes) } } /** * Unmaps a buffer given by [pbo]. This function currently has no effect. */ override fun unmap(pbo: StagingBuffer) { logger.debug("Unmapping $pbo...") } /** * Marks a given [texture] for reallocation. */ override fun delete(texture: BVVTexture) { bindings[texture]?.reallocate = true } private data class SubImageUpdate(val xoffset: Int, val yoffset: Int, val zoffset: Int, val width: Int, val height: Int, val depth: Int, val contents: ByteBuffer, val reallocate: Boolean = false, val deallocate: Boolean = false) private var cachedUpdates = ConcurrentHashMap<BVVTexture, MutableList<SubImageUpdate>>() private data class UpdateParameters(val xoffset: Int, val yoffset: Int, val zoffset: Int, val width: Int, val height: Int, val depth: Int, val hash: Long) private val lastUpdates = ConcurrentHashMap<Texture3D, UpdateParameters>() /** * Runs all cached texture updates gathered from [texSubImage3D]. */ fun runTextureUpdates() { cachedUpdates.forEach { (t, updates) -> val texture = bindings[t] val name = texture?.uniformName if(texture != null && name != null) { val material = node.material() val gt = material.textures[name] as? UpdatableTexture ?: throw IllegalStateException("Texture for $name is null or not updateable") logger.debug("Running ${updates.size} texture updates for $texture") updates.forEach { update -> if (texture.reallocate) { val newDimensions = Vector3i(update.width, update.height, update.depth) val dimensionsChanged = Vector3i(newDimensions).sub(gt.dimensions).length() > 0.0001f if(dimensionsChanged) { logger.debug("Reallocating for size change ${gt.dimensions} -> $newDimensions") gt.clearUpdates() gt.dimensions = newDimensions gt.contents = null if (t is LookupTextureARGB) { gt.normalized = false } material.textures[name] = gt } val textureUpdate = TextureUpdate( TextureExtents(update.xoffset, update.yoffset, update.zoffset, update.width, update.height, update.depth), update.contents, deallocate = update.deallocate) gt.addUpdate(textureUpdate) texture.reallocate = false } else { val textureUpdate = TextureUpdate( TextureExtents(update.xoffset, update.yoffset, update.zoffset, update.width, update.height, update.depth), update.contents, deallocate = update.deallocate) gt.addUpdate(textureUpdate) } } updates.clear() } else { if(t is TextureCache) { logger.debug("Don't know how to update $t/$texture/$name") } else { if(node.readyToRender()) { logger.error("Don't know how to update $t/$texture/$name") } else { logger.debug("Don't know how to update $t/$texture/$name") } } } } } /** * Updates the memory allocated to [texture] with the contents of the staging buffer [pbo]. * This function updates only the part of the texture at the offsets [xoffset], [yoffset], [zoffset], with the given * [width], [height], and [depth]. In case the texture data does not start at offset 0, [pixels_buffer_offset] can be * set in addition. */ override fun texSubImage3D(pbo: StagingBuffer, texture: Texture3D, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, pixels_buffer_offset: Long) { logger.debug("Updating 3D texture via PBO from {}: dx={} dy={} dz={} w={} h={} d={} offset={}", texture, xoffset, yoffset, zoffset, width, height, depth, pixels_buffer_offset ) val tmpStorage = (map(pbo) as ByteBuffer).duplicate().order(ByteOrder.LITTLE_ENDIAN) tmpStorage.position(pixels_buffer_offset.toInt()) val tmp = MemoryUtil.memAlloc(width*height*depth*texture.texInternalFormat().bytesPerElement) tmpStorage.limit(tmpStorage.position() + width*height*depth*texture.texInternalFormat().bytesPerElement) tmp.put(tmpStorage) tmp.flip() val update = SubImageUpdate(xoffset, yoffset, zoffset, width, height, depth, tmp, deallocate = true) cachedUpdates.getOrPut(texture, { ArrayList(10) }).add(update) } /** * Updates the memory allocated to [texture] with the contents of [pixels]. * This function updates only the part of the texture at the offsets [xoffset], [yoffset], [zoffset], with the given * [width], [height], and [depth]. */ @OptIn(ExperimentalTime::class) override fun texSubImage3D(texture: Texture3D, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, pixels: Buffer) { if(pixels !is ByteBuffer) { return } // val (params, duration) = measureTimedValue { // UpdateParameters(xoffset, yoffset, zoffset, width, height, depth, XXHash.XXH3_64bits(pixels)) // } // if (lastUpdates[texture] == params) { // logger.debug("Updates already seen, skipping") // return // } logger.debug("Updating 3D texture via Texture3D, hash took from {}: dx={} dy={} dz={} w={} h={} d={}", texture, xoffset, yoffset, zoffset, width, height, depth ) val p = pixels.duplicate().order(ByteOrder.LITTLE_ENDIAN) // val allocationSize = width * height * depth * texture.texInternalFormat().bytesPerElement // val tmp = //MemoryUtil.memAlloc(allocationSize) // p.limit(p.position() + allocationSize) // MemoryUtil.memCopy(p, tmp) // lastUpdates[texture] = params val update = SubImageUpdate(xoffset, yoffset, zoffset, width, height, depth, p) cachedUpdates.getOrPut(texture, { ArrayList(10) }).add(update) } fun clearLUTs() { val luts = currentlyBoundTextures.filterKeys { it.startsWith("colorMap_") }.keys luts.forEach { currentlyBoundTextures.remove(it) } } }
lgpl-3.0
bcfa0829ed72738e874b9f0d6bb82900
38.384848
232
0.573594
4.670979
false
false
false
false
allotria/intellij-community
platform/indexing-impl/src/com/intellij/model/search/impl/SearchWordQueryBuilderImpl.kt
3
4422
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.model.search.impl import com.intellij.lang.Language import com.intellij.lang.LanguageMatcher import com.intellij.model.search.LeafOccurrenceMapper import com.intellij.model.search.SearchContext import com.intellij.model.search.SearchWordQueryBuilder import com.intellij.model.search.TextOccurrence import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchScopeUtil.restrictScopeTo import com.intellij.psi.search.PsiSearchScopeUtil.restrictScopeToFileLanguage import com.intellij.psi.search.SearchScope import com.intellij.util.Query import com.intellij.util.containers.toArray import java.util.* internal data class SearchWordQueryBuilderImpl( private val myProject: Project, private val myWord: String, private val myContainerName: String? = null, private val myCaseSensitive: Boolean = true, private val mySearchContexts: Set<SearchContext> = emptySet(), private val mySearchScope: SearchScope = GlobalSearchScope.EMPTY_SCOPE, private val myFileTypes: Collection<FileType>? = null, private val myFileLanguage: LanguageInfo = LanguageInfo.NoLanguage, private val myInjection: InjectionInfo = InjectionInfo.NoInjection ) : SearchWordQueryBuilder { override fun withContainerName(containerName: String?): SearchWordQueryBuilder = copy(myContainerName = containerName) override fun caseSensitive(caseSensitive: Boolean): SearchWordQueryBuilder = copy(myCaseSensitive = caseSensitive) override fun inScope(searchScope: SearchScope): SearchWordQueryBuilder = copy(mySearchScope = searchScope) override fun restrictFileTypes(fileType: FileType, vararg fileTypes: FileType): SearchWordQueryBuilder = copy( myFileTypes = listOf(fileType, *fileTypes) ) override fun inFilesWithLanguage(language: Language): SearchWordQueryBuilder = copy( myFileLanguage = LanguageInfo.InLanguage(LanguageMatcher.match(language)) ) override fun inFilesWithLanguageOfKind(language: Language): SearchWordQueryBuilder = copy( myFileLanguage = LanguageInfo.InLanguage(LanguageMatcher.matchWithDialects(language)) ) override fun inContexts(context: SearchContext, vararg otherContexts: SearchContext): SearchWordQueryBuilder = copy( mySearchContexts = EnumSet.of(context, *otherContexts) ) override fun inContexts(contexts: Set<SearchContext>): SearchWordQueryBuilder { require(contexts.isNotEmpty()) return copy(mySearchContexts = contexts) } override fun includeInjections(): SearchWordQueryBuilder = copy(myInjection = InjectionInfo.IncludeInjections) override fun inInjections(): SearchWordQueryBuilder = copy(myInjection = InjectionInfo.InInjection(LanguageInfo.NoLanguage)) override fun inInjections(language: Language): SearchWordQueryBuilder = copy( myInjection = InjectionInfo.InInjection(LanguageInfo.InLanguage(LanguageMatcher.match(language))) ) override fun inInjectionsOfKind(language: Language): SearchWordQueryBuilder = copy( myInjection = InjectionInfo.InInjection(LanguageInfo.InLanguage(LanguageMatcher.matchWithDialects(language))) ) private fun buildSearchScope(): SearchScope { var scope = mySearchScope if (myFileTypes != null) { scope = restrictScopeTo(scope, *myFileTypes.toArray(FileType.EMPTY_ARRAY)) } if (myFileLanguage is LanguageInfo.InLanguage) { scope = restrictScopeToFileLanguage(myProject, scope, myFileLanguage.matcher) } return scope } override fun <T> buildQuery(mapper: LeafOccurrenceMapper<T>): Query<out T> = SearchWordQuery( Parameters( myProject, myWord, myContainerName, myCaseSensitive, mySearchContexts, buildSearchScope(), myInjection ), mapper ) override fun buildOccurrenceQuery(): Query<out TextOccurrence> = buildQuery(TextOccurrenceWalker) override fun buildLeafOccurrenceQuery(): Query<out TextOccurrence> = buildQuery(IdLeafOccurenceMapper) internal data class Parameters( val project: Project, val word: String, val containerName: String?, val caseSensitive: Boolean, val searchContexts: Set<SearchContext>, val searchScope: SearchScope, val injection: InjectionInfo ) }
apache-2.0
5f506eb269b8c5973123fd879170c482
39.944444
140
0.789236
4.918799
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/index/actions/GitConflictActions.kt
2
3167
// 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 git4idea.index.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.project.Project import com.intellij.util.containers.asJBIterable import git4idea.conflicts.GitMergeHandler import git4idea.conflicts.acceptConflictSide import git4idea.conflicts.getConflictOperationLock import git4idea.conflicts.showMergeWindow import git4idea.i18n.GitBundle import git4idea.index.ui.* import git4idea.repo.GitConflict import org.jetbrains.annotations.Nls import java.util.function.Supplier class GitAcceptTheirsAction : GitAcceptConflictSideAction(true) class GitAcceptYoursAction : GitAcceptConflictSideAction(false) abstract class GitConflictAction(text: Supplier<@Nls String>) : GitFileStatusNodeAction(text, Presentation.NULL_STRING, null) { override fun update(e: AnActionEvent) { val project = e.project val nodes = e.getData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable() if (project == null || nodes.filter(this::matches).isEmpty) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = isEnabled(project, nodes.filterMap(GitFileStatusNode::createConflict).asSequence() as Sequence<GitConflict>) } override fun matches(statusNode: GitFileStatusNode): Boolean = statusNode.kind == NodeKind.CONFLICTED override fun perform(project: Project, nodes: List<GitFileStatusNode>) { perform(project, createMergeHandler(project), nodes.mapNotNull { it.createConflict() }) } protected open fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean { return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked } } protected abstract fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) } abstract class GitAcceptConflictSideAction(private val takeTheirs: Boolean) : GitConflictAction(getActionText(takeTheirs)) { override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) { acceptConflictSide(project, createMergeHandler(project), conflicts, takeTheirs, project::isReversedRoot) } } private fun getActionText(takeTheirs: Boolean): Supplier<@Nls String> { return if (takeTheirs) GitBundle.messagePointer("conflicts.accept.theirs.action.text") else GitBundle.messagePointer("conflicts.accept.yours.action.text") } class GitMergeConflictAction : GitConflictAction(GitBundle.messagePointer("action.Git.Merge.text")) { override fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean { val handler = createMergeHandler(project) return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked && handler.canResolveConflict(conflict) } } override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) { showMergeWindow(project, handler, conflicts, project::isReversedRoot) } }
apache-2.0
55fff626d950d44133b939e6e9142650
42.986111
140
0.792232
4.616618
false
false
false
false
Polidea/Polithings
steppermotor/src/main/java/com/polidea/androidthings/driver/steppermotor/awaiter/DefaultAwaiter.kt
1
1081
package com.polidea.androidthings.driver.steppermotor.awaiter class DefaultAwaiter(val busyAwaitThresholdMillis: Long = 2, val busyAwaitThresholdNanos: Int = 0) : Awaiter { override fun await(millis: Long, nanos: Int) { if (millis == 0L && nanos == 0) { return } val exceedsThreshold = millis < busyAwaitThresholdMillis || millis >= busyAwaitThresholdMillis && nanos < busyAwaitThresholdNanos if (exceedsThreshold) { busyAwait(millis, nanos) } else { sleep(millis, nanos) } } private fun sleep(millis: Long, nanos: Int) = Thread.sleep(millis, nanos) private fun busyAwait(millis: Long, nanos: Int) { val awaitFinishNanos = System.nanoTime() + getNanos(millis, nanos) while (System.nanoTime() < awaitFinishNanos) { } } private fun getNanos(millis: Long, nanos: Int): Long = millis * NANOS_IN_MILLISECOND + nanos.toLong() companion object { private val NANOS_IN_MILLISECOND = 1000000L } }
mit
e0feb6a2850ae0c988f7987e3758476e
30.823529
110
0.618871
4.358871
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/util/NotificationBackend.kt
1
3689
/* * Copyright (C) 2019 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.util import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.SharedPreferences import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.preference.PreferenceManager import org.monora.uprotocol.client.android.R /** * Created by: veli * Date: 4/28/17 2:00 AM */ class NotificationBackend(val context: Context) { val manager = NotificationManagerCompat.from(context) val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val notificationSettings: Int get() { val makeSound = if (preferences.getBoolean("notification_sound", true)) NotificationCompat.DEFAULT_SOUND else 0 val vibrate = if (preferences.getBoolean("notification_vibrate", true)) NotificationCompat.DEFAULT_VIBRATE else 0 val light = if (preferences.getBoolean("notification_light", false)) NotificationCompat.DEFAULT_LIGHTS else 0 return makeSound or vibrate or light } fun buildDynamicNotification(notificationId: Int, channelId: String): DynamicNotification { return DynamicNotification(context, manager, channelId, notificationId) } fun cancel(notificationId: Int) { manager.cancel(notificationId) } companion object { private const val TAG = "NotificationBackend" const val NOTIFICATION_CHANNEL_HIGH = "tsHighPriority" const val NOTIFICATION_CHANNEL_LOW = "tsLowPriority" const val CHANNEL_INSTRUCTIVE = "instructiveNotifications" const val EXTRA_NOTIFICATION_ID = "notificationId" } init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelHigh = NotificationChannel( NOTIFICATION_CHANNEL_HIGH, context.getString(R.string.high_priority_notifications), NotificationManager.IMPORTANCE_HIGH ) channelHigh.enableLights(preferences.getBoolean("notification_light", false)) channelHigh.enableVibration(preferences.getBoolean("notification_vibrate", false)) manager.createNotificationChannel(channelHigh) val channelLow = NotificationChannel( NOTIFICATION_CHANNEL_LOW, context.getString(R.string.low_priority_notifications), NotificationManager.IMPORTANCE_LOW ) manager.createNotificationChannel(channelLow) val channelInstructive = NotificationChannel( CHANNEL_INSTRUCTIVE, context.getString(R.string.notifications_instructive), NotificationManager.IMPORTANCE_MAX ) manager.createNotificationChannel(channelInstructive) } } }
gpl-2.0
c913a5b6e6d8807158c3b2a23e629fd5
38.655914
108
0.70526
5.024523
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/Job.kt
1
31453
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("JobKt") @file:Suppress("DEPRECATION_ERROR", "RedundantUnitReturnType") package kotlinx.coroutines import kotlinx.coroutines.selects.* import kotlin.coroutines.* import kotlin.jvm.* // --------------- core job interfaces --------------- /** * A background job. Conceptually, a job is a cancellable thing with a life-cycle that * culminates in its completion. * * Jobs can be arranged into parent-child hierarchies where cancellation * of a parent leads to immediate cancellation of all its [children] recursively. * Failure of a child with an exception other than [CancellationException] immediately cancels its parent and, * consequently, all its other children. This behavior can be customized using [SupervisorJob]. * * The most basic instances of `Job` interface are created like this: * * * **Coroutine job** is created with [launch][CoroutineScope.launch] coroutine builder. * It runs a specified block of code and completes on completion of this block. * * **[CompletableJob]** is created with a `Job()` factory function. * It is completed by calling [CompletableJob.complete]. * * Conceptually, an execution of a job does not produce a result value. Jobs are launched solely for their * side-effects. See [Deferred] interface for a job that produces a result. * * ### Job states * * A job has the following states: * * | **State** | [isActive] | [isCompleted] | [isCancelled] | * | -------------------------------- | ---------- | ------------- | ------------- | * | _New_ (optional initial state) | `false` | `false` | `false` | * | _Active_ (default initial state) | `true` | `false` | `false` | * | _Completing_ (transient state) | `true` | `false` | `false` | * | _Cancelling_ (transient state) | `false` | `false` | `true` | * | _Cancelled_ (final state) | `false` | `true` | `true` | * | _Completed_ (final state) | `false` | `true` | `false` | * * Usually, a job is created in the _active_ state (it is created and started). However, coroutine builders * that provide an optional `start` parameter create a coroutine in the _new_ state when this parameter is set to * [CoroutineStart.LAZY]. Such a job can be made _active_ by invoking [start] or [join]. * * A job is _active_ while the coroutine is working or until [CompletableJob] is completed, * or until it fails or cancelled. * * Failure of an _active_ job with an exception makes it _cancelling_. * A job can be cancelled at any time with [cancel] function that forces it to transition to * the _cancelling_ state immediately. The job becomes _cancelled_ when it finishes executing its work and * all its children complete. * * Completion of an _active_ coroutine's body or a call to [CompletableJob.complete] transitions the job to * the _completing_ state. It waits in the _completing_ state for all its children to complete before * transitioning to the _completed_ state. * Note that _completing_ state is purely internal to the job. For an outside observer a _completing_ job is still * active, while internally it is waiting for its children. * * ``` * wait children * +-----+ start +--------+ complete +-------------+ finish +-----------+ * | New | -----> | Active | ---------> | Completing | -------> | Completed | * +-----+ +--------+ +-------------+ +-----------+ * | cancel / fail | * | +----------------+ * | | * V V * +------------+ finish +-----------+ * | Cancelling | --------------------------------> | Cancelled | * +------------+ +-----------+ * ``` * * A `Job` instance in the * [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/coroutine-context.html) * represents the coroutine itself. * * ### Cancellation cause * * A coroutine job is said to _complete exceptionally_ when its body throws an exception; * a [CompletableJob] is completed exceptionally by calling [CompletableJob.completeExceptionally]. * An exceptionally completed job is cancelled and the corresponding exception becomes the _cancellation cause_ of the job. * * Normal cancellation of a job is distinguished from its failure by the type of this exception that caused its cancellation. * A coroutine that threw [CancellationException] is considered to be _cancelled normally_. * If a cancellation cause is a different exception type, then the job is considered to have _failed_. * When a job has _failed_, then its parent gets cancelled with the exception of the same type, * thus ensuring transparency in delegating parts of the job to its children. * * Note, that [cancel] function on a job only accepts [CancellationException] as a cancellation cause, thus * calling [cancel] always results in a normal cancellation of a job, which does not lead to cancellation * of its parent. This way, a parent can [cancel] its own children (cancelling all their children recursively, too) * without cancelling itself. * * ### Concurrency and synchronization * * All functions on this interface and on all interfaces derived from it are **thread-safe** and can * be safely invoked from concurrent coroutines without external synchronization. * * ### Not stable for inheritance * * **`Job` interface and all its derived interfaces are not stable for inheritance in 3rd party libraries**, * as new methods might be added to this interface in the future, but is stable for use. */ public interface Job : CoroutineContext.Element { /** * Key for [Job] instance in the coroutine context. */ public companion object Key : CoroutineContext.Key<Job> // ------------ state query ------------ /** * Returns `true` when this job is active -- it was already started and has not completed nor was cancelled yet. * The job that is waiting for its [children] to complete is still considered to be active if it * was not cancelled nor failed. * * See [Job] documentation for more details on job states. */ public val isActive: Boolean /** * Returns `true` when this job has completed for any reason. A job that was cancelled or failed * and has finished its execution is also considered complete. Job becomes complete only after * all its [children] complete. * * See [Job] documentation for more details on job states. */ public val isCompleted: Boolean /** * Returns `true` if this job was cancelled for any reason, either by explicit invocation of [cancel] or * because it had failed or its child or parent was cancelled. * In the general case, it does not imply that the * job has already [completed][isCompleted], because it may still be finishing whatever it was doing and * waiting for its [children] to complete. * * See [Job] documentation for more details on cancellation and failures. */ public val isCancelled: Boolean /** * Returns [CancellationException] that signals the completion of this job. This function is * used by [cancellable][suspendCancellableCoroutine] suspending functions. They throw exception * returned by this function when they suspend in the context of this job and this job becomes _complete_. * * This function returns the original [cancel] cause of this job if that `cause` was an instance of * [CancellationException]. Otherwise (if this job was cancelled with a cause of a different type, or * was cancelled without a cause, or had completed normally), an instance of [CancellationException] is * returned. The [CancellationException.cause] of the resulting [CancellationException] references * the original cancellation cause that was passed to [cancel] function. * * This function throws [IllegalStateException] when invoked on a job that is still active. * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public fun getCancellationException(): CancellationException // ------------ state update ------------ /** * Starts coroutine related to this job (if any) if it was not started yet. * The result is `true` if this invocation actually started coroutine or `false` * if it was already started or completed. */ public fun start(): Boolean /** * Cancels this job with an optional cancellation [cause]. * A cause can be used to specify an error message or to provide other details on * the cancellation reason for debugging purposes. * See [Job] documentation for full explanation of cancellation machinery. */ public fun cancel(cause: CancellationException? = null) /** * @suppress This method implements old version of JVM ABI. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun cancel(): Unit = cancel(null) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun cancel(cause: Throwable? = null): Boolean // ------------ parent-child ------------ /** * Returns a sequence of this job's children. * * A job becomes a child of this job when it is constructed with this job in its * [CoroutineContext] or using an explicit `parent` parameter. * * A parent-child relation has the following effect: * * * Cancellation of parent with [cancel] or its exceptional completion (failure) * immediately cancels all its children. * * Parent cannot complete until all its children are complete. Parent waits for all its children to * complete in _completing_ or _cancelling_ state. * * Uncaught exception in a child, by default, cancels parent. This applies even to * children created with [async][CoroutineScope.async] and other future-like * coroutine builders, even though their exceptions are caught and are encapsulated in their result. * This default behavior can be overridden with [SupervisorJob]. */ public val children: Sequence<Job> /** * Attaches child job so that this job becomes its parent and * returns a handle that should be used to detach it. * * A parent-child relation has the following effect: * * Cancellation of parent with [cancel] or its exceptional completion (failure) * immediately cancels all its children. * * Parent cannot complete until all its children are complete. Parent waits for all its children to * complete in _completing_ or _cancelling_ states. * * **A child must store the resulting [ChildHandle] and [dispose][DisposableHandle.dispose] the attachment * to its parent on its own completion.** * * Coroutine builders and job factory functions that accept `parent` [CoroutineContext] parameter * lookup a [Job] instance in the parent context and use this function to attach themselves as a child. * They also store a reference to the resulting [ChildHandle] and dispose a handle when they complete. * * @suppress This is an internal API. This method is too error prone for public API. */ // ChildJob and ChildHandle are made internal on purpose to further deter 3rd-party impl of Job @InternalCoroutinesApi public fun attachChild(child: ChildJob): ChildHandle // ------------ state waiting ------------ /** * Suspends the coroutine until this job is complete. This invocation resumes normally (without exception) * when the job is complete for any reason and the [Job] of the invoking coroutine is still [active][isActive]. * This function also [starts][Job.start] the corresponding coroutine if the [Job] was still in _new_ state. * * Note that the job becomes complete only when all its children are complete. * * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job. * If the [Job] of the invoking coroutine is cancelled or completed when this * suspending function is invoked or while it is suspended, this function * throws [CancellationException]. * * In particular, it means that a parent coroutine invoking `join` on a child coroutine throws * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default, * unless the child was launched from within [supervisorScope]. * * This function can be used in [select] invocation with [onJoin] clause. * Use [isCompleted] to check for a completion of this job without waiting. * * There is [cancelAndJoin] function that combines an invocation of [cancel] and `join`. */ public suspend fun join() /** * Clause for [select] expression of [join] suspending function that selects when the job is complete. * This clause never fails, even if the job completes exceptionally. */ public val onJoin: SelectClause0 // ------------ low-level state-notification ------------ /** * Registers handler that is **synchronously** invoked once on completion of this job. * When the job is already complete, then the handler is immediately invoked * with the job's exception or cancellation cause or `null`. Otherwise, the handler will be invoked once when this * job is complete. * * The meaning of `cause` that is passed to the handler: * * Cause is `null` when the job has completed normally. * * Cause is an instance of [CancellationException] when the job was cancelled _normally_. * **It should not be treated as an error**. In particular, it should not be reported to error logs. * * Otherwise, the job had _failed_. * * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the * registration of this handler and release its memory if its invocation is no longer needed. * There is no need to dispose the handler after completion of this job. The references to * all the handlers are released when this job completes. * * Installed [handler] should not throw any exceptions. If it does, they will get caught, * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code. * * **Note**: Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe. * This handler can be invoked concurrently with the surrounding code. * There is no guarantee on the execution context in which the [handler] is invoked. */ public fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle /** * Registers handler that is **synchronously** invoked once on cancellation or completion of this job. * when the job was already cancelled and is completed its execution, then the handler is immediately invoked * with the job's cancellation cause or `null` unless [invokeImmediately] is set to false. * Otherwise, handler will be invoked once when this job is cancelled or is complete. * * The meaning of `cause` that is passed to the handler: * * Cause is `null` when the job has completed normally. * * Cause is an instance of [CancellationException] when the job was cancelled _normally_. * **It should not be treated as an error**. In particular, it should not be reported to error logs. * * Otherwise, the job had _failed_. * * Invocation of this handler on a transition to a _cancelling_ state * is controlled by [onCancelling] boolean parameter. * The handler is invoked when the job becomes _cancelling_ if [onCancelling] parameter is set to `true`. * * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the * registration of this handler and release its memory if its invocation is no longer needed. * There is no need to dispose the handler after completion of this job. The references to * all the handlers are released when this job completes. * * Installed [handler] should not throw any exceptions. If it does, they will get caught, * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code. * * **Note**: This function is a part of internal machinery that supports parent-child hierarchies * and allows for implementation of suspending functions that wait on the Job's state. * This function should not be used in general application code. * Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe. * This handler can be invoked concurrently with the surrounding code. * There is no guarantee on the execution context in which the [handler] is invoked. * * @param onCancelling when `true`, then the [handler] is invoked as soon as this job transitions to _cancelling_ state; * when `false` then the [handler] is invoked only when it transitions to _completed_ state. * @param invokeImmediately when `true` and this job is already in the desired state (depending on [onCancelling]), * then the [handler] is immediately and synchronously invoked and no-op [DisposableHandle] is returned; * when `false` then no-op [DisposableHandle] is returned, but the [handler] is not invoked. * @param handler the handler. * * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public fun invokeOnCompletion( onCancelling: Boolean = false, invokeImmediately: Boolean = true, handler: CompletionHandler): DisposableHandle // ------------ unstable internal API ------------ /** * @suppress **Error**: Operator '+' on two Job objects is meaningless. * Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts. * The job to the right of `+` just replaces the job the left of `+`. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated(message = "Operator '+' on two Job objects is meaningless. " + "Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts. " + "The job to the right of `+` just replaces the job the left of `+`.", level = DeprecationLevel.ERROR) public operator fun plus(other: Job): Job = other } /** * Creates a job object in an active state. * A failure of any child of this job immediately causes this job to fail, too, and cancels the rest of its children. * * To handle children failure independently of each other use [SupervisorJob]. * * If [parent] job is specified, then this job becomes a child job of its parent and * is cancelled when its parent fails or is cancelled. All this job's children are cancelled in this case, too. * The invocation of [cancel][Job.cancel] with exception (other than [CancellationException]) on this job also cancels parent. * * Conceptually, the resulting job works in the same way as the job created by the `launch { body }` invocation * (see [launch]), but without any code in the body. It is active until cancelled or completed. Invocation of * [CompletableJob.complete] or [CompletableJob.completeExceptionally] corresponds to the successful or * failed completion of the body of the coroutine. * * @param parent an optional parent job. */ @Suppress("FunctionName") public fun Job(parent: Job? = null): CompletableJob = JobImpl(parent) /** @suppress Binary compatibility only */ @Suppress("FunctionName") @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") @JvmName("Job") public fun Job0(parent: Job? = null): Job = Job(parent) /** * A handle to an allocated object that can be disposed to make it eligible for garbage collection. */ public fun interface DisposableHandle { /** * Disposes the corresponding object, making it eligible for garbage collection. * Repeated invocation of this function has no effect. */ public fun dispose() } // -------------------- Parent-child communication -------------------- /** * A reference that parent receives from its child so that it can report its cancellation. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ChildJob : Job { /** * Parent is cancelling its child by invoking this method. * Child finds the cancellation cause using [ParentJob.getChildJobCancellationCause]. * This method does nothing is the child is already being cancelled. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun parentCancelled(parentJob: ParentJob) } /** * A reference that child receives from its parent when it is being cancelled by the parent. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ParentJob : Job { /** * Child job is using this method to learn its cancellation cause when the parent cancels it with [ChildJob.parentCancelled]. * This method is invoked only if the child was not already being cancelled. * * Note that [CancellationException] is the method's return type: if child is cancelled by its parent, * then the original exception is **already** handled by either the parent or the original source of failure. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun getChildJobCancellationCause(): CancellationException } /** * A handle that child keep onto its parent so that it is able to report its cancellation. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases") public interface ChildHandle : DisposableHandle { /** * Returns the parent of the current parent-child relationship. * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public val parent: Job? /** * Child is cancelling its parent by invoking this method. * This method is invoked by the child twice. The first time child report its root cause as soon as possible, * so that all its siblings and the parent can start cancelling their work asap. The second time * child invokes this method when it had aggregated and determined its final cancellation cause. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public fun childCancelled(cause: Throwable): Boolean } // -------------------- Job extensions -------------------- /** * Disposes a specified [handle] when this job is complete. * * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created). * ``` * invokeOnCompletion { handle.dispose() } * ``` */ internal fun Job.disposeOnCompletion(handle: DisposableHandle): DisposableHandle = invokeOnCompletion(handler = DisposeOnCompletion(handle).asHandler) /** * Cancels the job and suspends the invoking coroutine until the cancelled job is complete. * * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job. * If the [Job] of the invoking coroutine is cancelled or completed when this * suspending function is invoked or while it is suspended, this function * throws [CancellationException]. * * In particular, it means that a parent coroutine invoking `cancelAndJoin` on a child coroutine throws * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default, * unless the child was launched from within [supervisorScope]. * * This is a shortcut for the invocation of [cancel][Job.cancel] followed by [join][Job.join]. */ public suspend fun Job.cancelAndJoin() { cancel() return join() } /** * Cancels all [children][Job.children] jobs of this coroutine using [Job.cancel] for all of them * with an optional cancellation [cause]. * Unlike [Job.cancel] on this job as a whole, the state of this job itself is not affected. */ public fun Job.cancelChildren(cause: CancellationException? = null) { children.forEach { it.cancel(cause) } } /** * @suppress This method implements old version of JVM ABI. Use [cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun Job.cancelChildren(): Unit = cancelChildren(null) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [Job.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun Job.cancelChildren(cause: Throwable? = null) { children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(this)) } } // -------------------- CoroutineContext extensions -------------------- /** * Returns `true` when the [Job] of the coroutine in this context is still active * (has not completed and was not cancelled yet). * * Check this property in long-running computation loops to support cancellation * when [CoroutineScope.isActive] is not available: * * ``` * while (coroutineContext.isActive) { * // do some computation * } * ``` * * The `coroutineContext.isActive` expression is a shortcut for `coroutineContext[Job]?.isActive == true`. * See [Job.isActive]. */ public val CoroutineContext.isActive: Boolean get() = this[Job]?.isActive == true /** * Cancels [Job] of this context with an optional cancellation cause. * See [Job.cancel] for details. */ public fun CoroutineContext.cancel(cause: CancellationException? = null) { this[Job]?.cancel(cause) } /** * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancel(): Unit = cancel(null) /** * Ensures that current job is [active][Job.isActive]. * If the job is no longer active, throws [CancellationException]. * If the job was cancelled, thrown exception contains the original cancellation cause. * * This method is a drop-in replacement for the following code, but with more precise exception: * ``` * if (!job.isActive) { * throw CancellationException() * } * ``` */ public fun Job.ensureActive(): Unit { if (!isActive) throw getCancellationException() } /** * Ensures that job in the current context is [active][Job.isActive]. * * If the job is no longer active, throws [CancellationException]. * If the job was cancelled, thrown exception contains the original cancellation cause. * This function does not do anything if there is no [Job] in the context, since such a coroutine cannot be cancelled. * * This method is a drop-in replacement for the following code, but with more precise exception: * ``` * if (!isActive) { * throw CancellationException() * } * ``` */ public fun CoroutineContext.ensureActive() { get(Job)?.ensureActive() } /** * Cancels current job, including all its children with a specified diagnostic error [message]. * A [cause] can be specified to provide additional details on a cancellation reason for debugging purposes. */ public fun Job.cancel(message: String, cause: Throwable? = null): Unit = cancel(CancellationException(message, cause)) /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancel]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancel(cause: Throwable? = null): Boolean { val job = this[Job] as? JobSupport ?: return false job.cancelInternal(cause.orCancellation(job)) return true } /** * Cancels all children of the [Job] in this context, without touching the state of this job itself * with an optional cancellation cause. See [Job.cancel]. * It does not do anything if there is no job in the context or it has no children. */ public fun CoroutineContext.cancelChildren(cause: CancellationException? = null) { this[Job]?.children?.forEach { it.cancel(cause) } } /** * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancelChildren(): Unit = cancelChildren(null) /** * Retrieves the current [Job] instance from the given [CoroutineContext] or * throws [IllegalStateException] if no job is present in the context. * * This method is a short-cut for `coroutineContext[Job]!!` and should be used only when it is known in advance that * the context does have instance of the job in it. */ public val CoroutineContext.job: Job get() = get(Job) ?: error("Current context doesn't contain Job in it: $this") /** * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancelChildren]. */ @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x") public fun CoroutineContext.cancelChildren(cause: Throwable? = null) { val job = this[Job] ?: return job.children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(job)) } } private fun Throwable?.orCancellation(job: Job): Throwable = this ?: JobCancellationException("Job was cancelled", null, job) /** * No-op implementation of [DisposableHandle]. * @suppress **This an internal API and should not be used from general code.** */ @InternalCoroutinesApi public object NonDisposableHandle : DisposableHandle, ChildHandle { override val parent: Job? get() = null /** * Does not do anything. * @suppress */ override fun dispose() {} /** * Returns `false`. * @suppress */ override fun childCancelled(cause: Throwable): Boolean = false /** * Returns "NonDisposableHandle" string. * @suppress */ override fun toString(): String = "NonDisposableHandle" }
apache-2.0
421a274b9b7452f925fce664aec3b200
46.014948
129
0.691317
4.589669
false
false
false
false
leafclick/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt
1
12551
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable import com.intellij.codeInsight.hints.settings.Diff import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.injected.editor.EditorWindow import com.intellij.lang.Language import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil class ShowSettingsWithAddedPattern : AnAction() { init { templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description") templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_") } override fun update(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) if (info is MethodInfo) { e.presentation.setText(CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName()), false) } else { e.presentation.isVisible = false } } override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) { when (it) { is HintInfo.OptionInfo -> null is MethodInfo -> it.toPattern() }} } } class ShowParameterHintsSettings : AnAction() { override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) {null} } } fun showParameterHintsDialog(e: AnActionEvent, getPattern: (HintInfo) -> String?) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val fileLanguage = file.language InlayParameterHintsExtension.forLanguage(fileLanguage) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) ?: return val selectedLanguage = (info as? MethodInfo)?.language ?: fileLanguage when (val pattern = getPattern(info)) { null -> InlayHintsConfigurable.showSettingsDialogForLanguage(file.project, fileLanguage) else -> BlackListDialog(selectedLanguage, pattern).show() } } class BlacklistCurrentMethodIntention : IntentionAction, LowPriorityAction { companion object { private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method") private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } override fun getText(): String = presentableText override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false return hintsProvider.isBlackListSupported && hasEditorParameterHintAtOffset(editor, file) && isMethodHintAtOffset(editor, file) } private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) is MethodInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return val language = info.language ?: file.language ParameterNameHintsSettings.getInstance().addIgnorePattern(getLanguageForSettingKey(language), info.toPattern()) refreshAllOpenEditors() showHint(project, language, info) } private fun showHint(project: Project, language: Language, info: MethodInfo) { val methodName = info.getMethodName() val listener = NotificationListener { notification, event -> when (event.description) { "settings" -> showSettings(language) "undo" -> undo(language, info) } notification.expire() } val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist", "<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>", NotificationType.INFORMATION, listener) notification.notify(project) } private fun showSettings(language: Language) { BlackListDialog(language).show() } private fun undo(language: Language, info: MethodInfo) { val settings = ParameterNameHintsSettings.getInstance() val languageForSettings = getLanguageForSettingKey(language) val diff = settings.getBlackListDiff(languageForSettings) val updated = diff.added.toMutableSet().apply { remove(info.toPattern()) } settings.setBlackListDiff(languageForSettings, Diff(updated, diff.removed)) refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class DisableCustomHintsOption: IntentionAction, LowPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String = getIntentionText() private fun getIntentionText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return "Do not ${lastOptionName.toLowerCase()}" } return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { InlayParameterHintsExtension.forLanguage(file.language) ?: return false if (!hasEditorParameterHintAtOffset(editor, file)) return false val option = getOptionHintAtOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getOptionHintAtOffset(editor, file) ?: return option.disable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class EnableCustomHintsOption: IntentionAction, HighPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return lastOptionName.capitalizeFirstLetter() } return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language if(!isParameterHintsEnabledForLanguage(language)) return false if (editor !is EditorImpl) return false InlayParameterHintsExtension.forLanguage(file.language) ?: return false val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val target = PsiTreeUtil.findFirstParent(element) { it is PsiFile || provider.hasDisabledOptionHintInfo(it) } if (target == null || target is PsiFile) return null return provider.getHintInfo(target) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return option.enable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean { val info = getHintInfo(element) return info is HintInfo.OptionInfo && !info.isOptionEnabled() } class ToggleInlineHintsAction : AnAction() { companion object { private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize() private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize() } override fun update(e: AnActionEvent) { if (!InlayParameterHintsExtension.hasAnyExtensions()) { e.presentation.isEnabledAndVisible = false return } val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val isHintsShownNow = isParameterHintsEnabledForLanguage(file.language) e.presentation.text = if (isHintsShownNow) disableText else enableText e.presentation.isEnabledAndVisible = true } override fun actionPerformed(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val language = file.language val before = isParameterHintsEnabledForLanguage(language) setShowParameterHintsForLanguage(!before, language) refreshAllOpenEditors() } } private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean { if (editor is EditorWindow) return false val offset = editor.caretModel.offset val element = file.findElementAt(offset) val startOffset = element?.textRange?.startOffset ?: offset val endOffset = element?.textRange?.endOffset ?: offset return ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(editor, startOffset, endOffset).isNotEmpty() } private fun refreshAllOpenEditors() { ParameterHintsPassFactory.forceHintsUpdateOnNextPass() ProjectManager.getInstance().openProjects.forEach { project -> val psiManager = PsiManager.getInstance(project) val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(project) val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.selectedFiles.forEach { file -> psiManager.findFile(file)?.let { daemonCodeAnalyzer.restart(it) } } } } private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? { val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val method = PsiTreeUtil.findFirstParent(element) { it is PsiFile // hint owned by element || (provider.getHintInfo(it)?.isOwnedByPsiElement(it, editor) ?: false)} if (method == null || method is PsiFile) return null return provider.getHintInfo(method) } fun MethodInfo.toPattern(): String = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')' private fun String.capitalize() = StringUtil.capitalizeWords(this, true) private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this)
apache-2.0
03349edce9ad507addb82a9e763def0f
36.580838
140
0.748148
4.97858
false
false
false
false
AndroidX/androidx
room/room-migration/src/main/java/androidx/room/migration/bundle/DatabaseBundle.kt
3
3696
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.migration.bundle import androidx.annotation.RestrictTo import androidx.room.migration.bundle.SchemaEqualityUtil.checkSchemaEquality import com.google.gson.annotations.SerializedName /** * Data class that holds the schema information for a * [androidx.room.Database]. * * @constructor Creates a new database * @property version Version * @property identityHash Identity hash * @property entities List of entities * @property views List of views * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) public open class DatabaseBundle( @field:SerializedName("version") public open val version: Int, @field:SerializedName("identityHash") public open val identityHash: String, @field:SerializedName("entities") public open val entities: List<EntityBundle>, @field:SerializedName("views") public open val views: List<DatabaseViewBundle>, @field:SerializedName("setupQueries") private val setupQueries: List<String>, ) : SchemaEquality<DatabaseBundle> { // Used by GSON @Deprecated("Marked deprecated to avoid usage in the codebase") @SuppressWarnings("unused") public constructor() : this(0, "", emptyList(), emptyList(), emptyList()) @delegate:Transient public open val entitiesByTableName: Map<String, EntityBundle> by lazy { entities.associateBy { it.tableName } } @delegate:Transient public val viewsByName: Map<String, DatabaseViewBundle> by lazy { views.associateBy { it.viewName } } /** * @return List of SQL queries to build this database from scratch. */ public open fun buildCreateQueries(): List<String> { return buildList { entities.sortedWith(FtsEntityCreateComparator()).forEach { entityBundle -> addAll(entityBundle.buildCreateQueries()) } views.forEach { viewBundle -> add(viewBundle.createView()) } addAll(setupQueries) } } @Override override fun isSchemaEqual(other: DatabaseBundle): Boolean { return checkSchemaEquality(entitiesByTableName, other.entitiesByTableName) && checkSchemaEquality(viewsByName, other.viewsByName) } // Comparator to sort FTS entities after their declared external content entity so that the // content entity table gets created first. public class FtsEntityCreateComparator : Comparator<EntityBundle> { override fun compare(firstEntity: EntityBundle, secondEntity: EntityBundle): Int { if (firstEntity is FtsEntityBundle) { val contentTable = firstEntity.ftsOptions.contentTable if (contentTable == secondEntity.tableName) { return 1 } } else if (secondEntity is FtsEntityBundle) { val contentTable = secondEntity.ftsOptions.contentTable if (contentTable == firstEntity.tableName) { return -1 } } return 0 } } }
apache-2.0
bcbe148370a917d6c2c153e02898984b
34.883495
95
0.678301
4.844037
false
false
false
false
AndroidX/androidx
buildSrc/private/src/main/kotlin/androidx/build/resources/UpdateResourceApiTask.kt
3
2794
/* * 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.build.resources import androidx.build.checkapi.ApiLocation import org.gradle.api.DefaultTask import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFiles import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import java.io.File /** * Task for updating the public Android resource surface, e.g. `public.xml`. */ @CacheableTask abstract class UpdateResourceApiTask : DefaultTask() { /** Generated resource API file (in build output). */ @get:Internal abstract val apiLocation: Property<ApiLocation> @get:Input abstract val forceUpdate: Property<Boolean> @InputFile @PathSensitive(PathSensitivity.RELATIVE) fun getTaskInput(): File { return apiLocation.get().resourceFile } /** Resource API files to which APIs should be written (in source control). */ @get:Internal // outputs are declared in getTaskOutputs() abstract val outputApiLocations: ListProperty<ApiLocation> @OutputFiles fun getTaskOutputs(): List<File> { return outputApiLocations.get().flatMap { outputApiLocation -> listOf( outputApiLocation.resourceFile ) } } @TaskAction fun updateResourceApi() { var permitOverwriting = true for (outputApi in outputApiLocations.get()) { val version = outputApi.version() if (version != null && version.isFinalApi() && outputApi.publicApiFile.exists() && !forceUpdate.get() ) { permitOverwriting = false } } val inputApi = apiLocation.get().resourceFile for (outputApi in outputApiLocations.get()) { androidx.build.metalava.copy( inputApi, outputApi.resourceFile, permitOverwriting, logger ) } } }
apache-2.0
b40a8c76703910a5c561fb8492796c70
30.75
82
0.675376
4.602965
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/namedVariant/NamedVariantTransformationSupport.kt
12
4022
// 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.transformations.impl.namedVariant import com.intellij.openapi.util.NlsSafe import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiManager import com.intellij.psi.PsiModifier 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.impl.PsiImplUtil.getAnnotation import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightModifierList import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightParameter import org.jetbrains.plugins.groovy.lang.resolve.ast.extractVisibility import org.jetbrains.plugins.groovy.lang.resolve.ast.getVisibility import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport import org.jetbrains.plugins.groovy.transformations.TransformationContext class NamedVariantTransformationSupport : AstTransformationSupport { override fun applyTransformation(context: TransformationContext) { context.codeClass.codeMethods.forEach { if (!it.hasAnnotation(GROOVY_TRANSFORM_NAMED_VARIANT)) return@forEach val method = constructNamedMethod(it, context) ?: return@forEach context.addMethod(method) } } private fun constructNamedMethod(method: GrMethod, context: TransformationContext): GrLightMethodBuilder? { val parameters = mutableListOf<GrParameter>() val namedVariantAnnotation = method.getAnnotation(GROOVY_TRANSFORM_NAMED_VARIANT) ?: return null val mapType = TypesUtil.createType(JAVA_UTIL_MAP, method) val mapParameter = GrLightParameter(NAMED_ARGS_PARAMETER_NAME, mapType, method) val modifierList = GrLightModifierList(mapParameter) mapParameter.modifierList = modifierList parameters.add(mapParameter) val namedParams = collectNamedParamsFromNamedVariantMethod(method) namedParams.forEach { namedParam -> addNamedParamAnnotation(modifierList, namedParam) } val requiredParameters = method.parameterList.parameters .filter { getAnnotation(it, GROOVY_TRANSFORM_NAMED_PARAM) == null && getAnnotation(it, GROOVY_TRANSFORM_NAMED_DELEGATE) == null } if (requiredParameters.size != method.parameters.size) { parameters.addAll(requiredParameters) } return buildMethod(parameters, method, namedVariantAnnotation, context) } internal class NamedVariantGeneratedMethod(manager: PsiManager?, name: @NlsSafe String?) : GrLightMethodBuilder(manager, name) private fun buildMethod(parameters: List<GrParameter>, method: GrMethod, namedVariantAnnotation: PsiAnnotation, context: TransformationContext): GrLightMethodBuilder? { val builder = NamedVariantGeneratedMethod(method.manager, method.name + "") val psiClass = method.containingClass ?: return null builder.containingClass = psiClass builder.returnType = method.returnType builder.navigationElement = method val defaultVisibility = extractVisibility(method) val requiredVisibility = getVisibility(namedVariantAnnotation, builder, defaultVisibility) builder.modifierList.addModifier(requiredVisibility.toString()) if (context.hasModifierProperty(method.modifierList, PsiModifier.STATIC)) { builder.modifierList.addModifier(PsiModifier.STATIC) } builder.isConstructor = method.isConstructor parameters.forEach { builder.addParameter(it) } method.throwsList.referencedTypes.forEach { builder.addException(it) } builder.originInfo = NAMED_VARIANT_ORIGIN_INFO return builder } }
apache-2.0
c94522ae461b94dc54ffa5edecfd3fcd
49.2875
140
0.781701
4.788095
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/NewProjectWizardPanelBuilder.kt
1
2132
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Key import com.intellij.ui.dsl.builder.Panel import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @ApiStatus.Internal internal class NewProjectWizardPanelBuilder(private val context: WizardContext) { private val panels = LinkedHashMap<DialogPanel, Boolean>() private val straightPanels get() = panels.filter { it.value }.keys fun getPreferredFocusedComponent(): JComponent? = straightPanels.firstNotNullOfOrNull { it.preferredFocusedComponent } fun panel(init: Panel.() -> Unit) = com.intellij.ui.dsl.builder.panel(init) .also { panels[it] = true } .apply { registerValidators(context.disposable) } fun setVisible(panel: DialogPanel, isVisible: Boolean) { panels[panel] = isVisible panel.isVisible = isVisible } fun validate() = straightPanels.asSequence() .flatMap { it.validateCallbacks } .mapNotNull { it() } .map { it.also(::logValidationInfoInHeadlessMode) } .all { it.okEnabled } private fun logValidationInfoInHeadlessMode(info: ValidationInfo) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { logger<NewProjectWizardPanelBuilder>().warn(info.message) } } fun isModified() = straightPanels.any { it.isModified() } fun apply() = straightPanels.forEach(DialogPanel::apply) fun reset() = panels.keys.forEach(DialogPanel::reset) init { KEY.set(context, this) } companion object { private val KEY = Key.create<NewProjectWizardPanelBuilder>(NewProjectWizardPanelBuilder::class.java.name) fun getInstance(context: WizardContext): NewProjectWizardPanelBuilder = KEY.get(context) } }
apache-2.0
bcc9f132296a7aab4e34f4a9cb1e960a
33.403226
158
0.751876
4.469602
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt
1
10176
package info.nightscout.androidaps.plugins.treatments.fragments import android.graphics.Paint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment.RecyclerProfileViewAdapter.ProfileSwitchViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.treatments_profileswitch_fragment.* import javax.inject.Inject class TreatmentsProfileSwitchFragment : DaggerFragment() { private val disposable = CompositeDisposable() @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsUpload: NSUpload @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.treatments_profileswitch_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) profileswitch_recyclerview.setHasFixedSize(true) profileswitch_recyclerview.layoutManager = LinearLayoutManager(view.context) profileswitch_recyclerview.adapter = RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)) profileswitch_refreshfromnightscout.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { MainApp.getDbHelper().resetProfileSwitch() rxBus.send(EventNSClientRestart()) } } } if (sp.getBoolean(R.string.key_ns_upload_only, true) || !buildHelper.isEngineeringMode()) profileswitch_refreshfromnightscout.visibility = View.GONE } @Synchronized override fun onResume() { super.onResume() disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } ) updateGUI() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } fun updateGUI() = profileswitch_recyclerview?.swapAdapter(RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false) inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ProfileSwitchViewHolder { return ProfileSwitchViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_profileswitch_item, viewGroup, false)) } override fun onBindViewHolder(holder: ProfileSwitchViewHolder, position: Int) { val profileSwitch = profileSwitchList[position] holder.ph.visibility = (profileSwitch.source == Source.PUMP).toVisibility() holder.ns.visibility = NSUpload.isIdValid(profileSwitch._id).toVisibility() holder.date.text = dateUtil.dateAndTimeString(profileSwitch.date) if (!profileSwitch.isEndingEvent) { holder.duration.text = resourceHelper.gs(R.string.format_mins, profileSwitch.durationInMinutes) } else { holder.duration.text = "" } holder.name.text = profileSwitch.customizedName if (profileSwitch.isInProgress) holder.date.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.date.setTextColor(holder.duration.currentTextColor) holder.remove.tag = profileSwitch holder.clone.tag = profileSwitch holder.name.tag = profileSwitch holder.date.tag = profileSwitch holder.invalid.visibility = if (profileSwitch.isValid()) View.GONE else View.VISIBLE } override fun getItemCount(): Int { return profileSwitchList.size } inner class ProfileSwitchViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { var date: TextView = itemView.findViewById<View>(R.id.profileswitch_date) as TextView var duration: TextView = itemView.findViewById<View>(R.id.profileswitch_duration) as TextView var name: TextView = itemView.findViewById<View>(R.id.profileswitch_name) as TextView var remove: TextView = itemView.findViewById<View>(R.id.profileswitch_remove) as TextView var clone: TextView = itemView.findViewById<View>(R.id.profileswitch_clone) as TextView var ph: TextView = itemView.findViewById<View>(R.id.pump_sign) as TextView var ns: TextView = itemView.findViewById<View>(R.id.ns_sign) as TextView var invalid: TextView = itemView.findViewById<View>(R.id.invalid_sign) as TextView override fun onClick(v: View) { val profileSwitch = v.tag as ProfileSwitch when (v.id) { R.id.profileswitch_remove -> activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { val id = profileSwitch._id if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(profileSwitch) }) } R.id.profileswitch_clone -> activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.customizedName + "\n" + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { profileSwitch.profileObject?.let { val nonCustomized = it.convertToNonCustomizedProfile() if (nonCustomized.isValid(resourceHelper.gs(R.string.careportal_profileswitch, false))) { localProfilePlugin.addProfile(localProfilePlugin.copyFrom(nonCustomized, profileSwitch.customizedName + " " + dateUtil.dateAndTimeString(profileSwitch.date).replace(".", "_"))) rxBus.send(EventLocalProfileChanged()) } else { OKDialog.show(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile_invalid)) } } }) } R.id.profileswitch_date, R.id.profileswitch_name -> { val args = Bundle() args.putLong("time", (v.tag as ProfileSwitch).date) args.putInt("mode", ProfileViewerDialog.Mode.DB_PROFILE.ordinal) val pvd = ProfileViewerDialog() pvd.arguments = args pvd.show(childFragmentManager, "ProfileViewDialog") } } } init { remove.setOnClickListener(this) clone.setOnClickListener(this) remove.paintFlags = remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG clone.paintFlags = clone.paintFlags or Paint.UNDERLINE_TEXT_FLAG name.setOnClickListener(this) date.setOnClickListener(this) } } } }
agpl-3.0
6bea363e6270efcf7e509eae1f429d67
55.226519
270
0.667453
5.341732
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/KslLitShader.kt
1
13210
package de.fabmax.kool.modules.ksl import de.fabmax.kool.math.Mat3f import de.fabmax.kool.math.Vec2f import de.fabmax.kool.math.Vec4f import de.fabmax.kool.modules.ksl.blocks.* import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.BlendMode import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.TextureCube import de.fabmax.kool.pipeline.shading.AlphaMode import de.fabmax.kool.util.Color abstract class KslLitShader(cfg: LitShaderConfig, model: KslProgram) : KslShader(model, cfg.pipelineCfg) { var color: Vec4f by uniform4f(cfg.colorCfg.primaryUniform?.uniformName, cfg.colorCfg.primaryUniform?.defaultColor) var colorMap: Texture2d? by texture2d(cfg.colorCfg.primaryTexture?.textureName, cfg.colorCfg.primaryTexture?.defaultTexture) var normalMap: Texture2d? by texture2d(cfg.normalMapCfg.normalMapName, cfg.normalMapCfg.defaultNormalMap) var normalMapStrength: Float by uniform1f("uNormalMapStrength", cfg.normalMapCfg.defaultStrength) var ssaoMap: Texture2d? by texture2d("tSsaoMap", cfg.defaultSsaoMap) var ambientFactor: Vec4f by uniform4f("uAmbientColor") var ambientTextureOrientation: Mat3f by uniformMat3f("uAmbientTextureOri", Mat3f().setIdentity()) // if ambient color is image based var ambientTexture: TextureCube? by textureCube("tAmbientTexture") // if ambient color is dual image based val ambientTextures: Array<TextureCube?> by textureCubeArray("tAmbientTextures", 2) var ambientTextureWeights by uniform2f("tAmbientWeights", Vec2f.X_AXIS) init { when (val ambient = cfg.ambientColor) { is AmbientColor.Uniform -> ambientFactor = ambient.color is AmbientColor.ImageBased -> { ambientTexture = ambient.ambientTexture ambientFactor = ambient.colorFactor } is AmbientColor.DualImageBased -> { ambientFactor = ambient.colorFactor } } } sealed class AmbientColor { class Uniform(val color: Color) : AmbientColor() class ImageBased(val ambientTexture: TextureCube?, val colorFactor: Color) : AmbientColor() class DualImageBased(val colorFactor: Color) : AmbientColor() } open class LitShaderConfig { val vertexCfg = BasicVertexConfig() val colorCfg = ColorBlockConfig("baseColor") val normalMapCfg = NormalMapConfig() val pipelineCfg = PipelineConfig() val shadowCfg = ShadowConfig() var ambientColor: AmbientColor = AmbientColor.Uniform(Color(0.2f, 0.2f, 0.2f).toLinear()) var colorSpaceConversion = ColorSpaceConversion.LINEAR_TO_sRGB_HDR var maxNumberOfLights = 4 var lightStrength = 1f var isSsao = false var defaultSsaoMap: Texture2d? = null var alphaMode: AlphaMode = AlphaMode.Blend() var modelCustomizer: (KslProgram.() -> Unit)? = null fun enableSsao(ssaoMap: Texture2d? = null) { isSsao = true defaultSsaoMap = ssaoMap } fun color(block: ColorBlockConfig.() -> Unit) { colorCfg.block() } fun uniformAmbientColor(color: Color = Color(0.2f, 0.2f, 0.2f).toLinear()) { ambientColor = AmbientColor.Uniform(color) } fun imageBasedAmbientColor(ambientTexture: TextureCube? = null, colorFactor: Color = Color.WHITE) { ambientColor = AmbientColor.ImageBased(ambientTexture, colorFactor) } fun dualImageBasedAmbientColor(colorFactor: Color = Color.WHITE) { ambientColor = AmbientColor.DualImageBased(colorFactor) } fun normalMapping(block: NormalMapConfig.() -> Unit) { normalMapCfg.block() } fun pipeline(block: PipelineConfig.() -> Unit) { pipelineCfg.block() } fun shadow(block: ShadowConfig.() -> Unit) { shadowCfg.block() } fun vertices(block: BasicVertexConfig.() -> Unit) { vertexCfg.block() } } abstract class LitShaderModel<T: LitShaderConfig>(name: String) : KslProgram(name) { open fun createModel(cfg: T) { val camData = cameraData() val positionWorldSpace = interStageFloat3("positionWorldSpace") val normalWorldSpace = interStageFloat3("normalWorldSpace") val projPosition = interStageFloat4("screenUv") var tangentWorldSpace: KslInterStageVector<KslTypeFloat4, KslTypeFloat1>? = null val texCoordBlock: TexCoordAttributeBlock val shadowMapVertexStage: ShadowBlockVertexStage vertexStage { main { val uModelMat = modelMatrix() val viewProj = mat4Var(camData.viewProjMat) val modelMat = mat4Var(uModelMat.matrix) if (cfg.vertexCfg.isInstanced) { val instanceModelMat = instanceAttribMat4(Attribute.INSTANCE_MODEL_MAT.name) modelMat *= instanceModelMat } if (cfg.vertexCfg.isArmature) { val armatureBlock = armatureBlock(cfg.vertexCfg.maxNumberOfBones) armatureBlock.inBoneWeights(vertexAttribFloat4(Attribute.WEIGHTS.name)) armatureBlock.inBoneIndices(vertexAttribInt4(Attribute.JOINTS.name)) modelMat *= armatureBlock.outBoneTransform } // transform vertex attributes into world space and forward them to fragment stage val localPos = float4Value(vertexAttribFloat3(Attribute.POSITIONS.name), 1f) val localNormal = float4Value(vertexAttribFloat3(Attribute.NORMALS.name), 0f) // world position and normal are made available via ports for custom models to modify them val worldPos = float3Port("worldPos", float3Var((modelMat * localPos).xyz)) val worldNormal = float3Port("worldNormal", float3Var(normalize((modelMat * localNormal).xyz))) positionWorldSpace.input set worldPos normalWorldSpace.input set worldNormal projPosition.input set (viewProj * float4Value(worldPos, 1f)) outPosition set projPosition.input // if normal mapping is enabled, the input vertex data is expected to have a tangent attribute if (cfg.normalMapCfg.isNormalMapped) { tangentWorldSpace = interStageFloat4().apply { input set modelMat * float4Value(vertexAttribFloat4(Attribute.TANGENTS.name).xyz, 0f) } } // texCoordBlock is used by various other blocks to access texture coordinate vertex // attributes (usually either none, or Attribute.TEXTURE_COORDS but there can be more) texCoordBlock = texCoordAttributeBlock() // project coordinates into shadow map / light space shadowMapVertexStage = vertexShadowBlock(cfg.shadowCfg) { inPositionWorldSpace(worldPos) inNormalWorldSpace(worldNormal) } } } fragmentStage { val uNormalMapStrength = uniformFloat1("uNormalMapStrength") val lightData = sceneLightData(cfg.maxNumberOfLights) main { // determine main color (albedo) val colorBlock = fragmentColorBlock(cfg.colorCfg) val baseColorPort = float4Port("baseColor", colorBlock.outColor) // discard fragment output if alpha mode is mask and fragment alpha value is below cutoff value (cfg.alphaMode as? AlphaMode.Mask)?.let { mask -> `if`(baseColorPort.a lt mask.cutOff.const) { discard() } } val vertexNormal = float3Var(normalize(normalWorldSpace.output)) if (cfg.pipelineCfg.cullMethod.isBackVisible && cfg.vertexCfg.isFlipBacksideNormals) { `if`(!inIsFrontFacing) { vertexNormal *= (-1f).const3 } } // do normal map computations (if enabled) and adjust material block input normal accordingly val bumpedNormal = if (cfg.normalMapCfg.isNormalMapped) { normalMapBlock(cfg.normalMapCfg) { inTangentWorldSpace(normalize(tangentWorldSpace!!.output)) inNormalWorldSpace(vertexNormal) inStrength(uNormalMapStrength) inTexCoords(texCoordBlock.getAttributeCoords(cfg.normalMapCfg.coordAttribute)) }.outBumpNormal } else { vertexNormal } // make final normal value available to model customizer val normal = float3Port("normal", bumpedNormal) // create an array with light strength values per light source (1.0 = full strength) val shadowFactors = float1Array(lightData.maxLightCount, 1f.const) // adjust light strength values by shadow maps fragmentShadowBlock(shadowMapVertexStage, shadowFactors) val aoFactor = float1Var(1f.const) if (cfg.isSsao) { val aoMap = texture2d("tSsaoMap") val aoUv = float2Var(projPosition.output.xy / projPosition.output.w * 0.5f.const + 0.5f.const) aoFactor set sampleTexture(aoMap, aoUv).x } val irradiance = when (cfg.ambientColor) { is AmbientColor.Uniform -> uniformFloat4("uAmbientColor").rgb is AmbientColor.ImageBased -> { val ambientOri = uniformMat3("uAmbientTextureOri") val ambientTex = textureCube("tAmbientTexture") (sampleTexture(ambientTex, ambientOri * normal) * uniformFloat4("uAmbientColor")).rgb } is AmbientColor.DualImageBased -> { val ambientOri = uniformMat3("uAmbientTextureOri") val ambientTexs = textureArrayCube("tAmbientTextures", 2) val ambientWeights = uniformFloat2("tAmbientWeights") val ambientColor = float4Var(sampleTexture(ambientTexs[0], ambientOri * normal) * ambientWeights.x) `if`(ambientWeights.y gt 0f.const) { ambientColor += float4Var(sampleTexture(ambientTexs[1], ambientOri * normal) * ambientWeights.y) } (ambientColor * uniformFloat4("uAmbientColor")).rgb } } // main material block val materialColor = createMaterial( cfg = cfg, camData = camData, irradiance = irradiance, lightData = lightData, shadowFactors = shadowFactors, aoFactor = aoFactor, normal = normal, fragmentWorldPos = positionWorldSpace.output, baseColor = baseColorPort ) val materialColorPort = float4Port("materialColor", materialColor) // set fragment stage output color val outRgb = float3Var(materialColorPort.rgb) outRgb set convertColorSpace(outRgb, cfg.colorSpaceConversion) if (cfg.pipelineCfg.blendMode == BlendMode.BLEND_PREMULTIPLIED_ALPHA) { outRgb set outRgb * materialColorPort.a } when (cfg.alphaMode) { is AlphaMode.Blend -> colorOutput(outRgb, materialColorPort.a) is AlphaMode.Mask -> colorOutput(outRgb, 1f.const) is AlphaMode.Opaque -> colorOutput(outRgb, 1f.const) } } } cfg.modelCustomizer?.invoke(this) } protected abstract fun KslScopeBuilder.createMaterial( cfg: T, camData: CameraData, irradiance: KslExprFloat3, lightData: SceneLightData, shadowFactors: KslExprFloat1Array, aoFactor: KslExprFloat1, normal: KslExprFloat3, fragmentWorldPos: KslExprFloat3, baseColor: KslExprFloat4, ): KslExprFloat4 } }
apache-2.0
a93891a290da5f047b4768d4f53d133d
46.182143
128
0.579939
5.262948
false
false
false
false
Groostav/CMPT886-Proj-3
src/com/softwareleyline/Assig3Driver.kt
1
4827
package com.softwareleyline import bytecodeparser.analysis.decoders.DecodedMethodInvocationOp import bytecodeparser.analysis.stack.StackAnalyzer import javassist.ClassPool /** * Created by Geoff on 4/28/2016. */ class Assig3Driver { /** * executes the call to profile with installed instrimentation as per the provided graph. */ fun determinePathFor(targetClassName: String, callGraph: Node, callToProfile: () -> Unit) : Pair<Int, () -> Path> { val map = buildNodeMap(callGraph) val pathMap = generatePathIDByPathNodeNamesMap(map, callGraph); println("Path Id's are as follows:\n $pathMap") assert( ! isLoaded(targetClassName)) { "the class $targetClassName was already available in this class loader, aborting." } rewriteByteCode(targetClassName, map, callGraph.flattened()) val result = try { callToProfile() path; } finally { reset(); } val pathProvider : () -> Path = { pathMap.entries.single{ it.value == result }.key } return Pair(result, pathProvider); } private fun isLoaded(targetClassName: String): Boolean { val findLoadedClass = ClassLoader::class.java.getDeclaredMethod("findLoadedClass", String::class.java) findLoadedClass.isAccessible = true; val cl = ClassLoader.getSystemClassLoader(); val loaded = findLoadedClass.invoke(cl, targetClassName); return loaded != null; } private fun generatePathIDByPathNodeNamesMap(map: Map<Node, Int>, callGraph: Node) : Map<Path, Int> { val visitor = PathTrackingVisitor(map); callGraph.accept(visitor); return visitor.pathIDByNodeNames; } // builds the path-count-to-exit-by-node map // assumes there is only one zero-successor node. // if there are multiple zero-successor nodes, all of them are assumed to be 'exits'. // not sure if this algorithm still works under that condition // intuition says it should for some, if not all, possible graphs. private fun buildNodeMap(root : Node) : Map<Node, Int>{ val visitor = PathCountingVisitor() root.accept(visitor) return visitor.pathCountByNode; } private fun rewriteByteCode(target : String, nodeByPathCount : Map<Node, Int>, nodesToReWrite : Set<Node>){ pathCountByNodeName = nodeByPathCount.mapKeys { it.key.name } nodeByName = nodesToReWrite.associateBy { it.name } val pool = ClassPool.getDefault(); var clazz = pool.get(target) for(node in nodesToReWrite){ val method = clazz.getMethod(node.name, node.signature) //ok, the byte code from the resulting re-write looks like this: // LDC "A" // INVOKESTATIC com/softwareleyline/Assig3DriverKt.hit (Ljava/lang/String;)V //so what I want to know //is the first op code LDC, is the first opcodes arg "A", is the second op code INVOKESTATIC, is the target 'hit'. val analyzer = StackAnalyzer(method); val targetFrame = analyzer.analyze().map{ it.decodedOp }.take(2).last() if(targetFrame is DecodedMethodInvocationOp && targetFrame.run { declaringClassName == "com.softwareleyline.Assig3DriverKt" && name == "hit" }){ continue; } method.insertBefore("com.softwareleyline.Assig3DriverKt.hit(\"${node.name}\");") } clazz.freeze() val targetDir = javaClass.protectionDomain.codeSource.location.path clazz.writeFile(targetDir.toString()) } } //TODO this isn't thread safe. // could get some thread safety by using THreadLocal, // but that blows up if the annotated methods do their own thread hoping. // could add a UUID to the static closure, a little yucky but would do the job. var pathCountByNodeName : Map<String, Int> = emptyMap() var nodeByName : Map<String, Node> = emptyMap(); var path = 0 var lastVisitedNode = "" private fun reset(){ path = 0; lastVisitedNode = ""; pathCountByNodeName = emptyMap(); nodeByName = emptyMap(); } //well, insertBefore doesnt take a closure, annoyingly, // so im reduced to this kind of singleton. @Suppress("unused") // called via byte-code rewrite fun hit(name : String) { if(lastVisitedNode.isEmpty()){ lastVisitedNode = name; return; } if (name !in nodeByName.keys){ println("<saw hit on uninstructed method>") return; } val olderSibs = nodeByName.get(name)!!.getOlderSiblingsBy(nodeByName.get(lastVisitedNode)!!) path += olderSibs.sumBy { pathCountByNodeName[it.name]!! } lastVisitedNode = name; return; }
apache-2.0
1274c812143d18e5bd07f78c2ffe2bff
32.762238
126
0.646364
4.372283
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/services/apiresponses/ProjectsEnvelope.kt
1
3165
package com.kickstarter.services.apiresponses import android.os.Parcelable import com.kickstarter.models.Project import kotlinx.parcelize.Parcelize @Parcelize class ProjectsEnvelope private constructor( private val projects: List<Project>, private val urls: UrlsEnvelope ) : Parcelable { fun projects() = this.projects fun urls() = this.urls @Parcelize data class Builder( private var projects: List<Project> = emptyList(), private var urls: UrlsEnvelope = UrlsEnvelope.builder().build() ) : Parcelable { fun projects(projects: List<Project>) = apply { this.projects = projects } fun urls(urls: UrlsEnvelope) = apply { this.urls = urls } fun build() = ProjectsEnvelope( projects = projects, urls = urls ) } fun toBuilder() = Builder( projects = projects, urls = urls ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is ProjectsEnvelope) { equals = projects() == other.projects() && urls() == other.urls() } return equals } @Parcelize class UrlsEnvelope private constructor( private val api: ApiEnvelope ) : Parcelable { fun api() = this.api @Parcelize data class Builder( private var api: ApiEnvelope = ApiEnvelope.builder().build() ) : Parcelable { fun api(api: ApiEnvelope) = apply { this.api = api } fun build() = UrlsEnvelope( api = api ) } fun toBuilder() = Builder( api = api ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is UrlsEnvelope) { equals = api() == other.api() } return equals } @Parcelize class ApiEnvelope private constructor( private val moreProjects: String ) : Parcelable { fun moreProjects() = this.moreProjects @Parcelize data class Builder( private var moreProjects: String = "" ) : Parcelable { fun moreProjects(moreProjects: String?) = apply { this.moreProjects = moreProjects ?: "" } fun build() = ApiEnvelope( moreProjects = moreProjects ) } fun toBuilder() = Builder( moreProjects = moreProjects ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(other: Any?): Boolean { var equals = super.equals(other) if (other is ApiEnvelope) { equals = moreProjects() == other.moreProjects() } return equals } } } }
apache-2.0
5f3f6d74c8e9d7d4ecc37d88e209cd82
26.763158
106
0.52575
5.328283
false
false
false
false
ian-pi/kotlin-koans
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
1
892
package i_introduction._9_Extension_Functions import util.TODO import util.doc9 import i_introduction._9_Extension_Functions.nested_package.r fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int)
mit
f166268382fa6c684727e0864ddb83c8
26.030303
109
0.674888
3.640816
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetTempBasalStart.kt
1
1159
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag class MsgSetTempBasalStart( injector: HasAndroidInjector, private var percent: Int, private var durationInHours: Int ) : MessageBase(injector) { init { SetCommand(0x0401) //HARDCODED LIMITS if (percent < 0) percent = 0 if (percent > 200) percent = 200 if (durationInHours < 1) durationInHours = 1 if (durationInHours > 24) durationInHours = 24 AddParamByte((percent and 255).toByte()) AddParamByte((durationInHours and 255).toByte()) aapsLogger.debug(LTag.PUMPCOMM, "Temp basal start percent: $percent duration hours: $durationInHours") } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set temp basal start result: $result FAILED!!!") } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set temp basal start result: $result") } } }
agpl-3.0
ac29e4e46d012d0c062cadd074a1239a
32.142857
110
0.647972
4.457692
false
false
false
false
leafclick/intellij-community
plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightProfile.kt
1
2234
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.maddyhome.idea.copyright import com.intellij.configurationStore.SerializableScheme import com.intellij.configurationStore.serializeObjectInto import com.intellij.openapi.components.BaseState import com.intellij.openapi.options.ExternalizableScheme import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.maddyhome.idea.copyright.pattern.EntityUtil import org.jdom.Element @JvmField val DEFAULT_COPYRIGHT_NOTICE: String = EntityUtil.encode( "Copyright (c) \$today.year. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" + "Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. \n" + "Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. \n" + "Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. \n" + "Vestibulum commodo. Ut rhoncus gravida arcu. ") class CopyrightProfile @JvmOverloads constructor(profileName: String? = null) : ExternalizableScheme, BaseState(), SerializableScheme { // ugly name to preserve compatibility // must be not private because otherwise binding is not created for private accessor @Suppress("MemberVisibilityCanBePrivate") @get:OptionTag("myName") var profileName: String? by string() var notice: String? by string(DEFAULT_COPYRIGHT_NOTICE) var keyword: String? by string(EntityUtil.encode("Copyright")) var allowReplaceRegexp: String? by string() @Deprecated("use allowReplaceRegexp instead", ReplaceWith("")) var allowReplaceKeyword: String? by string() init { // otherwise will be as default value and name will be not serialized this.profileName = profileName } // ugly name to preserve compatibility @Transient override fun getName(): String = profileName ?: "" override fun setName(value: String) { profileName = value } override fun toString(): String = profileName ?: "" override fun writeScheme(): Element { val element = Element("copyright") serializeObjectInto(this, element) return element } }
apache-2.0
f1bfcdfcda165bf9ad222bb4c0ff5088
40.37037
140
0.768577
4.16791
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/migrate/dead/AbstractMigrateAllocation.kt
2
2036
package com.github.kerubistan.kerub.planner.steps.storage.migrate.dead import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.StorageCapability import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.base.AbstractUnAllocate import com.github.kerubistan.kerub.planner.steps.storage.AbstractCreateVirtualStorage abstract class AbstractMigrateAllocation : AbstractOperationalStep { abstract val sourceHost: Host abstract val targetHost: Host abstract val virtualStorage: VirtualStorageDevice abstract val sourceAllocation: VirtualStorageAllocation abstract val allocationStep: AbstractCreateVirtualStorage<out VirtualStorageAllocation, out StorageCapability> abstract val deAllocationStep: AbstractUnAllocate<*> override fun take(state: OperationalState): OperationalState = deAllocationStep.take(allocationStep.take(state.copy())) protected open fun validate() { check(allocationStep.host.id == targetHost.id) { "target allocation step is on ${allocationStep.host.id} ${allocationStep.host.address} " + " - it must be on the target server ${targetHost.id} ${targetHost.address}" } check(deAllocationStep.host.id == sourceHost.id) { "source allocation step is on ${deAllocationStep.host.id} ${deAllocationStep.host.address} " + " - it must be on the target server ${sourceHost.id} ${sourceHost.address}" } check(sourceHost.id != targetHost.id) { "source host must not be the same as target host (${sourceHost.id})" } } override fun reservations(): List<Reservation<*>> = listOf( UseHostReservation(sourceHost), UseHostReservation(targetHost) ) }
apache-2.0
613074f5bd73c476365e4c0b6cb9da03
45.295455
111
0.80501
4.359743
false
false
false
false
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/BorderSamples.kt
3
2088
/* * 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.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.unit.dp @Composable @Sampled fun BorderSample() { Text( "Text with square border", modifier = Modifier.border(4.dp, Color.Magenta).padding(10.dp) ) } @Composable @Sampled fun BorderSampleWithBrush() { val gradientBrush = Brush.horizontalGradient( colors = listOf(Color.Red, Color.Blue, Color.Green), startX = 0.0f, endX = 500.0f, tileMode = TileMode.Repeated ) Text( "Text with gradient border", modifier = Modifier.border(width = 2.dp, brush = gradientBrush, shape = CircleShape) .padding(10.dp) ) } @Composable @Sampled fun BorderSampleWithDataClass() { Text( "Text with gradient border", modifier = Modifier.border( border = BorderStroke(2.dp, Color.Blue), shape = CutCornerShape(8.dp) ).padding(10.dp) ) }
apache-2.0
467e2a71d96dcfd953bd2ee894d0a589
29.720588
92
0.723659
4.102161
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryTextWatcher.kt
1
2170
package org.thoughtcrime.securesms.mediasend.v2.text import android.text.Editable import android.text.TextWatcher import android.util.TypedValue import android.view.Gravity import android.widget.EditText import android.widget.TextView import org.signal.core.util.BreakIteratorCompat import org.signal.core.util.DimensionUnit import org.signal.core.util.EditTextUtil import org.thoughtcrime.securesms.util.doOnEachLayout class TextStoryTextWatcher private constructor(private val textView: TextView) : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { ensureProperTextSize(textView) } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit override fun afterTextChanged(s: Editable) = Unit companion object { fun ensureProperTextSize(textView: TextView) { val breakIteratorCompat = BreakIteratorCompat.getInstance() breakIteratorCompat.setText(textView.text) val length = breakIteratorCompat.countBreaks() val expectedTextSize = when { length < 50 -> 34f length < 200 -> 24f else -> 18f } if (expectedTextSize < 24f) { textView.gravity = Gravity.START } else { textView.gravity = Gravity.CENTER } textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, DimensionUnit.DP.toPixels(expectedTextSize)) if (textView !is EditText) { textView.requestLayout() } } fun install(textView: TextView) { val watcher = TextStoryTextWatcher(textView) if (textView is EditText) { EditTextUtil.addGraphemeClusterLimitFilter(textView, 700) } else { textView.doOnEachLayout { val contentHeight = textView.height - textView.paddingTop - textView.paddingBottom if (textView.layout != null && textView.layout.height > contentHeight) { val percentShown = contentHeight / textView.layout.height.toFloat() textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, DimensionUnit.DP.toPixels(18f * percentShown)) } } } textView.addTextChangedListener(watcher) } } }
gpl-3.0
dd86f8fac96b081d63a31b050f123b83
31.878788
107
0.708756
4.530271
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/AnnotatedString.kt
3
41301
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.text.AnnotatedString.Builder import androidx.compose.ui.text.AnnotatedString.Range import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap /** * The basic data structure of text with multiple styles. To construct an [AnnotatedString] you * can use [Builder]. */ @Immutable class AnnotatedString internal constructor( val text: String, val spanStyles: List<Range<SpanStyle>> = emptyList(), val paragraphStyles: List<Range<ParagraphStyle>> = emptyList(), internal val annotations: List<Range<out Any>> = emptyList() ) : CharSequence { /** * The basic data structure of text with multiple styles. To construct an [AnnotatedString] * you can use [Builder]. * * @param text the text to be displayed. * @param spanStyles a list of [Range]s that specifies [SpanStyle]s on certain portion of the * text. These styles will be applied in the order of the list. And the [SpanStyle]s applied * later can override the former styles. Notice that [SpanStyle] attributes which are null or * [androidx.compose.ui.unit.TextUnit.Unspecified] won't change the current ones. * @param paragraphStyles a list of [Range]s that specifies [ParagraphStyle]s on certain * portion of the text. Each [ParagraphStyle] with a [Range] defines a paragraph of text. * It's required that [Range]s of paragraphs don't overlap with each other. If there are gaps * between specified paragraph [Range]s, a default paragraph will be created in between. * * @throws IllegalArgumentException if [paragraphStyles] contains any two overlapping [Range]s. * @sample androidx.compose.ui.text.samples.AnnotatedStringConstructorSample * * @see SpanStyle * @see ParagraphStyle */ constructor( text: String, spanStyles: List<Range<SpanStyle>> = listOf(), paragraphStyles: List<Range<ParagraphStyle>> = listOf() ) : this(text, spanStyles, paragraphStyles, listOf()) init { var lastStyleEnd = -1 paragraphStyles.sortedBy { it.start }.fastForEach { paragraphStyle -> require(paragraphStyle.start >= lastStyleEnd) { "ParagraphStyle should not overlap" } require(paragraphStyle.end <= text.length) { "ParagraphStyle range [${paragraphStyle.start}, ${paragraphStyle.end})" + " is out of boundary" } lastStyleEnd = paragraphStyle.end } } override val length: Int get() = text.length override operator fun get(index: Int): Char = text[index] /** * Return a substring for the AnnotatedString and include the styles in the range of [startIndex] * (inclusive) and [endIndex] (exclusive). * * @param startIndex the inclusive start offset of the range * @param endIndex the exclusive end offset of the range */ override fun subSequence(startIndex: Int, endIndex: Int): AnnotatedString { require(startIndex <= endIndex) { "start ($startIndex) should be less or equal to end ($endIndex)" } if (startIndex == 0 && endIndex == text.length) return this val text = text.substring(startIndex, endIndex) return AnnotatedString( text = text, spanStyles = filterRanges(spanStyles, startIndex, endIndex), paragraphStyles = filterRanges(paragraphStyles, startIndex, endIndex), annotations = filterRanges(annotations, startIndex, endIndex) ) } /** * Return a substring for the AnnotatedString and include the styles in the given [range]. * * @param range the text range * * @see subSequence(start: Int, end: Int) */ fun subSequence(range: TextRange): AnnotatedString { return subSequence(range.min, range.max) } @Stable operator fun plus(other: AnnotatedString): AnnotatedString { return with(Builder(this)) { append(other) toAnnotatedString() } } /** * Query the string annotations attached on this AnnotatedString. * Annotations are metadata attached on the AnnotatedString, for example, a URL is a string * metadata attached on the a certain range. Annotations are also store with [Range] like the * styles. * * @param tag the tag of the annotations that is being queried. It's used to distinguish * the annotations for different purposes. * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getStringAnnotations(tag: String, start: Int, end: Int): List<Range<String>> = annotations.fastFilter { it.item is String && tag == it.tag && intersect(start, end, it.start, it.end) } as List<Range<String>> /** * Query all of the string annotations attached on this AnnotatedString. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getStringAnnotations(start: Int, end: Int): List<Range<String>> = annotations.fastFilter { it.item is String && intersect(start, end, it.start, it.end) } as List<Range<String>> /** * Query all of the [TtsAnnotation]s attached on this [AnnotatedString]. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @Suppress("UNCHECKED_CAST") fun getTtsAnnotations(start: Int, end: Int): List<Range<TtsAnnotation>> = annotations.fastFilter { it.item is TtsAnnotation && intersect(start, end, it.start, it.end) } as List<Range<TtsAnnotation>> /** * Query all of the [UrlAnnotation]s attached on this [AnnotatedString]. * * @param start the start of the query range, inclusive. * @param end the end of the query range, exclusive. * @return a list of annotations stored in [Range]. Notice that All annotations that intersect * with the range [start, end) will be returned. When [start] is bigger than [end], an empty * list will be returned. */ @ExperimentalTextApi @Suppress("UNCHECKED_CAST") fun getUrlAnnotations(start: Int, end: Int): List<Range<UrlAnnotation>> = annotations.fastFilter { it.item is UrlAnnotation && intersect(start, end, it.start, it.end) } as List<Range<UrlAnnotation>> override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is AnnotatedString) return false if (text != other.text) return false if (spanStyles != other.spanStyles) return false if (paragraphStyles != other.paragraphStyles) return false if (annotations != other.annotations) return false return true } override fun hashCode(): Int { var result = text.hashCode() result = 31 * result + spanStyles.hashCode() result = 31 * result + paragraphStyles.hashCode() result = 31 * result + annotations.hashCode() return result } override fun toString(): String { // AnnotatedString.toString has special value, it converts it into regular String // rather than debug string. return text } /** * The information attached on the text such as a [SpanStyle]. * * @param item The object attached to [AnnotatedString]s. * @param start The start of the range where [item] takes effect. It's inclusive * @param end The end of the range where [item] takes effect. It's exclusive * @param tag The tag used to distinguish the different ranges. It is useful to store custom * data. And [Range]s with same tag can be queried with functions such as [getStringAnnotations]. */ @Immutable data class Range<T>(val item: T, val start: Int, val end: Int, val tag: String) { constructor(item: T, start: Int, end: Int) : this(item, start, end, "") init { require(start <= end) { "Reversed range is not supported" } } } /** * Builder class for AnnotatedString. Enables construction of an [AnnotatedString] using * methods such as [append] and [addStyle]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderSample * * This class implements [Appendable] and can be used with other APIs that don't know about * [AnnotatedString]s: * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderAppendableSample * * @param capacity initial capacity for the internal char buffer */ class Builder(capacity: Int = 16) : Appendable { private data class MutableRange<T>( val item: T, val start: Int, var end: Int = Int.MIN_VALUE, val tag: String = "" ) { /** * Create an immutable [Range] object. * * @param defaultEnd if the end is not set yet, it will be set to this value. */ fun toRange(defaultEnd: Int = Int.MIN_VALUE): Range<T> { val end = if (end == Int.MIN_VALUE) defaultEnd else end check(end != Int.MIN_VALUE) { "Item.end should be set first" } return Range(item = item, start = start, end = end, tag = tag) } } private val text: StringBuilder = StringBuilder(capacity) private val spanStyles: MutableList<MutableRange<SpanStyle>> = mutableListOf() private val paragraphStyles: MutableList<MutableRange<ParagraphStyle>> = mutableListOf() private val annotations: MutableList<MutableRange<out Any>> = mutableListOf() private val styleStack: MutableList<MutableRange<out Any>> = mutableListOf() /** * Create an [Builder] instance using the given [String]. */ constructor(text: String) : this() { append(text) } /** * Create an [Builder] instance using the given [AnnotatedString]. */ constructor(text: AnnotatedString) : this() { append(text) } /** * Returns the length of the [String]. */ val length: Int get() = text.length /** * Appends the given [String] to this [Builder]. * * @param text the text to append */ fun append(text: String) { this.text.append(text) } @Deprecated( message = "Replaced by the append(Char) method that returns an Appendable. " + "This method must be kept around for binary compatibility.", level = DeprecationLevel.HIDDEN ) @Suppress("FunctionName", "unused") // Set the JvmName to preserve compatibility with bytecode that expects a void return type. @JvmName("append") fun deprecated_append_returning_void(char: Char) { append(char) } /** * Appends [text] to this [Builder] if non-null, and returns this [Builder]. * * If [text] is an [AnnotatedString], all spans and annotations will be copied over as well. * No other subtypes of [CharSequence] will be treated specially. For example, any * platform-specific types, such as `SpannedString` on Android, will only have their text * copied and any other information held in the sequence, such as Android `Span`s, will be * dropped. */ @Suppress("BuilderSetStyle") override fun append(text: CharSequence?): Builder { if (text is AnnotatedString) { append(text) } else { this.text.append(text) } return this } /** * Appends the range of [text] between [start] (inclusive) and [end] (exclusive) to this * [Builder] if non-null, and returns this [Builder]. * * If [text] is an [AnnotatedString], all spans and annotations from [text] between * [start] and [end] will be copied over as well. * No other subtypes of [CharSequence] will be treated specially. For example, any * platform-specific types, such as `SpannedString` on Android, will only have their text * copied and any other information held in the sequence, such as Android `Span`s, will be * dropped. * * @param start The index of the first character in [text] to copy over (inclusive). * @param end The index after the last character in [text] to copy over (exclusive). */ @Suppress("BuilderSetStyle") override fun append(text: CharSequence?, start: Int, end: Int): Builder { if (text is AnnotatedString) { append(text, start, end) } else { this.text.append(text, start, end) } return this } // Kdoc comes from interface method. override fun append(char: Char): Builder { this.text.append(char) return this } /** * Appends the given [AnnotatedString] to this [Builder]. * * @param text the text to append */ fun append(text: AnnotatedString) { val start = this.text.length this.text.append(text.text) // offset every style with start and add to the builder text.spanStyles.fastForEach { addStyle(it.item, start + it.start, start + it.end) } text.paragraphStyles.fastForEach { addStyle(it.item, start + it.start, start + it.end) } text.annotations.fastForEach { annotations.add( MutableRange(it.item, start + it.start, start + it.end, it.tag) ) } } /** * Appends the range of [text] between [start] (inclusive) and [end] (exclusive) to this * [Builder]. All spans and annotations from [text] between [start] and [end] will be copied * over as well. * * @param start The index of the first character in [text] to copy over (inclusive). * @param end The index after the last character in [text] to copy over (exclusive). */ @Suppress("BuilderSetStyle") fun append(text: AnnotatedString, start: Int, end: Int) { val insertionStart = this.text.length this.text.append(text.text, start, end) // offset every style with insertionStart and add to the builder text.getLocalSpanStyles(start, end).fastForEach { addStyle(it.item, insertionStart + it.start, insertionStart + it.end) } text.getLocalParagraphStyles(start, end).fastForEach { addStyle(it.item, insertionStart + it.start, insertionStart + it.end) } text.getLocalAnnotations(start, end).fastForEach { annotations.add( MutableRange( it.item, insertionStart + it.start, insertionStart + it.end, it.tag ) ) } } /** * Set a [SpanStyle] for the given [range]. * * @param style [SpanStyle] to be applied * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range */ fun addStyle(style: SpanStyle, start: Int, end: Int) { spanStyles.add(MutableRange(item = style, start = start, end = end)) } /** * Set a [ParagraphStyle] for the given [range]. When a [ParagraphStyle] is applied to the * [AnnotatedString], it will be rendered as a separate paragraph. * * @param style [ParagraphStyle] to be applied * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range */ fun addStyle(style: ParagraphStyle, start: Int, end: Int) { paragraphStyles.add(MutableRange(item = style, start = start, end = end)) } /** * Set an Annotation for the given [range]. * * @param tag the tag used to distinguish annotations * @param annotation the string annotation that is attached * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ fun addStringAnnotation(tag: String, annotation: String, start: Int, end: Int) { annotations.add(MutableRange(annotation, start, end, tag)) } /** * Set a [TtsAnnotation] for the given [range]. * * @param ttsAnnotation an object that stores text to speech metadata that intended for the * TTS engine. * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ @ExperimentalTextApi @Suppress("SetterReturnsThis") fun addTtsAnnotation(ttsAnnotation: TtsAnnotation, start: Int, end: Int) { annotations.add(MutableRange(ttsAnnotation, start, end)) } /** * Set a [UrlAnnotation] for the given [range]. URLs may be treated specially by screen * readers, including being identified while reading text with an audio icon or being * summarized in a links menu. * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @param start the inclusive starting offset of the range * @param end the exclusive end offset of the range * @see getStringAnnotations * @sample androidx.compose.ui.text.samples.AnnotatedStringAddStringAnnotationSample */ @ExperimentalTextApi @Suppress("SetterReturnsThis") fun addUrlAnnotation(urlAnnotation: UrlAnnotation, start: Int, end: Int) { annotations.add(MutableRange(urlAnnotation, start, end)) } /** * Applies the given [SpanStyle] to any appended text until a corresponding [pop] is * called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushSample * * @param style SpanStyle to be applied */ fun pushStyle(style: SpanStyle): Int { MutableRange(item = style, start = text.length).also { styleStack.add(it) spanStyles.add(it) } return styleStack.size - 1 } /** * Applies the given [ParagraphStyle] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushParagraphStyleSample * * @param style ParagraphStyle to be applied */ fun pushStyle(style: ParagraphStyle): Int { MutableRange(item = style, start = text.length).also { styleStack.add(it) paragraphStyles.add(it) } return styleStack.size - 1 } /** * Attach the given [annotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param tag the tag used to distinguish annotations * @param annotation the string annotation attached on this AnnotatedString * @see getStringAnnotations * @see Range */ fun pushStringAnnotation(tag: String, annotation: String): Int { MutableRange(item = annotation, start = text.length, tag = tag).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Attach the given [ttsAnnotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param ttsAnnotation an object that stores text to speech metadata that intended for the * TTS engine. * @see getStringAnnotations * @see Range */ fun pushTtsAnnotation(ttsAnnotation: TtsAnnotation): Int { MutableRange(item = ttsAnnotation, start = text.length).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Attach the given [UrlAnnotation] to any appended text until a corresponding [pop] * is called. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderPushStringAnnotationSample * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @see getStringAnnotations * @see Range */ @Suppress("BuilderSetStyle") @ExperimentalTextApi fun pushUrlAnnotation(urlAnnotation: UrlAnnotation): Int { MutableRange(item = urlAnnotation, start = text.length).also { styleStack.add(it) annotations.add(it) } return styleStack.size - 1 } /** * Ends the style or annotation that was added via a push operation before. * * @see pushStyle * @see pushStringAnnotation */ fun pop() { check(styleStack.isNotEmpty()) { "Nothing to pop." } // pop the last element val item = styleStack.removeAt(styleStack.size - 1) item.end = text.length } /** * Ends the styles or annotation up to and `including` the [pushStyle] or * [pushStringAnnotation] that returned the given index. * * @param index the result of the a previous [pushStyle] or [pushStringAnnotation] in order * to pop to * * @see pop * @see pushStyle * @see pushStringAnnotation */ fun pop(index: Int) { check(index < styleStack.size) { "$index should be less than ${styleStack.size}" } while ((styleStack.size - 1) >= index) { pop() } } /** * Constructs an [AnnotatedString] based on the configurations applied to the [Builder]. */ fun toAnnotatedString(): AnnotatedString { return AnnotatedString( text = text.toString(), spanStyles = spanStyles.fastMap { it.toRange(text.length) }, paragraphStyles = paragraphStyles.fastMap { it.toRange(text.length) }, annotations = annotations.fastMap { it.toRange(text.length) } ) } } } /** * A helper function used to determine the paragraph boundaries in [MultiParagraph]. * * It reads paragraph information from [AnnotatedString.paragraphStyles] where only some parts of * text has [ParagraphStyle] specified, and unspecified parts(gaps between specified paragraphs) * are considered as default paragraph with default [ParagraphStyle]. * For example, the following string with a specified paragraph denoted by "[]" * "Hello WorldHi!" * [ ] * The result paragraphs are "Hello World" and "Hi!". * * @param defaultParagraphStyle The default [ParagraphStyle]. It's used for both unspecified * default paragraphs and specified paragraph. When a specified paragraph's [ParagraphStyle] has * a null attribute, the default one will be used instead. */ internal fun AnnotatedString.normalizedParagraphStyles( defaultParagraphStyle: ParagraphStyle ): List<Range<ParagraphStyle>> { val length = text.length val paragraphStyles = paragraphStyles var lastOffset = 0 val result = mutableListOf<Range<ParagraphStyle>>() paragraphStyles.fastForEach { (style, start, end) -> if (start != lastOffset) { result.add(Range(defaultParagraphStyle, lastOffset, start)) } result.add(Range(defaultParagraphStyle.merge(style), start, end)) lastOffset = end } if (lastOffset != length) { result.add(Range(defaultParagraphStyle, lastOffset, length)) } // This is a corner case where annotatedString is an empty string without any ParagraphStyle. // In this case, an empty ParagraphStyle is created. if (result.isEmpty()) { result.add(Range(defaultParagraphStyle, 0, 0)) } return result } /** * Helper function used to find the [SpanStyle]s in the given paragraph range and also convert the * range of those [SpanStyle]s to paragraph local range. * * @param start The start index of the paragraph range, inclusive * @param end The end index of the paragraph range, exclusive * @return The list of converted [SpanStyle]s in the given paragraph range */ private fun AnnotatedString.getLocalSpanStyles( start: Int, end: Int ): List<Range<SpanStyle>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return spanStyles } return spanStyles.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( it.item, it.start.coerceIn(start, end) - start, it.end.coerceIn(start, end) - start ) } } /** * Helper function used to find the [ParagraphStyle]s in the given range and also convert the range * of those styles to the local range. * * @param start The start index of the range, inclusive * @param end The end index of the range, exclusive */ private fun AnnotatedString.getLocalParagraphStyles( start: Int, end: Int ): List<Range<ParagraphStyle>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return paragraphStyles } return paragraphStyles.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( it.item, it.start.coerceIn(start, end) - start, it.end.coerceIn(start, end) - start ) } } /** * Helper function used to find the annotations in the given range and also convert the range * of those annotations to the local range. * * @param start The start index of the range, inclusive * @param end The end index of the range, exclusive */ private fun AnnotatedString.getLocalAnnotations( start: Int, end: Int ): List<Range<out Any>> { if (start == end) return listOf() // If the given range covers the whole AnnotatedString, return SpanStyles without conversion. if (start == 0 && end >= this.text.length) { return annotations } return annotations.fastFilter { intersect(start, end, it.start, it.end) } .fastMap { Range( tag = it.tag, item = it.item, start = it.start.coerceIn(start, end) - start, end = it.end.coerceIn(start, end) - start ) } } /** * Helper function used to return another AnnotatedString that is a substring from [start] to * [end]. This will ignore the [ParagraphStyle]s and the resulting [AnnotatedString] will have no * [ParagraphStyle]s. * * @param start The start index of the paragraph range, inclusive * @param end The end index of the paragraph range, exclusive * @return The list of converted [SpanStyle]s in the given paragraph range */ private fun AnnotatedString.substringWithoutParagraphStyles( start: Int, end: Int ): AnnotatedString { return AnnotatedString( text = if (start != end) text.substring(start, end) else "", spanStyles = getLocalSpanStyles(start, end) ) } internal inline fun <T> AnnotatedString.mapEachParagraphStyle( defaultParagraphStyle: ParagraphStyle, crossinline block: ( annotatedString: AnnotatedString, paragraphStyle: Range<ParagraphStyle> ) -> T ): List<T> { return normalizedParagraphStyles(defaultParagraphStyle).fastMap { paragraphStyleRange -> val annotatedString = substringWithoutParagraphStyles( paragraphStyleRange.start, paragraphStyleRange.end ) block(annotatedString, paragraphStyleRange) } } /** * Create upper case transformed [AnnotatedString] * * The uppercase sometimes maps different number of characters. This function adjusts the text * style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the uppercase mapping context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for upper case mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * @return A uppercase transformed string. */ fun AnnotatedString.toUpperCase(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> str.substring(start, end).toUpperCase(localeList) } } /** * Create lower case transformed [AnnotatedString] * * The lowercase sometimes maps different number of characters. This function adjusts the text * style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the lowercase mapping context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for lower case mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * @return A lowercase transformed string. */ fun AnnotatedString.toLowerCase(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> str.substring(start, end).toLowerCase(localeList) } } /** * Create capitalized [AnnotatedString] * * The capitalization sometimes maps different number of characters. This function adjusts the * text style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the capitalization context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for capitalize mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * Note that, this locale is currently ignored since underlying Kotlin method * is experimental. * @return A capitalized string. */ fun AnnotatedString.capitalize(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> if (start == 0) { str.substring(start, end).capitalize(localeList) } else { str.substring(start, end) } } } /** * Create capitalized [AnnotatedString] * * The decapitalization sometimes maps different number of characters. This function adjusts * the text style and paragraph style ranges to transformed offset. * * Note, if the style's offset is middle of the decapitalization context, this function won't * transform the character, e.g. style starts from between base alphabet character and accent * character. * * @param localeList A locale list used for decapitalize mapping. Only the first locale is * effective. If empty locale list is passed, use the current locale instead. * Note that, this locale is currently ignored since underlying Kotlin method * is experimental. * @return A decapitalized string. */ fun AnnotatedString.decapitalize(localeList: LocaleList = LocaleList.current): AnnotatedString { return transform { str, start, end -> if (start == 0) { str.substring(start, end).decapitalize(localeList) } else { str.substring(start, end) } } } /** * The core function of [AnnotatedString] transformation. * * @param transform the transformation method * @return newly allocated transformed AnnotatedString */ internal expect fun AnnotatedString.transform( transform: (String, Int, Int) -> String ): AnnotatedString /** * Pushes [style] to the [AnnotatedString.Builder], executes [block] and then pops the [style]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderWithStyleSample * * @param style [SpanStyle] to be applied * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStyle * @see AnnotatedString.Builder.pop */ inline fun <R : Any> Builder.withStyle( style: SpanStyle, block: Builder.() -> R ): R { val index = pushStyle(style) return try { block(this) } finally { pop(index) } } /** * Pushes [style] to the [AnnotatedString.Builder], executes [block] and then pops the [style]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderWithStyleSample * * @param style [SpanStyle] to be applied * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStyle * @see AnnotatedString.Builder.pop */ inline fun <R : Any> Builder.withStyle( style: ParagraphStyle, crossinline block: Builder.() -> R ): R { val index = pushStyle(style) return try { block(this) } finally { pop(index) } } /** * Pushes an annotation to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param tag the tag used to distinguish annotations * @param annotation the string annotation attached on this AnnotatedString * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( tag: String, annotation: String, crossinline block: Builder.() -> R ): R { val index = pushStringAnnotation(tag, annotation) return try { block(this) } finally { pop(index) } } /** * Pushes an [TtsAnnotation] to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param ttsAnnotation an object that stores text to speech metadata that intended for the TTS * engine. * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( ttsAnnotation: TtsAnnotation, crossinline block: Builder.() -> R ): R { val index = pushTtsAnnotation(ttsAnnotation) return try { block(this) } finally { pop(index) } } /** * Pushes an [UrlAnnotation] to the [AnnotatedString.Builder], executes [block] and then pops the * annotation. * * @param urlAnnotation A [UrlAnnotation] object that stores the URL being linked to. * @param block function to be executed * * @return result of the [block] * * @see AnnotatedString.Builder.pushStringAnnotation * @see AnnotatedString.Builder.pop */ @ExperimentalTextApi inline fun <R : Any> Builder.withAnnotation( urlAnnotation: UrlAnnotation, crossinline block: Builder.() -> R ): R { val index = pushUrlAnnotation(urlAnnotation) return try { block(this) } finally { pop(index) } } /** * Filter the range list based on [Range.start] and [Range.end] to include ranges only in the range * of [start] (inclusive) and [end] (exclusive). * * @param start the inclusive start offset of the text range * @param end the exclusive end offset of the text range */ private fun <T> filterRanges(ranges: List<Range<out T>>, start: Int, end: Int): List<Range<T>> { require(start <= end) { "start ($start) should be less than or equal to end ($end)" } return ranges.fastFilter { intersect(start, end, it.start, it.end) }.fastMap { Range( item = it.item, start = maxOf(start, it.start) - start, end = minOf(end, it.end) - start, tag = it.tag ) } } /** * Create an AnnotatedString with a [spanStyle] that will apply to the whole text. * * @param spanStyle [SpanStyle] to be applied to whole text * @param paragraphStyle [ParagraphStyle] to be applied to whole text */ fun AnnotatedString( text: String, spanStyle: SpanStyle, paragraphStyle: ParagraphStyle? = null ): AnnotatedString = AnnotatedString( text, listOf(Range(spanStyle, 0, text.length)), if (paragraphStyle == null) listOf() else listOf(Range(paragraphStyle, 0, text.length)) ) /** * Create an AnnotatedString with a [paragraphStyle] that will apply to the whole text. * * @param paragraphStyle [ParagraphStyle] to be applied to whole text */ fun AnnotatedString( text: String, paragraphStyle: ParagraphStyle ): AnnotatedString = AnnotatedString( text, listOf(), listOf(Range(paragraphStyle, 0, text.length)) ) /** * Build a new AnnotatedString by populating newly created [AnnotatedString.Builder] provided * by [builder]. * * @sample androidx.compose.ui.text.samples.AnnotatedStringBuilderLambdaSample * * @param builder lambda to modify [AnnotatedString.Builder] */ inline fun buildAnnotatedString(builder: (Builder).() -> Unit): AnnotatedString = Builder().apply(builder).toAnnotatedString() /** * Helper function that checks if the range [baseStart, baseEnd) contains the range * [targetStart, targetEnd). * * @return true if [baseStart, baseEnd) contains [targetStart, targetEnd), vice versa. * When [baseStart]==[baseEnd] it return true iff [targetStart]==[targetEnd]==[baseStart]. */ internal fun contains(baseStart: Int, baseEnd: Int, targetStart: Int, targetEnd: Int) = (baseStart <= targetStart && targetEnd <= baseEnd) && (baseEnd != targetEnd || (targetStart == targetEnd) == (baseStart == baseEnd)) /** * Helper function that checks if the range [lStart, lEnd) intersects with the range * [rStart, rEnd). * * @return [lStart, lEnd) intersects with range [rStart, rEnd), vice versa. */ internal fun intersect(lStart: Int, lEnd: Int, rStart: Int, rEnd: Int) = maxOf(lStart, rStart) < minOf(lEnd, rEnd) || contains(lStart, lEnd, rStart, rEnd) || contains(rStart, rEnd, lStart, lEnd) private val EmptyAnnotatedString: AnnotatedString = AnnotatedString("") /** * Returns an AnnotatedString with empty text and no annotations. */ internal fun emptyAnnotatedString() = EmptyAnnotatedString
apache-2.0
c0c6895009c6b3561c4f732b49abcfdd
36.99632
101
0.63967
4.642127
false
false
false
false
GunoH/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/InlayPresentationFactory.kt
7
2511
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.hints.presentation.InlayPresentation import org.jetbrains.annotations.Contract import java.awt.Color import java.awt.Point import java.awt.event.MouseEvent import javax.swing.Icon interface InlayPresentationFactory { /** * Text that can be used for elements that ARE valid syntax if they are pasted into file. */ @Contract(pure = true) fun text(text: String) : InlayPresentation /** * Small text should be used for elements which text is not a valid syntax of the file, where this inlay is inserted. * Should be used with [container] to be aligned and properly placed * @return presentation that renders small text */ @Contract(pure = true) fun smallText(text: String) : InlayPresentation /** * @return presentation that wraps existing with borders, background and rounded corners if set * @param padding properties of space between [presentation] and border that is filled with background and has corners * @param roundedCorners properties of rounded corners. If null, corners will have right angle * @param background color of background, if null, no background will be rendered * @param backgroundAlpha value from 0 to 1 of background opacity */ @Contract(pure = true) fun container( presentation: InlayPresentation, padding: Padding? = null, roundedCorners: RoundedCorners? = null, background: Color? = null, backgroundAlpha: Float = 0.55f ) : InlayPresentation /** * @return presentation that renders icon */ @Contract(pure = true) fun icon(icon: Icon) : InlayPresentation /** * @return presentation with given mouse handlers */ @Contract(pure = true) fun mouseHandling(base: InlayPresentation, clickListener: ClickListener?, hoverListener: HoverListener?) : InlayPresentation interface HoverListener { fun onHover(event: MouseEvent, translated: Point) fun onHoverFinished() } fun interface ClickListener { fun onClick(event: MouseEvent, translated: Point) } data class Padding( val left: Int, val right: Int, val top: Int, val bottom: Int ) data class RoundedCorners( val arcWidth: Int, val arcHeight: Int ) @Contract(pure = true) fun smallScaledIcon(icon: Icon): InlayPresentation }
apache-2.0
0e7a0018a7ecac4ef4fbd967bbcc54ec
30
140
0.718439
4.548913
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHRepositoryListItem.kt
7
1922
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.cloneDialog import org.jetbrains.plugins.github.api.data.GithubRepo import org.jetbrains.plugins.github.api.data.GithubUser import org.jetbrains.plugins.github.authentication.accounts.GithubAccount sealed class GHRepositoryListItem( val account: GithubAccount ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GHRepositoryListItem if (account != other.account) return false return true } override fun hashCode(): Int { return account.hashCode() } class Repo( account: GithubAccount, val user: GithubUser, val repo: GithubRepo ) : GHRepositoryListItem(account) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as Repo if (user != other.user) return false if (repo != other.repo) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + user.hashCode() result = 31 * result + repo.hashCode() return result } } class Error(account: GithubAccount, val error: Throwable) : GHRepositoryListItem(account) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as Error if (error != other.error) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + error.hashCode() return result } } }
apache-2.0
1bf8627129095e56a3c7600d7fff23cd
24.986486
140
0.668054
4.418391
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/merge/GitMergeOption.kt
12
1471
// 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 git4idea.merge import com.intellij.openapi.util.NlsSafe import git4idea.i18n.GitBundle import org.jetbrains.annotations.Nls enum class GitMergeOption(@NlsSafe val option: String, @Nls val description: String) { NO_FF("--no-ff", GitBundle.message("merge.option.no.ff")), FF_ONLY("--ff-only", GitBundle.message("merge.option.ff.only")), SQUASH("--squash", GitBundle.message("merge.option.squash")), COMMIT_MESSAGE("-m", GitBundle.message("merge.option.msg")), NO_COMMIT("--no-commit", GitBundle.message("merge.option.no.commit")), NO_VERIFY("--no-verify", GitBundle.message("merge.option.no.verify")); fun isOptionSuitable(option: GitMergeOption): Boolean { return when (this) { NO_FF -> option !in NO_FF_INCOMPATIBLE FF_ONLY -> option !in FF_ONLY_INCOMPATIBLE SQUASH -> option !in SQUASH_INCOMPATIBLE COMMIT_MESSAGE -> option !in COMMIT_MSG_INCOMPATIBLE NO_COMMIT -> option != COMMIT_MESSAGE NO_VERIFY -> true } } companion object { private val NO_FF_INCOMPATIBLE = listOf(FF_ONLY, SQUASH) private val FF_ONLY_INCOMPATIBLE = listOf(NO_FF, SQUASH, COMMIT_MESSAGE) private val SQUASH_INCOMPATIBLE = listOf(NO_FF, FF_ONLY, COMMIT_MESSAGE) private val COMMIT_MSG_INCOMPATIBLE = listOf(FF_ONLY, SQUASH, NO_COMMIT) } }
apache-2.0
899829906fbfcce7e88e325140234c00
41.057143
140
0.698844
3.810881
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/notification/NotificationIntentService.kt
1
1814
package com.maubis.scarlet.base.notification import android.app.IntentService import android.app.NotificationManager import android.content.Context import android.content.Intent import com.maubis.scarlet.base.config.ApplicationBase import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb import com.maubis.scarlet.base.support.INTENT_KEY_ACTION import com.maubis.scarlet.base.support.INTENT_KEY_NOTE_ID import com.maubis.scarlet.base.support.utils.throwOrReturn class NotificationIntentService : IntentService("NotificationIntentService") { override fun onHandleIntent(intent: Intent?) { if (intent === null) { return } val context = applicationContext if (context === null) { return } val action = getAction(intent.getStringExtra(INTENT_KEY_ACTION)) if (action === null) { return } val noteId = intent.getIntExtra(INTENT_KEY_NOTE_ID, 0) if (noteId == 0) { return } val note = notesDb.getByID(noteId) if (note === null) { return } when (action) { NoteAction.COPY -> ApplicationBase.instance.noteActions(note).copy(context) NoteAction.SHARE -> ApplicationBase.instance.noteActions(note).share(context) NoteAction.DELETE -> { ApplicationBase.instance.noteActions(note).softDelete(context) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(note.uid) } } } private fun getAction(action: String?): NoteAction? { if (action === null) { return null } try { return NoteAction.valueOf(action) } catch (exception: Exception) { return throwOrReturn(exception, null) } } enum class NoteAction { COPY, SHARE, DELETE, } }
gpl-3.0
a5a81ce20e7e5ac03580a8666ab246b9
25.691176
111
0.697905
4.268235
false
false
false
false
jwren/intellij-community
uast/uast-common/src/com/intellij/psi/UastReferenceByUsageAdapter.kt
6
7755
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi import com.intellij.codeInsight.completion.CompletionUtilCoreImpl import com.intellij.lang.jvm.JvmModifier import com.intellij.model.search.SearchService import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Key import com.intellij.patterns.ElementPattern import com.intellij.patterns.uast.UExpressionPattern import com.intellij.patterns.uast.injectionHostUExpression import com.intellij.psi.impl.cache.CacheManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.PsiSearchHelper.SearchCostResult import com.intellij.psi.search.UsageSearchContext import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.ProcessingContext import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* internal class UastReferenceByUsageAdapter(private val usagePattern: ElementPattern<out UElement>, private val provider: UastReferenceProvider) : UastReferenceProvider(UExpression::class.java) { override fun acceptsTarget(target: PsiElement): Boolean { return provider.acceptsTarget(target) } override fun getReferencesByElement(element: UElement, context: ProcessingContext): Array<PsiReference> { val parentVariable = when (val uastParent = getOriginalUastParent(element)) { is UVariable -> uastParent is UPolyadicExpression -> uastParent.uastParent as? UVariable // support .withUastParentOrSelf() patterns else -> null } if (parentVariable == null || parentVariable.name.isNullOrEmpty() || !parentVariable.type.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { return PsiReference.EMPTY_ARRAY } val usage = getDirectVariableUsages(parentVariable).find { usage -> val refExpression = getUsageReferenceExpressionWithCache(usage, context) refExpression != null && usagePattern.accepts(refExpression, context) } ?: return PsiReference.EMPTY_ARRAY context.put(USAGE_PSI_ELEMENT, usage) return provider.getReferencesByElement(element, context) } override fun toString(): String = "uastReferenceByUsageAdapter($provider)" } @ApiStatus.Experimental fun uInjectionHostInVariable(): UExpressionPattern<*, *> = injectionHostUExpression().filter { it.uastParent is UVariable } @ApiStatus.Experimental fun uExpressionInVariable(): UExpressionPattern<*, *> = injectionHostUExpression().filter { val parent = it.uastParent parent is UVariable || (parent is UPolyadicExpression && parent.uastParent is UVariable) } private val USAGE_REFERENCE_EXPRESSION: Key<UReferenceExpression> = Key.create("uast.referenceExpressions.byUsage") private fun getUsageReferenceExpressionWithCache(usage: PsiElement, context: ProcessingContext): UReferenceExpression? { val cachedElement = context.sharedContext.get(USAGE_REFERENCE_EXPRESSION, usage) if (cachedElement != null) return cachedElement val newElement = usage.toUElementOfType<UReferenceExpression>() if (newElement != null) { context.sharedContext.put(USAGE_REFERENCE_EXPRESSION, usage, newElement) } return newElement } private fun getOriginalUastParent(element: UElement): UElement? { // Kotlin sends non-original element on completion val src = element.sourcePsi ?: return null val original = CompletionUtilCoreImpl.getOriginalElement(src) ?: src return original.toUElement()?.uastParent } private fun getDirectVariableUsages(uVar: UVariable): Sequence<PsiElement> { val variablePsi = uVar.sourcePsi ?: return emptySequence() val project = variablePsi.project if (DumbService.isDumb(project)) return emptySequence() // do not try to search in dumb mode val cachedValue = CachedValuesManager.getManager(project).getCachedValue(variablePsi, CachedValueProvider { val anchors = findDirectVariableUsages(variablePsi).map(PsiAnchor::create) Result.createSingleDependency(anchors, PsiModificationTracker.MODIFICATION_COUNT) }) return cachedValue.asSequence().mapNotNull(PsiAnchor::retrieve) } private const val MAX_FILES_TO_FIND_USAGES: Int = 5 private val STRICT_CONSTANT_NAME_PATTERN: Regex = Regex("[\\p{Upper}_0-9]+") private fun findDirectVariableUsages(variablePsi: PsiElement): Iterable<PsiElement> { val uVariable = variablePsi.toUElementOfType<UVariable>() val variableName = uVariable?.name if (variableName.isNullOrEmpty()) return emptyList() val currentFile = variablePsi.containingFile ?: return emptyList() val localUsages = findVariableUsages(variablePsi, variableName, arrayOf(currentFile)) // non-local searches are limited for real-life use cases, we do not try to find all possible usages if (uVariable is ULocalVariable || (variablePsi is PsiModifierListOwner && variablePsi.hasModifier(JvmModifier.PRIVATE)) || !STRICT_CONSTANT_NAME_PATTERN.matches(variableName)) { return localUsages } val module = ModuleUtilCore.findModuleForPsiElement(variablePsi) ?: return localUsages val uastScope = getUastScope(module.moduleScope) val searchHelper = PsiSearchHelper.getInstance(module.project) if (searchHelper.isCheapEnoughToSearch(variableName, uastScope, currentFile, null) != SearchCostResult.FEW_OCCURRENCES) { return localUsages } val cacheManager = CacheManager.getInstance(variablePsi.project) val containingFiles = cacheManager.getVirtualFilesWithWord( variableName, UsageSearchContext.IN_CODE, uastScope, true) val useScope = variablePsi.useScope val psiManager = PsiManager.getInstance(module.project) val filesToSearch = containingFiles.asSequence() .filter { useScope.contains(it) && it != currentFile.virtualFile } .mapNotNull { psiManager.findFile(it) } .sortedBy { it.virtualFile.canonicalPath } .take(MAX_FILES_TO_FIND_USAGES) .toList() .toTypedArray() val nonLocalUsages = findVariableUsages(variablePsi, variableName, filesToSearch) return ContainerUtil.concat(localUsages, nonLocalUsages) } private fun findVariableUsages(variablePsi: PsiElement, variableName: String, files: Array<PsiFile>): List<PsiElement> { if (files.isEmpty()) return emptyList() return SearchService.getInstance() .searchWord(variablePsi.project, variableName) .inScope(LocalSearchScope(files, null, true)) .buildQuery { (_, occurrencePsi, _) -> val uRef = occurrencePsi.findContaining(UReferenceExpression::class.java) val expressionType = uRef?.getExpressionType() if (expressionType != null && expressionType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { val occurrenceResolved = uRef.tryResolve() if (occurrenceResolved != null && PsiManager.getInstance(occurrencePsi.project).areElementsEquivalent(occurrenceResolved, variablePsi)) { return@buildQuery listOfNotNull(uRef.sourcePsi) } } emptyList<PsiElement>() } .findAll() .sortedWith(compareBy({ it.containingFile?.virtualFile?.canonicalPath ?: "" }, { it.textOffset })) } private fun getUastScope(originalScope: GlobalSearchScope): GlobalSearchScope { val fileTypes = UastLanguagePlugin.getInstances().map { it.language.associatedFileType }.toTypedArray() return GlobalSearchScope.getScopeRestrictedByFileTypes(originalScope, *fileTypes) }
apache-2.0
5e5c257ac23eaa224f6aaf8daa3b5264
42.573034
140
0.775758
4.843848
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/LiftReturnOrAssignmentInspection.kt
4
6486
// 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.inspections import com.intellij.codeInspection.* import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class LiftReturnOrAssignmentInspection @JvmOverloads constructor(private val skipLongExpressions: Boolean = true) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = object : KtVisitorVoid() { override fun visitExpression(expression: KtExpression) { val states = getState(expression, skipLongExpressions) ?: return if (expression.isUsedAsExpression(expression.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) return states.forEach { state -> registerProblem( expression, state.keyword, state.isSerious, when (state.liftType) { LiftType.LIFT_RETURN_OUT -> LiftReturnOutFix(state.keyword.text) LiftType.LIFT_ASSIGNMENT_OUT -> LiftAssignmentOutFix(state.keyword.text) }, state.highlightElement, state.highlightType ) } } private fun registerProblem( expression: KtExpression, keyword: PsiElement, isSerious: Boolean, fix: LocalQuickFix, highlightElement: PsiElement = keyword, highlightType: ProblemHighlightType = if (isSerious) GENERIC_ERROR_OR_WARNING else INFORMATION ) { val subject = if (fix is LiftReturnOutFix) KotlinBundle.message("text.Return") else KotlinBundle.message("text.Assignment") holder.registerProblemWithoutOfflineInformation( expression, KotlinBundle.message("0.1.be.lifted.out.of.2", subject, keyword.text), isOnTheFly, highlightType, highlightElement.textRange?.shiftRight(-expression.startOffset), fix ) } } private class LiftReturnOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("lift.return.out.fix.text.0", keyword) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val replaced = BranchedFoldingUtils.foldToReturn(descriptor.psiElement as KtExpression) replaced.findExistingEditor()?.caretModel?.moveToOffset(replaced.startOffset) } } private class LiftAssignmentOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("lift.assignment.out.fix.text.0", keyword) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { BranchedFoldingUtils.tryFoldToAssignment(descriptor.psiElement as KtExpression) } } companion object { private const val LINES_LIMIT = 15 fun getState(expression: KtExpression, skipLongExpressions: Boolean) = when (expression) { is KtWhenExpression -> getStateForWhenOrTry(expression, expression.whenKeyword, skipLongExpressions) is KtIfExpression -> getStateForWhenOrTry(expression, expression.ifKeyword, skipLongExpressions) is KtTryExpression -> expression.tryKeyword?.let { getStateForWhenOrTry(expression, it, skipLongExpressions) } else -> null } private fun getStateForWhenOrTry( expression: KtExpression, keyword: PsiElement, skipLongExpressions: Boolean ): List<LiftState>? { if (skipLongExpressions && expression.getLineCount() > LINES_LIMIT) return null if (expression.isElseIf()) return null val foldableReturns = BranchedFoldingUtils.getFoldableReturns(expression) if (foldableReturns?.isNotEmpty() == true) { val hasOtherReturns = expression.anyDescendantOfType<KtReturnExpression> { it !in foldableReturns } val isSerious = !hasOtherReturns && foldableReturns.size > 1 return foldableReturns.map { LiftState(keyword, isSerious, LiftType.LIFT_RETURN_OUT, it, INFORMATION) } + LiftState(keyword, isSerious, LiftType.LIFT_RETURN_OUT) } val assignmentNumber = BranchedFoldingUtils.getFoldableAssignmentNumber(expression) if (assignmentNumber > 0) { val isSerious = assignmentNumber > 1 return listOf(LiftState(keyword, isSerious, LiftType.LIFT_ASSIGNMENT_OUT)) } return null } enum class LiftType { LIFT_RETURN_OUT, LIFT_ASSIGNMENT_OUT } data class LiftState( val keyword: PsiElement, val isSerious: Boolean, val liftType: LiftType, val highlightElement: PsiElement = keyword, val highlightType: ProblemHighlightType = if (isSerious) GENERIC_ERROR_OR_WARNING else INFORMATION ) } }
apache-2.0
a0e2121825c5cbf9f68488a1490cfae3
46.343066
158
0.659729
5.576956
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/laf/MouseDragSelectionEventHandler.kt
2
2355
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.ui.laf import com.intellij.openapi.util.SystemInfo import java.awt.Component import java.awt.event.MouseEvent internal class MouseDragSelectionEventHandler(private val mouseDraggedOriginal: (MouseEvent) -> Unit) { var isNativeSelectionEnabled = false fun mouseDragged(e: MouseEvent) { when (dragSelectionMode()) { DragSelectionMode.ORIGINAL -> mouseDraggedOriginal(e) DragSelectionMode.WINDOWS -> mouseDraggedWindows(e) DragSelectionMode.UNIX -> mouseDraggedUnix(e) } } private fun dragSelectionMode(): DragSelectionMode = when { !isNativeSelectionEnabled -> DragSelectionMode.ORIGINAL SystemInfo.isWindows -> DragSelectionMode.WINDOWS else -> DragSelectionMode.UNIX } private enum class DragSelectionMode { ORIGINAL, WINDOWS, UNIX } private fun mouseDraggedWindows(e: MouseEvent) { // Pretend the mouse always moves horizontally, // as this is what Windows users generally expect. mouseDragged(e, e.x, e.sourceHeight?.div(2) ?: e.y) } private fun mouseDraggedUnix(e: MouseEvent) { val height = e.sourceHeight val width = e.sourceWidth if (height == null || width == null) { // A next-to-impossible scenario, fall back to original behavior. mouseDraggedOriginal(e) return } // In case of the mouse cursor moved above or below the component, // imitate fast selection by moving the mouse cursor far away horizontally either left or right. val normalizedY = height / 2 when { e.y < 0 -> mouseDragged(e, -OMG_ITS_OVER_9000, normalizedY) e.y > height -> mouseDragged(e, width + OMG_ITS_OVER_9000, normalizedY) else -> mouseDragged(e, e.x, e.y) } } private val MouseEvent.sourceWidth: Int? get() = (source as? Component)?.width private val MouseEvent.sourceHeight: Int? get() = (source as? Component)?.height private fun mouseDragged(e: MouseEvent, x: Int, y: Int) { val originalX = e.x val originalY = e.y e.translatePoint(x - originalX, y - originalY) try { mouseDraggedOriginal(e) } finally { e.translatePoint(originalX - x, originalY - y) } } } private const val OMG_ITS_OVER_9000 = 9999
apache-2.0
e3609c15ee475cf319ec11c6e082ecc2
31.260274
120
0.695117
4.13884
false
false
false
false
GunoH/intellij-community
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/MarkdownTableColumnShrinkTest.kt
3
3081
// 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.intellij.plugins.markdown.editor.tables import com.intellij.testFramework.LightPlatformCodeInsightTestCase import com.intellij.testFramework.RegistryKeyRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @Suppress("MarkdownIncorrectTableFormatting") class MarkdownTableColumnShrinkTest: LightPlatformCodeInsightTestCase() { @get:Rule val rule = RegistryKeyRule("markdown.tables.editing.support.enable", true) @Test fun `test right after cell content`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret> | asd | """.trimIndent(), """ | none | none | |------|------| | a<caret> | asd | """.trimIndent() ) } @Test fun `test between spaces on the right side`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret> | asd | """.trimIndent(), """ | none | none | |------|------| | a <caret> | asd | """.trimIndent() ) } @Test fun `test just before right pipe`() { // language=Markdown doTest( """ | none | none | |-------|------| | a <caret>| asd | """.trimIndent(), """ | none | none | |------|------| | a <caret>| asd | """.trimIndent() ) } @Test fun `test right before cell content`() { // language=Markdown doTest( """ | none | none | |-------|------| | <caret>a | asd | """.trimIndent(), """ | none | none | |------|------| | <caret>a | asd | """.trimIndent() ) } @Test fun `test just after left pipe`() { // language=Markdown doTest( """ | none | none | |-------|------| | <caret> a | asd | """.trimIndent(), """ | none | none | |------|------| |<caret> a | asd | """.trimIndent() ) } @Test fun `test in separator`() { doTest( """ | none | none | |---<caret>----|------| | a | asd | """.trimIndent(), """ | none | none | |--<caret>----|------| | a | asd | """.trimIndent() ) } @Test fun `test in separator with colon`() { doTest( """ | none | none | |:<caret>------|------| | a | asd | """.trimIndent(), """ | none | none | |<caret>------|------| | a | asd | """.trimIndent() ) } private fun doTest(content: String, expected: String, count: Int = 1) { TableTestUtils.runWithChangedSettings(project) { configureFromFileText("some.md", content) repeat(count) { backspace() } checkResultByText(expected) } } }
apache-2.0
97184eddcaf979ab319145d28bc860e0
20.545455
158
0.468679
4.075397
false
true
false
false
smmribeiro/intellij-community
platform/testFramework/src/com/intellij/testFramework/propertyBased/PsiIndexConsistencyTester.kt
5
8235
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework.propertyBased import com.intellij.lang.Language import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater import com.intellij.openapi.util.Conditions import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.intellij.util.FileContentUtilCore import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileBasedIndexImpl import com.intellij.util.ref.GCUtil import org.junit.Assert.fail object PsiIndexConsistencyTester { val commonRefs: List<RefKind> = listOf(RefKind.PsiFileRef, RefKind.DocumentRef, RefKind.DirRef, RefKind.AstRef(null), RefKind.StubRef(null), RefKind.GreenStubRef(null)) val commonActions: List<Action> = listOf(Action.Commit, Action.FlushIndexes, Action.Gc, Action.ReparseFile, Action.FilePropertiesChanged, Action.ReloadFromDisk, Action.Reformat, Action.PostponedFormatting, Action.RenamePsiFile, Action.RenameVirtualFile, Action.Save) fun refActions(refs: List<RefKind>): Iterable<Action> = refs.flatMap { listOf(Action.LoadRef(it), Action.ClearRef(it)) } fun runActions(model: Model, vararg actions: Action) { WriteCommandAction.runWriteCommandAction(model.project) { try { actions.forEach { it.performAction(model) } } finally { try { Action.Save.performAction(model) model.vFile.delete(this) } catch (e: Throwable) { e.printStackTrace() } } } } open class Model(val vFile: VirtualFile, val fixture: CodeInsightTestFixture) { val refs = hashMapOf<RefKind, Any?>() val project = fixture.project!! fun findPsiFile(language: Language? = null) = findViewProvider().let { vp -> vp.getPsi(language ?: vp.baseLanguage) }!! private fun findViewProvider() = PsiManager.getInstance(project).findViewProvider(vFile)!! fun getDocument() = FileDocumentManager.getInstance().getDocument(vFile)!! fun isCommitted(): Boolean { val document = FileDocumentManager.getInstance().getCachedDocument(vFile) return document == null || PsiDocumentManager.getInstance(project).isCommitted(document) } open fun onCommit() {} open fun onReload() {} open fun onSave() {} } interface Action { fun performAction(model: Model) abstract class SimpleAction: Action { override fun toString(): String = javaClass.simpleName } object FlushIndexes: SimpleAction() { override fun performAction(model: Model) { (FileBasedIndex.getInstance() as FileBasedIndexImpl).flushIndexes() } } object Gc: SimpleAction() { override fun performAction(model: Model) = GCUtil.tryGcSoftlyReachableObjects() } object Commit: SimpleAction() { override fun performAction(model: Model) { PsiDocumentManager.getInstance(model.project).commitAllDocuments() model.onCommit() } } object Save: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileDocumentManager.getInstance().saveAllDocuments() model.onSave() } } object PostponedFormatting: SimpleAction() { override fun performAction(model: Model) = PostprocessReformattingAspect.getInstance(model.project).doPostponedFormatting() } object ReparseFile : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileContentUtilCore.reparseFiles(model.vFile) } } object FilePropertiesChanged : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PushedFilePropertiesUpdater.getInstance(model.project).filePropertiesChanged(model.vFile, Conditions.alwaysTrue()) } } object ReloadFromDisk : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PsiManager.getInstance(model.project).reloadFromDisk(model.findPsiFile()) model.onReload() if (model.isCommitted()) { model.onCommit() } } } object RenameVirtualFile: SimpleAction() { override fun performAction(model: Model) { model.vFile.rename(this, model.vFile.nameWithoutExtension + "1." + model.vFile.extension) } } object RenamePsiFile: SimpleAction() { override fun performAction(model: Model) { val newName = model.vFile.nameWithoutExtension + "1." + model.vFile.extension model.findPsiFile().name = newName assert(model.findPsiFile().name == newName) assert(model.vFile.name == newName) } } object Reformat: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) Commit.performAction(model) CodeStyleManager.getInstance(model.project).reformat(model.findPsiFile()) } } data class LoadRef(val kind: RefKind): Action { override fun performAction(model: Model) { val oldValue = model.refs[kind] val newValue = kind.loadRef(model) if (oldValue !== null && newValue !== null && oldValue !== newValue) { kind.checkDuplicates(oldValue, newValue) } model.refs[kind] = newValue } } data class ClearRef(val kind: RefKind): Action { override fun performAction(model: Model) { model.refs.remove(kind) } } data class SetDocumentText(val text: String): Action { override fun performAction(model: Model) { PostponedFormatting.performAction(model) model.getDocument().setText(text) } } data class SetFileText(val text: String): Action { override fun performAction(model: Model) { PostponedFormatting.performAction(model) Save.performAction(model) VfsUtil.saveText(model.vFile, text) } } } abstract class RefKind { abstract fun loadRef(model: Model): Any? open fun checkDuplicates(oldValue: Any, newValue: Any) { if (oldValue is PsiElement && oldValue.isValid && newValue is PsiElement) { fail("Duplicate PSI elements: $oldValue and $newValue") } } object PsiFileRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile() } object DocumentRef : RefKind() { override fun loadRef(model: Model): Any? = model.getDocument() } object DirRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile().containingDirectory } data class AstRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile(language).node } data class StubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).stubTree } data class GreenStubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).greenStubTree } } }
apache-2.0
13be1d498592a0bd92740934e34f8da8
37.485981
140
0.655616
4.931138
false
false
false
false
ak80/BinaryDataParser
bdp-processor/src/main/java/org/ak80/bdp/CoreProcessor.kt
1
5483
package org.ak80.bdp import org.ak80.bdp.annotations.MappedByte import org.ak80.bdp.annotations.MappedEnum import org.ak80.bdp.annotations.MappedFlag import org.ak80.bdp.annotations.MappedWord import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.tools.Diagnostic /** * Processor for annotations */ interface BdpProcessor { /** * Init the processor with the environment * * @param processingEnvironment the processing environment */ fun init(processingEnvironment: ProcessingEnvironment) /** * Process an annotation * * @param annotations the registered annotations * @param roundEnv the information for this round */ fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean } /** * Core Processor * * @property mappedClasses the registry of mapped classes * @property generator the generator that generated and writes Java files */ class CoreProcessor(private val mappedClasses: MappedClasses, private val generator: Generator) : BdpProcessor { var fieldMappingAnnotations = setOf( MappedByte::class.java, MappedWord::class.java, MappedFlag::class.java, MappedEnum::class.java ) var processingEnvironment: ProcessingEnvironment? = null private val messager: Messager by lazy { processingEnvironment?.messager ?: throw IllegalStateException("the CoreProcessor was not initialized") } override fun init(processingEnvironment: ProcessingEnvironment) { this.processingEnvironment = processingEnvironment } override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean { var exit: Boolean; for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedByte::class.java)) { exit = processMappedField(annotatedElement) if (exit) break } for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedWord::class.java)) { exit = processMappedField(annotatedElement) if (exit) break } for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedFlag::class.java)) { exit = processMappedField(annotatedElement) if (exit) break } for (annotatedElement in roundEnv.getElementsAnnotatedWith(MappedEnum::class.java)) { exit = processMappedField(annotatedElement) if (exit) break } for (byteMappedClass in mappedClasses.getClasses()) { generator.generateFor(byteMappedClass) } mappedClasses.clear() return true } private fun processMappedField(element: Element): Boolean { if (element.kind != ElementKind.FIELD) { error(element, "Only fields can be annotated with mapping annotation"); return true; } val mappedClass = getMappedClass(element) val fieldName = element.simpleName.toString() val typeMirror = element.asType() val fieldType = getType(typeMirror) val annotation = getAnnotation(element) mappedClass.addMapping(fieldName, fieldType, annotation) return false } private fun getType(typeMirror: TypeMirror): String { if (typeMirror.kind.equals(TypeKind.DECLARED)) { return typeMirror.toString(); } else { return typeMirror.kind.name.toString() } } private fun getMappedClass(element: Element): MappedClass { val classFullName = getClassFullName(element) val classSimpleName = getClassSimpleName(element) val classPackage = getClassPackage(classFullName, classSimpleName) val parentType = element.enclosingElement.asType() return mappedClasses.get(classSimpleName, classPackage, parentType) } private fun getAnnotation(element: Element): Annotation { var annotations: Set<Annotation> = mutableSetOf() for (annotationClass in fieldMappingAnnotations) { var annotation = element.getAnnotation(annotationClass) if (annotation != null) { annotations = annotations.plus(annotation) } } if (annotations.size > 1) { throw IllegalStateException("Only one mapping annotation allowed for element ${element.simpleName} but found: $annotations") } return annotations.single() } private fun getClassFullName(element: Element): String { val parentTypeElement = element.enclosingElement as TypeElement return parentTypeElement.qualifiedName.toString() } private fun getClassSimpleName(element: Element): String { val parentTypeElement = element.enclosingElement as TypeElement return parentTypeElement.simpleName.toString() } private fun getClassPackage(fullName: String, simpleName: String): String { return fullName.subSequence(0, fullName.length - simpleName.length - 1).toString() } private fun error(element: Element, message: String) { messager.printMessage(Diagnostic.Kind.ERROR, message, element) } }
apache-2.0
36ecc569bf77a69ffdfb0ca71172f3cb
32.851852
136
0.692686
5.192235
false
false
false
false
junkdog/transducers-kotlin
src/test/kotlin/samples/samples.kt
1
3643
package samples import net.onedaybeard.transducers.* typealias Sample = org.junit.Test class Samples { @Sample fun branch_a() { intoList(xf = copy<Int>() + branch(test = { it % 4 == 0 }, xfTrue = map { i: Int -> i * 100 }, xfFalse = map { i: Int -> i / 4 } + distinct() + map(Int::toString)), input = (1..9) ) assertEquals listOf("0", 400, 400, "1", 800, 800, "2") } @Sample fun collect_a() { // using collect for sorting input transduce(xf = map { i: Int -> i / 3 } + distinct() + collect(sort = { a, b -> a.compareTo(b) * -1 }), rf = { _, input -> input.toList() }, init = listOf<Int>(), input = (0..20) ) assertEquals listOf(6, 5, 4, 3, 2, 1, 0) } @Sample fun collect_b() { // collecting into a set, releasing sorted iterable transduce(xf = map { i: Int -> i / 3 } + collect(sort = { a, b -> a.compareTo(b) * -1 }, collector = { mutableSetOf<Int>() }), rf = { _, input -> input.toList() }, init = listOf<Int>(), input = (0..20) ) assertEquals listOf(6, 5, 4, 3, 2, 1, 0) } @Sample fun mux_a() { listOf(xf = mux(isEven@ // labels only for readability { i: Int -> i % 2 == 0 } wires map { i: Int -> i * 100 } + filter { it != 400 }, leetify@ { i: Int -> i == 3 } wires map { _: Int -> 1337 } + collect() + // releases on final result cat()), input = (0..9) ) assertEquals listOf(0, 200, 600, 800, 1337) } @Sample fun mux_b() { // promiscuous = true: input goes through all applicable transducers listOf(xf = mux({ i: Int -> i % 1 == 0 } wires map { i: Int -> i / 2 } + distinct(), { i: Int -> i % 2 == 0 } wires map { it }, { i: Int -> i % 3 == 0 } wires map { i: Int -> i * 100 } + copy(), promiscuous = true), input = (0..6) ) assertEquals listOf(0, 0, 0, 0, // input: 0 // input: 1 1, 2, // input: 2 300, 300, // input: 3 2, 4, // input: 4 // input: 5 3, 6, 600, 600) // input: 6 } @Sample fun sum_a() { // collecting single result into list listOf(xf = filter<Int> { 4 > it } + sum<Int>(), input = (0..10) ) assertEquals listOf(1 + 2 + 3) } @Sample fun sum_b() { val xf = filter { i: Int -> i % 5 == 0 } + sum { i: Int -> i / 5 } transduce(xf = xf, rf = { result, input -> result + input }, init = 0, input = (0..20) ) assertEquals (1 + 2 + 3 + 4) } }
apache-2.0
c2aa6161a75a4deeb1ba3e5bee44a3d6
34.038462
77
0.335987
4.531095
false
false
false
false
seventhroot/elysium
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/card/CharacterCardCommand.kt
1
3324
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.card import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Character card command. * Displays the character card of the active character of either the player running the command or the specified player. */ class CharacterCardCommand(private val plugin: RPKCharactersBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender is Player) { if (sender.hasPermission("rpkit.characters.command.character.card.self")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) var minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (sender.hasPermission("rpkit.characters.command.character.card.other")) { if (args.isNotEmpty()) { val bukkitPlayer = plugin.server.getPlayer(args[0]) if (bukkitPlayer != null) { minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) } } } if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { val senderMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (senderMinecraftProfile != null) { character.showCharacterCard(senderMinecraftProfile) } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["no-permission-character-card-self"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } return true } }
apache-2.0
5d5757136fe1b8ddfb70e7a60c8b47c6
45.816901
128
0.640794
5.485149
false
false
false
false
seventhroot/elysium
bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/database/table/RPKAuctionTable.kt
1
11466
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.auctions.bukkit.database.table import com.rpkit.auctions.bukkit.RPKAuctionsBukkit import com.rpkit.auctions.bukkit.auction.RPKAuction import com.rpkit.auctions.bukkit.auction.RPKAuctionImpl import com.rpkit.auctions.bukkit.database.jooq.rpkit.Tables.RPKIT_AUCTION import com.rpkit.auctions.bukkit.database.jooq.rpkit.Tables.RPKIT_BID import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.core.bukkit.util.toByteArray import com.rpkit.core.bukkit.util.toItemStack import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider import org.bukkit.Location import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the auction table. */ class RPKAuctionTable(database: Database, private val plugin: RPKAuctionsBukkit): Table<RPKAuction>(database, RPKAuction::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_auction.id.enabled")) { database.cacheManager.createCache("rpk-auctions-bukkit.rpkit_auction.id", CacheConfigurationBuilder .newCacheConfigurationBuilder(Int::class.javaObjectType, RPKAuction::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_auction.id.size"))).build()) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_AUCTION) .column(RPKIT_AUCTION.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_AUCTION.ITEM, SQLDataType.BLOB) .column(RPKIT_AUCTION.CURRENCY_ID, SQLDataType.INTEGER) .column(RPKIT_AUCTION.WORLD, SQLDataType.VARCHAR(256)) .column(RPKIT_AUCTION.X, SQLDataType.DOUBLE) .column(RPKIT_AUCTION.Y, SQLDataType.DOUBLE) .column(RPKIT_AUCTION.Z, SQLDataType.DOUBLE) .column(RPKIT_AUCTION.YAW, SQLDataType.DOUBLE) .column(RPKIT_AUCTION.PITCH, SQLDataType.DOUBLE) .column(RPKIT_AUCTION.CHARACTER_ID, SQLDataType.INTEGER) .column(RPKIT_AUCTION.DURATION, SQLDataType.BIGINT) .column(RPKIT_AUCTION.END_TIME, SQLDataType.BIGINT) .column(RPKIT_AUCTION.START_PRICE, SQLDataType.INTEGER) .column(RPKIT_AUCTION.BUY_OUT_PRICE, SQLDataType.INTEGER) .column(RPKIT_AUCTION.NO_SELL_PRICE, SQLDataType.INTEGER) .column(RPKIT_AUCTION.MINIMUM_BID_INCREMENT, SQLDataType.INTEGER) .column(RPKIT_AUCTION.BIDDING_OPEN, SQLDataType.TINYINT.length(1)) .constraints( constraint("pk_rpkit_auction").primaryKey(RPKIT_AUCTION.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.4.0") } } override fun insert(entity: RPKAuction): Int { database.create .insertInto( RPKIT_AUCTION, RPKIT_AUCTION.ITEM, RPKIT_AUCTION.CURRENCY_ID, RPKIT_AUCTION.WORLD, RPKIT_AUCTION.X, RPKIT_AUCTION.Y, RPKIT_AUCTION.Z, RPKIT_AUCTION.YAW, RPKIT_AUCTION.PITCH, RPKIT_AUCTION.CHARACTER_ID, RPKIT_AUCTION.DURATION, RPKIT_AUCTION.END_TIME, RPKIT_AUCTION.START_PRICE, RPKIT_AUCTION.BUY_OUT_PRICE, RPKIT_AUCTION.NO_SELL_PRICE, RPKIT_AUCTION.MINIMUM_BID_INCREMENT, RPKIT_AUCTION.BIDDING_OPEN ) .values( entity.item.toByteArray(), entity.currency.id, entity.location?.world?.name, entity.location?.x, entity.location?.y, entity.location?.z, entity.location?.yaw?.toDouble(), entity.location?.pitch?.toDouble(), entity.character.id, entity.duration, entity.endTime, entity.startPrice, entity.buyOutPrice, entity.noSellPrice, entity.minimumBidIncrement, if (entity.isBiddingOpen) 1.toByte() else 0.toByte() ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKAuction) { database.create .update(RPKIT_AUCTION) .set(RPKIT_AUCTION.ITEM, entity.item.toByteArray()) .set(RPKIT_AUCTION.CURRENCY_ID, entity.currency.id) .set(RPKIT_AUCTION.WORLD, entity.location?.world?.name) .set(RPKIT_AUCTION.X, entity.location?.x) .set(RPKIT_AUCTION.Y, entity.location?.y) .set(RPKIT_AUCTION.Z, entity.location?.z) .set(RPKIT_AUCTION.YAW, entity.location?.yaw?.toDouble()) .set(RPKIT_AUCTION.PITCH, entity.location?.pitch?.toDouble()) .set(RPKIT_AUCTION.CHARACTER_ID, entity.character.id) .set(RPKIT_AUCTION.DURATION, entity.duration) .set(RPKIT_AUCTION.END_TIME, entity.endTime) .set(RPKIT_AUCTION.START_PRICE, entity.startPrice) .set(RPKIT_AUCTION.BUY_OUT_PRICE, entity.buyOutPrice) .set(RPKIT_AUCTION.NO_SELL_PRICE, entity.noSellPrice) .set(RPKIT_AUCTION.MINIMUM_BID_INCREMENT, entity.minimumBidIncrement) .set(RPKIT_AUCTION.BIDDING_OPEN, if (entity.isBiddingOpen) 1.toByte() else 0.toByte()) .where(RPKIT_AUCTION.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) } override fun get(id: Int): RPKAuction? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select( RPKIT_AUCTION.ITEM, RPKIT_AUCTION.CURRENCY_ID, RPKIT_AUCTION.WORLD, RPKIT_AUCTION.X, RPKIT_AUCTION.Y, RPKIT_AUCTION.Z, RPKIT_AUCTION.YAW, RPKIT_AUCTION.PITCH, RPKIT_AUCTION.CHARACTER_ID, RPKIT_AUCTION.DURATION, RPKIT_AUCTION.END_TIME, RPKIT_AUCTION.START_PRICE, RPKIT_AUCTION.BUY_OUT_PRICE, RPKIT_AUCTION.NO_SELL_PRICE, RPKIT_AUCTION.MINIMUM_BID_INCREMENT, RPKIT_AUCTION.BIDDING_OPEN ) .from(RPKIT_AUCTION) .where(RPKIT_AUCTION.ID.eq(id)) .fetchOne() ?: return null val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class) val currencyId = result.get(RPKIT_AUCTION.CURRENCY_ID) val currency = currencyProvider.getCurrency(currencyId) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val characterId = result.get(RPKIT_AUCTION.CHARACTER_ID) val character = characterProvider.getCharacter(characterId) if (currency != null && character != null) { val auction = RPKAuctionImpl( plugin, id, result.get(RPKIT_AUCTION.ITEM).toItemStack(), currency, Location( plugin.server.getWorld(result.get(RPKIT_AUCTION.WORLD)), result.get(RPKIT_AUCTION.X), result.get(RPKIT_AUCTION.Y), result.get(RPKIT_AUCTION.Z), result.get(RPKIT_AUCTION.YAW).toFloat(), result.get(RPKIT_AUCTION.PITCH).toFloat() ), character, result.get(RPKIT_AUCTION.DURATION), result.get(RPKIT_AUCTION.END_TIME), result.get(RPKIT_AUCTION.START_PRICE), result.get(RPKIT_AUCTION.BUY_OUT_PRICE), result.get(RPKIT_AUCTION.NO_SELL_PRICE), result.get(RPKIT_AUCTION.MINIMUM_BID_INCREMENT), result.get(RPKIT_AUCTION.BIDDING_OPEN) == 1.toByte() ) cache?.put(id, auction) return auction } else { val bidTable = database.getTable(RPKBidTable::class) database.create .select(RPKIT_BID.ID) .from(RPKIT_BID) .where(RPKIT_BID.AUCTION_ID.eq(id)) .fetch() .map { it[RPKIT_BID.ID] } .mapNotNull { bidId -> bidTable[bidId] } .forEach { bid -> bidTable.delete(bid) } database.create .deleteFrom(RPKIT_AUCTION) .where(RPKIT_AUCTION.ID.eq(id)) .execute() return null } } } /** * Gets a list of all auctions * * @return A list containing all auctions */ fun getAll(): List<RPKAuction> { val results = database.create .select(RPKIT_AUCTION.ID) .from(RPKIT_AUCTION) .fetch() return results.map { result -> get(result.get(RPKIT_AUCTION.ID)) }.filterNotNull() } override fun delete(entity: RPKAuction) { for (bid in entity.bids) { database.getTable(RPKBidTable::class).delete(bid) } database.create .deleteFrom(RPKIT_AUCTION) .where(RPKIT_AUCTION.ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
d558d92c74abe74bbef40e90f8c70ff3
44.145669
130
0.540206
4.872928
false
false
false
false
Orgmir/budget-app-android
app/src/main/kotlin/pt/orgmir/budgetandroid/localstorage/wrapers/BAExpense.kt
1
1395
package pt.orgmir.budgetandroid.localstorage.wrapers import io.realm.Realm import pt.orgmir.budgetandroid.BAApplication import pt.orgmir.budgetandroid.localstorage.model.BAExpenseModel /** * Created by Luis Ramos on 7/26/2015. */ public class BAExpense(public var model: BAExpenseModel) { public constructor() : this(BAExpenseModel()) companion object{ public fun findAll() : List<BAExpense> { val findAll = BAApplication.realm.where(javaClass<BAExpenseModel>()).findAll() return findAll.map { BAExpense(it) } } public fun findAllOrderedByDate() : List<BAExpense> { val findAll = BAApplication.realm.where(javaClass<BAExpenseModel>()).findAllSorted("createdAt", false) return findAll.map { BAExpense(it) } } } public var id : String get() = model.getId() set(value) { model.setId(value) } public var value : Double get() = model.getValue() set(value) { model.setValue(value) } public var category: String get() = model.getCategory() set(value) { model.setCategory(value) } public var title : String get() = model.getTitle() set(value) { model.setTitle(value)} public var description : String? get() = model.getDescription() set(value) { model.setDescription(description) } /** * QUERIES */ public fun create() { saveData { model = it.copyToRealm(model) } } }
mit
d2296a7d7ee76007ed13f0deba2b5b3c
23.928571
108
0.678136
3.864266
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/sceDmac.kt
1
989
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.hle.error.* import com.soywiz.kpspemu.mem.* class sceDmac(emulator: Emulator) : SceModule(emulator, "sceDmac", 0x40010011, "lowio.prx", "sceLowIO_Driver") { fun _sceDmacMemcpy(src: Int, dst: Int, size: Int): Int { if (size == 0) return SceKernelErrors.ERROR_INVALID_SIZE if (src == 0 || dst == 0) return SceKernelErrors.ERROR_INVALID_POINTER mem.copy(dst, src, size) return 0 } fun sceDmacMemcpy(src: Int, dst: Int, size: Int): Int = _sceDmacMemcpy(src, dst, size) fun sceDmacTryMemcpy(src: Int, dst: Int, size: Int): Int = _sceDmacMemcpy(src, dst, size) override fun registerModule() { registerFunctionInt("sceDmacMemcpy", 0x617F3FE6, since = 150) { sceDmacMemcpy(int, int, int) } registerFunctionInt("sceDmacTryMemcpy", 0xD97F94D8, since = 150) { sceDmacTryMemcpy(int, int, int) } } }
mit
cc28d74aa54e0a1791f34f0977f50927
40.208333
112
0.682508
3.410345
false
false
false
false
lisawray/groupie
example/src/main/java/com/xwray/groupie/example/MainActivity.kt
2
11973
package com.xwray.groupie.example import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.os.Handler import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.xwray.groupie.ExpandableGroup import com.xwray.groupie.Group import com.xwray.groupie.GroupieAdapter import com.xwray.groupie.OnItemClickListener import com.xwray.groupie.OnItemLongClickListener import com.xwray.groupie.Section import com.xwray.groupie.example.core.InfiniteScrollListener import com.xwray.groupie.example.core.Prefs import com.xwray.groupie.example.core.SettingsActivity import com.xwray.groupie.example.core.decoration.CarouselItemDecoration import com.xwray.groupie.example.core.decoration.DebugItemDecoration import com.xwray.groupie.example.core.decoration.SwipeTouchCallback import com.xwray.groupie.example.item.* import com.xwray.groupie.groupiex.plusAssign import kotlinx.android.synthetic.main.activity_main.* const val INSET_TYPE_KEY = "inset_type" const val INSET = "inset" class MainActivity : AppCompatActivity() { private val groupAdapter = GroupieAdapter() private lateinit var groupLayoutManager: GridLayoutManager private val prefs by lazy { Prefs.get(this) } private val handler = Handler() private val gray: Int by lazy { ContextCompat.getColor(this, R.color.background) } private val betweenPadding: Int by lazy { resources.getDimensionPixelSize(R.dimen.padding_small) } private val rainbow200: IntArray by lazy { resources.getIntArray(R.array.rainbow_200) } private val rainbow500: IntArray by lazy { resources.getIntArray(R.array.rainbow_500) } private val infiniteLoadingSection = Section(HeaderItem(R.string.infinite_loading)) private val swipeSection = Section(HeaderItem(R.string.swipe_to_delete)) private val dragSection = Section(HeaderItem(R.string.drag_to_reorder)) // Normally there's no need to hold onto a reference to this list, but for demonstration // purposes, we'll shuffle this list and post an update periodically private val updatableItems: ArrayList<UpdatableItem> by lazy { ArrayList<UpdatableItem>().apply { for (i in 1..12) { add(UpdatableItem(rainbow200[i], i)) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.refresh) { recreateAdapter() return true } return super.onOptionsItemSelected(item) } // Hold a reference to the updating group, so we can, well, update it private var updatingGroup = Section() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) groupAdapter.apply { setOnItemClickListener(onItemClickListener) setOnItemLongClickListener(onItemLongClickListener) spanCount = 12 } recreateAdapter() groupLayoutManager = GridLayoutManager(this, groupAdapter.spanCount).apply { spanSizeLookup = groupAdapter.spanSizeLookup } recyclerView.apply { layoutManager = groupLayoutManager addItemDecoration(HeaderItemDecoration(gray, betweenPadding)) addItemDecoration(InsetItemDecoration(gray, betweenPadding)) addItemDecoration(DebugItemDecoration(context)) adapter = groupAdapter addOnScrollListener(object : InfiniteScrollListener(groupLayoutManager) { override fun onLoadMore(currentPage: Int) { val color = rainbow200[currentPage % rainbow200.size] for (i in 0..4) { infiniteLoadingSection.add(CardItem(color)) } } }) } ItemTouchHelper(touchCallback).attachToRecyclerView(recyclerView) fab.setOnClickListener { startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) } prefs.registerListener(onSharedPrefChangeListener) } private fun recreateAdapter() { groupAdapter.clear() val groups = createGroups() if (prefs.useAsync) { groupAdapter.updateAsync(groups) } else { groupAdapter.update(groups) } } private fun createGroups(): List<Group> = mutableListOf<Group>().apply { // Full bleed item this += Section(HeaderItem(R.string.full_bleed_item)).apply { add(FullBleedCardItem(R.color.purple_200)) } // Update in place group this += Section().apply { val updatingHeader = HeaderItem( R.string.updating_group, R.string.updating_group_subtitle, R.drawable.shuffle, onShuffleClicked) setHeader(updatingHeader) updatingGroup.update(updatableItems) add(updatingGroup) } // Expandable group val expandableHeaderItem = ExpandableHeaderItem(R.string.expanding_group, R.string.expanding_group_subtitle) this += ExpandableGroup(expandableHeaderItem).apply { for (i in 0..1) { add(CardItem(rainbow200[1])) } } // Reordering a Section of Expandable Groups val section = Section(HeaderItem(R.string.reorderable_section)) val swappableExpandableGroup = mutableListOf<ExpandableGroup>() var colorIndex = 0 for (i in 0..2) { val header = ExpandableHeaderItem(R.string.reorderable_item_title, R.string.reorderable_item_subtitle) val group = ExpandableGroup(header).apply { val numChildren= i * 2 // groups will continue to grow by 2 for (j in 0..numChildren) { add(CardItem(rainbow200[colorIndex])) if (colorIndex + 1 >= rainbow200.size) { colorIndex = 0 } else { colorIndex += 1 } } } header.clickListener = { swappableExpandableGroup.remove(group) swappableExpandableGroup.add(group) section.update(swappableExpandableGroup) } swappableExpandableGroup.add(group) } section.addAll(swappableExpandableGroup) this += section // Columns fun makeColumnGroup(): ColumnGroup { val columnItems = ArrayList<ColumnItem>() for (i in 1..5) { // First five items are red -- they'll end up in a vertical column columnItems += ColumnItem(rainbow200[0], i) } for (i in 6..10) { // Next five items are pink columnItems += ColumnItem(rainbow200[1], i) } return ColumnGroup(columnItems) } this += Section(HeaderItem(R.string.vertical_columns)).apply { add(makeColumnGroup()) } // Group showing even spacing with multiple columns this += Section(HeaderItem(R.string.multiple_columns)).apply { for (i in 0..11) { add(SmallCardItem(rainbow200[5])) } } // Swipe to delete (with add button in header) swipeSection.clear() for (i in 0..2) { swipeSection += SwipeToDeleteItem(rainbow200[i]) } this += swipeSection dragSection.clear() for (i in 0..4) { dragSection += DraggableItem(rainbow500[i]) } this += dragSection // Horizontal carousel fun makeCarouselItem(): CarouselItem { val carouselDecoration = CarouselItemDecoration(gray, betweenPadding) val carouselAdapter = GroupieAdapter() for (i in 0..29) { carouselAdapter += CarouselCardItem(rainbow200[7]) } return CarouselItem(carouselDecoration, carouselAdapter) } this += Section(HeaderItem(R.string.carousel, R.string.carousel_subtitle)).apply { add(makeCarouselItem()) } // Update with payload this += Section(HeaderItem(R.string.update_with_payload, R.string.update_with_payload_subtitle)).apply { rainbow500.indices.forEach { i -> add(HeartCardItem(rainbow200[i], i.toLong()) { item, favorite -> // Pretend to make a network request handler.postDelayed({ // Network request was successful! item.setFavorite(favorite) item.notifyChanged(FAVORITE) }, 1000) }) } } // Infinite loading section this += infiniteLoadingSection } private val onItemClickListener = OnItemClickListener { item, _ -> if (item is CardItem && !TextUtils.isEmpty(item.text)) { Toast.makeText(this@MainActivity, item.text, Toast.LENGTH_SHORT).show() } } private val onItemLongClickListener = OnItemLongClickListener { item, _ -> if (item is CardItem && !item.text.isNullOrBlank()) { Toast.makeText(this@MainActivity, "Long clicked: " + item.text, Toast.LENGTH_SHORT).show() return@OnItemLongClickListener true } false } private val onShuffleClicked = View.OnClickListener { ArrayList(updatableItems).apply { shuffle() updatingGroup.update(this) } // You can also do this by forcing a change with payload recyclerView.post { recyclerView.invalidateItemDecorations() } } override fun onDestroy() { prefs.unregisterListener(onSharedPrefChangeListener) super.onDestroy() } private val touchCallback: SwipeTouchCallback by lazy { object : SwipeTouchCallback() { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { val item = groupAdapter.getItem(viewHolder.bindingAdapterPosition) val targetItem = groupAdapter.getItem(target.bindingAdapterPosition) val dragItems = dragSection.groups var targetIndex = dragItems.indexOf(targetItem) dragItems.remove(item) // if item gets moved out of the boundary if (targetIndex == -1) { targetIndex = if (target.bindingAdapterPosition < viewHolder.bindingAdapterPosition) { 0 } else { dragItems.size - 1 } } dragItems.add(targetIndex, item) dragSection.update(dragItems) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val item = groupAdapter.getItem(viewHolder.bindingAdapterPosition) // Change notification to the adapter happens automatically when the section is // changed. swipeSection.remove(item) } } } private val onSharedPrefChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> recreateAdapter() } }
mit
bd31d5ce0856401590e1b7e8128ff1b5
36.415625
116
0.62215
5.143041
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/InfoGroupFragment.kt
1
7916
package org.eurofurence.connavigator.ui.fragments import android.animation.LayoutTransition import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.RecyclerView import com.joanzapata.iconify.widget.IconTextView import io.reactivex.disposables.Disposables import org.eurofurence.connavigator.BuildConfig import org.eurofurence.connavigator.R import org.eurofurence.connavigator.database.HasDb import org.eurofurence.connavigator.database.lazyLocateDb import org.eurofurence.connavigator.ui.views.NonScrollingLinearLayout import org.eurofurence.connavigator.util.delegators.view import org.eurofurence.connavigator.util.extensions.* import org.eurofurence.connavigator.util.v2.compatAppearance import org.eurofurence.connavigator.util.v2.plus import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.UI import java.util.* /** * Renders an info group element and displays it's individual items */ class InfoGroupFragment : DisposingFragment(), HasDb, AnkoLogger { inner class InfoItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val layout: LinearLayout by view("layout") val name: TextView by view("title") } inner class DataAdapter : RecyclerView.Adapter<InfoItemViewHolder>() { override fun getItemCount() = infoItems.count() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = InfoItemViewHolder(UI { SingleInfoUi().createView(this) }.view) override fun onBindViewHolder(holder: InfoItemViewHolder, position: Int) { val item = infoItems[position] holder.name.text = item.title holder.layout.setOnClickListener { val action = InfoListFragmentDirections.actionInfoListFragmentToInfoItemFragment(item.id.toString(), BuildConfig.CONVENTION_IDENTIFIER) findNavController().navigate(action) } holder.layout.setOnLongClickListener { context?.let { context?.share(item.shareString(it), "Share Info") } != null } } } override val db by lazyLocateDb() private val infoGroupId: UUID? get() = UUID.fromString(arguments!!.getString("id")) private val infoGroup by lazy { db.knowledgeGroups[infoGroupId] } val infoItems by lazy { db.knowledgeEntries.items .filter { it.knowledgeGroupId == infoGroupId } .sortedBy { it.order } } val ui = InfoGroupUi() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = UI { ui.createView(this) }.view override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fillUi() db.subscribe { fillUi() } .collectOnDestroyView() } private fun fillUi() { ui.apply { infoGroup?.let { title.text = it.name mainIcon.text = it.fontAwesomeIconCharacterUnicodeAddress?.toUnicode() ?: "" description.text = it.description groupLayout.setOnClickListener { setDropdown() } recycler.apply { adapter = DataAdapter() layoutManager = NonScrollingLinearLayout(activity) itemAnimator = DefaultItemAnimator() } } ?: run { warn { "Info group initialized on non-existent ID." } groupLayout.visibility = View.GONE } } } private fun setDropdown() { if (ui.recyclerLayout.visibility == View.GONE) { ui.recyclerLayout.visibility = View.VISIBLE ui.dropdownCaret.text = "{fa-chevron-up 24sp}" } else { ui.recyclerLayout.visibility = View.GONE ui.dropdownCaret.text = "{fa-chevron-down 24sp}" } } } class InfoGroupUi : AnkoComponent<Fragment> { lateinit var title: TextView lateinit var description: TextView lateinit var recycler: RecyclerView lateinit var groupLayout: LinearLayout lateinit var dropdownCaret: IconTextView lateinit var mainIcon: TextView lateinit var recyclerLayout: LinearLayout override fun createView(ui: AnkoContext<Fragment>) = with(ui) { verticalLayout { groupLayout = linearLayout { isClickable = true weightSum = 20F backgroundResource = R.color.lightBackground layoutTransition = LayoutTransition().apply { enableTransitionType(LayoutTransition.APPEARING) enableTransitionType(LayoutTransition.CHANGE_APPEARING) enableTransitionType(LayoutTransition.CHANGING) } verticalLayout { mainIcon = fontAwesomeTextView { gravity = Gravity.CENTER textColor = ContextCompat.getColor(context, R.color.primary) textSize = 24f }.lparams(matchParent, matchParent) }.lparams(dip(0), matchParent) { weight = 4F } verticalLayout { verticalPadding = dip(15) title = textView { textResource = R.string.misc_title compatAppearance = android.R.style.TextAppearance_DeviceDefault_Large } description = textView { textResource = R.string.misc_description compatAppearance = android.R.style.TextAppearance_DeviceDefault_Small } }.lparams(dip(0), wrapContent) { weight = 13F } verticalLayout { dropdownCaret = fontAwesomeView { gravity = Gravity.CENTER text = "{fa-chevron-down 24sp}" }.lparams(matchParent, matchParent) }.lparams(dip(0), matchParent) { weight = 3F } } recyclerLayout = verticalLayout { recycler = recycler { }.lparams(matchParent, wrapContent) visibility = View.GONE } } } } class SingleInfoUi : AnkoComponent<Fragment> { override fun createView(ui: AnkoContext<Fragment>) = with(ui) { linearLayout { topPadding = dip(10) bottomPadding = dip(10) id = R.id.layout weightSum = 20F lparams(matchParent, wrapContent) view { // Sneaky view to pad stuff }.lparams(dip(0), wrapContent) { weight = 4F } textView { textResource = R.string.misc_name id = R.id.title compatAppearance = android.R.style.TextAppearance_DeviceDefault_Medium textColor = ContextCompat.getColor(context, R.color.textBlack) }.lparams(dip(0), wrapContent) { weight = 13F } fontAwesomeView { text = "{fa-chevron-right 24sp}" gravity = Gravity.CENTER }.lparams(dip(0), matchParent) { weight = 3F } } } }
mit
d16e2ae78b98cfd35e2f9770fed548b9
35.150685
151
0.596261
5.284379
false
false
false
false
Petrulak/kotlin-mvp-clean-architecture
app/src/main/java/com/petrulak/cleankotlin/platform/extensions/RxExtensions.kt
1
3983
package com.petrulak.cleankotlin.platform.extensions import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.observers.DisposableCompletableObserver import io.reactivex.observers.DisposableObserver import io.reactivex.observers.DisposableSingleObserver import io.reactivex.schedulers.Schedulers import io.reactivex.subscribers.DisposableSubscriber import timber.log.Timber fun <T1> subscribeOnIo(observable: Flowable<T1>, onNext: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(object : DisposableSubscriber<T1>() { override fun onNext(t: T1) { onNext.invoke(t) } override fun onComplete() { } override fun onError(e: Throwable) { Timber.e(e) onError.invoke(e) } }) } fun <T1> subscribeOnIo(observable: Observable<T1>, onNext: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(object : DisposableObserver<T1>() { override fun onNext(t: T1) { onNext.invoke(t) } override fun onComplete() { } override fun onError(e: Throwable) { onError.invoke(e) } }) } fun <T1> subscribeOnIo(single: Single<T1>, onSuccess: (T1) -> Unit = {}, onError: (Throwable) -> Unit = {}): Disposable { return single .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(object : DisposableSingleObserver<T1>() { override fun onSuccess(t: T1) { onSuccess.invoke(t) } override fun onError(e: Throwable) { Timber.e(e) onError.invoke(e) } }) } fun subscribeOnIo(completable: Completable, onCompleted: () -> Unit, onError: (Throwable) -> Unit) { return completable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : DisposableCompletableObserver() { override fun onComplete() { onCompleted.invoke() } override fun onError(e: Throwable) { onError.invoke(e) } }) } fun <T> getDisposableSingleObserver(onNext: (T) -> Unit, onError: (Throwable) -> Unit = {}): DisposableSingleObserver<T> { return object : DisposableSingleObserver<T>() { override fun onSuccess(value: T) { onNext.invoke(value) } override fun onError(e: Throwable) { Timber.e(e, "DisposableSingleObserver error") onError.invoke(e) } } } fun <T> getDisposableCompletableObserver(onComplete: () -> Unit, onError: (Throwable) -> Unit = {}): DisposableCompletableObserver { return object : DisposableCompletableObserver() { override fun onComplete() { onComplete.invoke() } override fun onError(e: Throwable) { Timber.e(e, "DisposableCompletableObserver error") onError.invoke(e) } } } fun <T> getDisposableSubscriber(onNext: (T) -> Unit, onError: (Throwable) -> Unit = {}): DisposableSubscriber<T> { return object : DisposableSubscriber<T>() { override fun onNext(value: T) { onNext.invoke(value) } override fun onComplete() { } override fun onError(e: Throwable) { Timber.e(e, "DisposableSubscriber error") onError.invoke(e) } } }
mit
26525494ff82f545b11b6305287a5bf9
28.731343
132
0.601557
4.691402
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/entity/messenger/Message.kt
2
1360
package me.proxer.library.entity.messenger import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.ProxerDateItem import me.proxer.library.entity.ProxerIdItem import me.proxer.library.enums.Device import me.proxer.library.enums.MessageAction import java.util.Date /** * Entity representing a single message. * * @property conferenceId The id of the associated [Conference]. * @property userId The id of the associated user. * @property username The username of the author. * @property message The actual content of the message. * @property action The action of this message. If the action is not [MessageAction.NONE], * [message] returns associated information, like the name of the user, performing the action. * @property device The device, the message was sent from. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class Message( @Json(name = "message_id") override val id: String, @Json(name = "conference_id") val conferenceId: String, @Json(name = "user_id") val userId: String, @Json(name = "username") val username: String, @Json(name = "message") val message: String, @Json(name = "action") val action: MessageAction, @Json(name = "timestamp") override val date: Date, @Json(name = "device") val device: Device ) : ProxerIdItem, ProxerDateItem
gpl-3.0
f02cf281b98dca3cade321bbcf8260c4
39
94
0.740441
3.874644
false
false
false
false
hhariri/mark-code
src/main/kotlin/com/hadihariri/markcode/KotlinLanguage.kt
1
1042
package com.hadihariri.markcode import com.hadihariri.markcode.ExampleLanguage import com.hadihariri.markcode.startsWithAny object KotlinLanguage : ExampleLanguage { override fun getPackageName(dirName: String, fileName: String): String { if (fileName[0] in '0'..'9') return dirName + ".ex" + fileName.substringAfter('.').removeSuffix(".kt").replace('.', '_') return dirName + "." + fileName.removeSuffix(".kt") } override fun formatPackageStatement(packageName: String) = "package $packageName" override fun formatImportStatement(importName: String) = "import $importName" override fun formatMainFunction(fileName: String) = "fun main(args: Array<String>) {" override fun formatMainFunctionIndent() = " " override fun formatMainFunctionEnd() = "}" override fun hasAnyDeclarations(lines: Collection<String>) = lines.any { it.startsWithAny("fun", "inline fun", "operator fun", "class", "enum class", "interface", "open class", "data class", "abstract class") } }
mit
074d3dc0bed29b7e2c49f155988bb5f9
42.458333
143
0.695777
4.491379
false
false
false
false
RocketChat/Rocket.Chat.Android
emoji/src/main/java/chat/rocket/android/emoji/internal/db/EmojiDatabase.kt
2
1301
package chat.rocket.android.emoji.internal.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import chat.rocket.android.emoji.Emoji import chat.rocket.android.emoji.EmojiDao @Database(entities = [Emoji::class], version = 1) @TypeConverters(StringListConverter::class) abstract class EmojiDatabase : RoomDatabase() { abstract fun emojiDao(): EmojiDao companion object : SingletonHolder<EmojiDatabase, Context>({ Room.databaseBuilder(it.applicationContext, EmojiDatabase::class.java, "emoji.db") .fallbackToDestructiveMigration() .build() }) } open class SingletonHolder<out T, in A>(creator: (A) -> T) { private var creator: ((A) -> T)? = creator @kotlin.jvm.Volatile private var instance: T? = null fun getInstance(arg: A): T { val i = instance if (i != null) { return i } return synchronized(this) { val i2 = instance if (i2 != null) { i2 } else { val created = creator!!(arg) instance = created creator = null created } } } }
mit
95dac60b543073d9707efa97697c8605
26.104167
64
0.605688
4.47079
false
false
false
false
thomasnield/kotlin-statistics
src/test/kotlin/org/nield/kotlinstatistics/NumberStatisticsTest.kt
1
11415
package org.nield.kotlinstatistics import org.junit.Assert.assertTrue import org.junit.Test import java.math.BigDecimal import java.util.* class NumberStatisticsTest { val doubleVector = sequenceOf(1.0, 3.0, 5.0, 11.0) val intVector = doubleVector.map { it.toInt() } val longVector = intVector.map { it.toLong() } val bigDecimalVector = doubleVector.map(BigDecimal::valueOf) val groups = sequenceOf("A","A","B", "B") @Test fun descriptiveStatistics() { assertTrue(doubleVector.descriptiveStatistics.mean == 5.0) assertTrue(intVector.descriptiveStatistics.mean == 5.0) assertTrue(longVector.descriptiveStatistics.mean == 5.0) assertTrue(bigDecimalVector.descriptiveStatistics.mean == 5.0) assertTrue(doubleVector.descriptiveStatistics.min == 1.0) assertTrue(intVector.descriptiveStatistics.min == 1.0) assertTrue(longVector.descriptiveStatistics.min == 1.0) assertTrue(bigDecimalVector.descriptiveStatistics.min == 1.0) assertTrue(doubleVector.descriptiveStatistics.max == 11.0) assertTrue(intVector.descriptiveStatistics.max == 11.0) assertTrue(longVector.descriptiveStatistics.max == 11.0) assertTrue(bigDecimalVector.descriptiveStatistics.max == 11.0) assertTrue(doubleVector.descriptiveStatistics.size == 4L) assertTrue(intVector.descriptiveStatistics.size == 4L) assertTrue(longVector.descriptiveStatistics.size == 4L) assertTrue(bigDecimalVector.descriptiveStatistics.size == 4L) } @Test fun descriptiveBy() { groups.zip(doubleVector).descriptiveStatisticsBy() .let { assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0) } groups.zip(intVector).descriptiveStatisticsBy() .let { assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0) } groups.zip(longVector).descriptiveStatisticsBy() .let { assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0) } groups.zip(bigDecimalVector).descriptiveStatisticsBy() .let { assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0) } groups.zip(doubleVector).descriptiveStatisticsBy( keySelector = { it.first }, valueSelector = {it.second} ) .let { assertTrue(it["A"]!!.mean == 2.0 && it["B"]!!.mean == 8.0) } } @Test fun geometricMean() { doubleVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) } intVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) } longVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) } bigDecimalVector.asSequence().geometricMean().let { assertTrue(it == 3.584024634215721) } } @Test fun median() { doubleVector.asSequence().median().let { assertTrue(it == 4.0) } doubleVector.asSequence().take(3).median().let { assertTrue(it == 3.0) } intVector.asSequence().median().let { assertTrue(it == 4.0) } longVector.asSequence().median().let { assertTrue(it == 4.0) } bigDecimalVector.asSequence().median().let { assertTrue(it == 4.0) } } @Test fun medianBy() { groups.zip(doubleVector).medianBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(intVector).medianBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(longVector).medianBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(bigDecimalVector).medianBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(doubleVector).medianBy( keySelector = {it.first}, valueSelector = {it.second} ) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } } @Test fun percentile() { doubleVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) } intVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) } longVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) } bigDecimalVector.asSequence().percentile(50.0).let { assertTrue(it == 4.0) } } @Test fun percentileBy() { groups.zip(doubleVector).percentileBy(50.0) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(intVector).percentileBy(50.0) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(longVector).percentileBy(50.0) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(bigDecimalVector).percentileBy(50.0) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } groups.zip(bigDecimalVector).percentileBy( percentile = 50.0, keySelector = {it.first}, valueSelector = {it.second} ) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 8.0) } } @Test fun variance() { val r = 18.666666666666668 doubleVector.asSequence().variance().let { assertTrue(it == r) } intVector.asSequence().variance().let { assertTrue(it == r) } longVector.asSequence().variance().let { assertTrue(it == r) } bigDecimalVector.asSequence().variance().let { assertTrue(it == r) } } @Test fun varianceBy() { groups.zip(doubleVector).varianceBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0) } groups.zip(intVector).varianceBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0) } groups.zip(longVector).varianceBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0) } groups.zip(bigDecimalVector).varianceBy() .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0) } groups.zip(bigDecimalVector).varianceBy( keySelector = {it.first}, valueSelector = {it.second} ) .let { assertTrue(it["A"]!! == 2.0 && it["B"]!! == 18.0) } } @Test fun sumOfSquares() { val r = 156.0 doubleVector.asSequence().sumOfSquares().let { assertTrue(it == r) } intVector.asSequence().sumOfSquares().let { assertTrue(it == r) } longVector.asSequence().sumOfSquares().let { assertTrue(it == r) } bigDecimalVector.asSequence().sumOfSquares().let { assertTrue(it == r) } } @Test fun standardDeviation() { val r = 4.320493798938574 doubleVector.asSequence().standardDeviation().let { assertTrue(it == r) } intVector.asSequence().standardDeviation().let { assertTrue(it == r) } longVector.asSequence().standardDeviation().let { assertTrue(it == r) } bigDecimalVector.asSequence().standardDeviation().let { assertTrue(it == r) } } @Test fun standardDeviationBy() { val r = mapOf("A" to 1.4142135623730951, "B" to 4.242640687119285) groups.zip(doubleVector).standardDeviationBy() .let { assertTrue(it == r) } groups.zip(intVector).standardDeviationBy() .let { assertTrue(it == r) } groups.zip(longVector).standardDeviationBy() .let { assertTrue(it == r) } groups.zip(bigDecimalVector).standardDeviationBy() .let { assertTrue(it == r) } groups.zip(bigDecimalVector).standardDeviationBy( keySelector = {it.first}, valueSelector = {it.second} ) .let { assertTrue(it == r) } } @Test fun normalize() { val r = doubleArrayOf( -0.9258200997725514, -0.4629100498862757, 0.0, 1.3887301496588271 ) doubleVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) } intVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) } longVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) } bigDecimalVector.asSequence().normalize().let { assertTrue(Arrays.equals(it, r)) } } @Test fun kurtosis() { val r = 1.4999999999999947 assertTrue(doubleVector.kurtosis == r) assertTrue(intVector.kurtosis == r) assertTrue(longVector.kurtosis == r) assertTrue(bigDecimalVector.kurtosis == r) } @Test fun skewness() { val r = 1.1903401282789945 assertTrue(doubleVector.skewness == r) assertTrue(intVector.skewness == r) assertTrue(longVector.skewness == r) assertTrue(bigDecimalVector.skewness == r) } @Test fun geometricMeanBy() { val r = mapOf("A" to 1.7320508075688774, "B" to 7.416198487095664) groups.zip(doubleVector).geometricMeanBy() .let { assertTrue(it == r) } groups.zip(intVector).geometricMeanBy() .let { assertTrue(it == r) } groups.zip(longVector).geometricMeanBy() .let { assertTrue(it == r) } groups.zip(bigDecimalVector).geometricMeanBy() .let { assertTrue(it == r) } groups.zip(bigDecimalVector).geometricMeanBy( keySelector = {it.first}, valueSelector = {it.second} ) .let { assertTrue(it == r) } } @Test fun simpleRegression() { doubleVector.zip(doubleVector.map { it * 2 }) .simpleRegression() .let { assertTrue(it.slope == 2.0) } intVector.zip(intVector.map { it * 2 }) .simpleRegression() .let { assertTrue(it.slope == 2.0) } longVector.zip(longVector.map { it * 2 }) .simpleRegression() .let { assertTrue(it.slope == 2.0) } bigDecimalVector.zip(bigDecimalVector.map { it * BigDecimal.valueOf(2L) }) .simpleRegression() .let { assertTrue(it.slope == 2.0) } intVector.zip(intVector.map { it * 2 }) .simpleRegression( xSelector = {it.first}, ySelector = {it.second} ) .let { assertTrue(it.slope == 2.0) } } }
apache-2.0
8181e0b4cdd62a14aa9e1d4883296830
32.875371
97
0.512659
4.457243
false
true
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/integration/DefaultDataTypeDescriptorSet.kt
1
4586
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api.integration import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.FieldType import java.time.Duration import java.time.Instant import kotlin.reflect.KClass /** Default implementation of [DataTypeDescriptorSet]. */ class DefaultDataTypeDescriptorSet(private val dtds: Set<DataTypeDescriptor>) : DataTypeDescriptorSet { private val dtdsByName: Map<String, DataTypeDescriptor> = dtds.flatMap { collectNestedDataTypeDescriptors(it) }.associateBy { it.name } private val dtdsByKClass: Map<KClass<*>, DataTypeDescriptor> = dtdsByName.values.associateBy { it.cls } private fun collectNestedDataTypeDescriptors(dtd: DataTypeDescriptor): List<DataTypeDescriptor> { return dtd.innerTypes.fold(listOf(dtd)) { acc, t -> acc + collectNestedDataTypeDescriptors(t) } } override fun getOrNull(name: String): DataTypeDescriptor? = dtdsByName[name] override tailrec fun findFieldTypeOrThrow( dtd: DataTypeDescriptor, accessPath: List<String>, ): FieldType { require(accessPath.isNotEmpty()) { "Cannot find field type for empty access path." } val field = accessPath[0] val fieldType = requireNotNull(dtd.fields[field]) { "Field \"$field\" not found in ${dtd.name}" } if (accessPath.size == 1) return fieldType val nextDtd = requireNotNull(findDataTypeDescriptor(fieldType)) return findFieldTypeOrThrow(nextDtd, accessPath.drop(1)) } override fun findDataTypeDescriptor(fieldType: FieldType): DataTypeDescriptor? { return when (fieldType) { is FieldType.Array -> findDataTypeDescriptor(fieldType.itemFieldType) is FieldType.List -> findDataTypeDescriptor(fieldType.itemFieldType) is FieldType.Nullable -> findDataTypeDescriptor(fieldType.itemFieldType) is FieldType.Nested -> getOrNull(fieldType.name) is FieldType.Reference -> getOrNull(fieldType.name) FieldType.Boolean, FieldType.Byte, FieldType.ByteArray, FieldType.Char, FieldType.Double, FieldType.Duration, FieldType.Float, FieldType.Instant, FieldType.Integer, FieldType.Long, FieldType.Short, FieldType.String, is FieldType.Enum, is FieldType.Opaque, // We would need to know which item within the tuple we are interested in. is FieldType.Tuple -> null } } override fun findDataTypeDescriptor(cls: KClass<*>): DataTypeDescriptor? = dtdsByKClass[cls] override fun fieldTypeAsClass(fieldType: FieldType): Class<*> { return when (fieldType) { FieldType.Boolean -> Boolean::class.javaObjectType FieldType.Byte -> Byte::class.javaObjectType FieldType.ByteArray -> ByteArray::class.java FieldType.Char -> Char::class.javaObjectType FieldType.Double -> Double::class.javaObjectType FieldType.Duration -> Duration::class.java FieldType.Float -> Float::class.javaObjectType FieldType.Instant -> Instant::class.java FieldType.Integer -> Int::class.javaObjectType FieldType.Long -> Long::class.javaObjectType FieldType.Short -> Short::class.javaObjectType FieldType.String -> String::class.java is FieldType.Enum -> Enum::class.java is FieldType.Array -> Array::class.java is FieldType.List -> List::class.java is FieldType.Reference -> this[fieldType.name].cls.java is FieldType.Nested -> this[fieldType.name].cls.java is FieldType.Opaque -> Class.forName(fieldType.name) is FieldType.Nullable -> fieldTypeAsClass(fieldType.itemFieldType) is FieldType.Tuple -> // TODO(b/208662121): Tuples could be android.util.Pair or kotlin.Pair (or similar) throw IllegalArgumentException("Tuple is too ambiguous to return a field type.") } } override fun toSet(): Set<DataTypeDescriptor> = dtds }
apache-2.0
ca3e1d507792b5ee2450c0f04bf8335d
39.584071
99
0.728522
4.604418
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/ui/activity/netease/PersonalFmActivity.kt
1
7979
package tech.summerly.quiet.ui.activity.netease import android.graphics.Color import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.SeekBar import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_personal_fm.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.toast import org.jetbrains.anko.uiThread import tech.summerly.quiet.R import tech.summerly.quiet.bus.FetchMusicErrorEvent import tech.summerly.quiet.bus.OnMusicLikedEvent import tech.summerly.quiet.data.netease.NeteaseCloudMusicApi import tech.summerly.quiet.extensions.* import tech.summerly.quiet.extensions.lib.GlideApp import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.module.common.bus.RxBus import tech.summerly.quiet.module.common.bus.event.MusicPlayerEvent import tech.summerly.quiet.module.common.player.MusicPlayerWrapper @Suppress("UNUSED_PARAMETER") class PersonalFmActivity : AppCompatActivity(), SeekBar.OnSeekBarChangeListener { private val compositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_personal_fm) setSupportActionBar(toolbar) toolbar.setNavigationOnClickListener { onBackPressed() } seekBar.setOnSeekBarChangeListener(this) startListenEvent() lyricView.setOnPlayIndicatorClickListener { MusicPlayerWrapper.seekToPosition(it.toLong()) } lyricView.setOnClickListener { if (lyricView.visibility == View.VISIBLE) { changeMusicInfoState() } } playerInfo.setOnClickListener { changeMusicInfoState() } } /** * 显示歌词与显示歌曲图片相互切换 */ private fun changeMusicInfoState(showLyric: Boolean = lyricView.visibility != View.VISIBLE) { if (showLyric) { lyricView.visibility = View.VISIBLE imageArtwork.visibility = View.INVISIBLE textArtist.visibility = View.INVISIBLE textMusicName.visibility = View.INVISIBLE } else { lyricView.visibility = View.INVISIBLE imageArtwork.visibility = View.VISIBLE textArtist.visibility = View.VISIBLE textMusicName.visibility = View.VISIBLE } } private val currentPlayingMusic: Music? get() = MusicPlayerWrapper.currentPlaying() private val isPlaying: Boolean get() = MusicPlayerWrapper.isPlaying() private fun startListenEvent() { RxBus.listen(FetchMusicErrorEvent::class.java) .subscribe { freezeViewState() toast("出错 : ${it.throwable.message}") it.throwable.printStackTrace() }.addTo(compositeDisposable) RxBus.listen(this, MusicPlayerEvent.OnPlayerStateChange::class) { resetViewState() setPlayingState(isPlaying) setLikeState(currentPlayingMusic!!.isFavorite) setMusicInfo(currentPlayingMusic) setImage(currentPlayingMusic?.picUrl) }.addTo(compositeDisposable) RxBus.listen(OnMusicLikedEvent::class.java) .subscribe { (music, liked) -> if (currentPlayingMusic == music) { setLikeState(liked) } } RxBus.listen(this, MusicPlayerEvent.OnMusicProgressChangeEvent::class) { setProgress(it.currentPosition, it.total) } // RxBus.listen<MusicPlayerEvent.OnMusicPrepareEvent> { // setMusicInfo(it.music) // setImage(it.music.picModel) // //TODO setPrepareState // setLikeState(it.music.isFavorite) // currentPlayingMusic = it.music // } // RxBus.listen<NeteaseFmPlayerEvent.OnMusicPlayerErrorEvent> { // setPlayingState(false) // }.addTo(compositeDisposable) } override fun onDestroy() { super.onDestroy() compositeDisposable.clear() } fun onDeleteButtonClick(view: View) { currentPlayingMusic?.let { MusicPlayerWrapper.remove(it) } } fun onLikeButtonClick(view: View) { RxBus.publish(MusicPlayerEvent.Like(currentPlayingMusic)) } fun onPlayButtonClick(view: View) { RxBus.publish(MusicPlayerEvent.PlayPause()) } fun onNextButtonClick(view: View) { RxBus.publish(MusicPlayerEvent.PlayNext()) } private fun setImage(model: Any?) { model ?: return //设置图片宽高上限. val width = getScreenWidthHeight().first / 2 val target = GlideApp.with(this) .asBitmap() .load(model) .submit(width, width) //取得图片,进行高斯模糊,然后显示为背景 doAsync { val bitmap = target.get() ?: return@doAsync log("artWork :height :${bitmap.height} width : ${bitmap.width}") uiThread { imageArtwork.setImageBitmap(bitmap) } bitmap.blur(canReuseInBitmap = false).let { blued -> uiThread { imageBackground.setImageBitmap(blued) } } } } private fun setPlayingState(isPlaying: Boolean) { val indicator = if (!isPlaying) R.drawable.ic_play_arrow_black_24dp else R.drawable.ic_pause_black_24dp buttonPlay.setImageResource(indicator) } private fun setLikeState(like: Boolean) { if (like) { buttonLike.setColorFilter(Color.RED) } else { buttonLike.setColorFilter(Color.WHITE) } } private fun setCommentState(any: Any) { toast("not implemented!") } private fun setMusicInfo(music: Music?) { music ?: return textMusicName.text = music.title textArtist.text = music.artistString() NeteaseCloudMusicApi.instance .lyric(music.id) .observeOn(AndroidSchedulers.mainThread()) .subscribeK { onNext { if (it.lrc.lyric != null) { lyricView.setLyricText(it.lrc.lyric) } else { lyricView.setLyricError(string(R.string.netease_player_message_lyric_not_found)) } } onError { lyricView.setLyricError(string(R.string.netease_error_can_not_fetch_lyric)) } } } private fun setProgress(current: Long, total: Long) { textCurrentPosition.text = current.toMusicTimeStamp() textDuration.text = total.toMusicTimeStamp() seekBar.max = total.toInt() if (!isUserSeeking) { seekBar.progress = current.toInt() } lyricView.scrollLyricTo(current.toInt()) } private fun freezeViewState() { buttonLike.isClickable = false buttonPlay.setImageResource(R.drawable.ic_play_arrow_black_24dp) buttonDelete.isClickable = false buttonComment.isClickable = false } private fun resetViewState() { buttonLike.isClickable = true buttonDelete.isClickable = true buttonComment.isClickable = true } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { } private var isUserSeeking = false override fun onStartTrackingTouch(seekBar: SeekBar) { isUserSeeking = true } override fun onStopTrackingTouch(seekBar: SeekBar) { MusicPlayerWrapper.seekToPosition(seekBar.progress.toLong()) isUserSeeking = false } }
gpl-2.0
91926593c7db30b1b88db093178c3a03
32.312236
108
0.626472
4.822847
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/ProcessComponent.kt
1
1061
@file:Suppress("unused") package cn.yiiguxing.plugin.translate.ui import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.util.ui.AnimatedIcon import com.intellij.util.ui.JBUI import java.awt.Insets import javax.swing.JPanel /** * ProcessComponent */ class ProcessComponent(private val icon: AnimatedIcon, insets: Insets = JBUI.emptyInsets()) : JPanel(), Disposable { val isRunning: Boolean get() = icon.isRunning init { isOpaque = false layout = GridLayoutManager(1, 1, insets, 0, 0) add(icon, GridConstraints().apply { column = 0 hSizePolicy = GridConstraints.SIZEPOLICY_FIXED vSizePolicy = GridConstraints.SIZEPOLICY_FIXED anchor = GridConstraints.ANCHOR_CENTER }) } fun resume() = icon.resume() fun suspend() = icon.suspend() override fun dispose() { Disposer.dispose(icon) } }
mit
5700669c25afe3eddc442462e8690f9c
24.878049
116
0.694628
4.278226
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/structure/presenter/EditUserInfoP.kt
1
3673
package com.fuyoul.sanwenseller.structure.presenter import android.app.Activity import android.content.Context import android.util.Log import com.alibaba.fastjson.JSON import com.fuyoul.sanwenseller.base.BaseP import com.fuyoul.sanwenseller.bean.reqhttp.ReqEditUserInfo import com.fuyoul.sanwenseller.bean.reshttp.ResHttpResult import com.fuyoul.sanwenseller.bean.reshttp.ResLoginInfoBean import com.fuyoul.sanwenseller.bean.reshttp.ResQiNiuBean import com.fuyoul.sanwenseller.configs.UrlInfo.EDITUSERINFO import com.fuyoul.sanwenseller.helper.HttpDialogHelper import com.fuyoul.sanwenseller.helper.MsgDialogHelper import com.fuyoul.sanwenseller.helper.QiNiuHelper import com.fuyoul.sanwenseller.listener.HttpReqListener import com.fuyoul.sanwenseller.listener.QiNiuUpLoadListener import com.fuyoul.sanwenseller.structure.model.EditUserInfoM import com.fuyoul.sanwenseller.structure.view.EditUserInfoV import com.fuyoul.sanwenseller.utils.NormalFunUtils import com.lzy.okgo.OkGo import org.litepal.crud.DataSupport /** * @author: chen * @CreatDate: 2017\10\28 0028 * @Desc: */ class EditUserInfoP(editUserInfoV: EditUserInfoV) : BaseP<EditUserInfoM, EditUserInfoV>(editUserInfoV) { override fun getModelImpl(): EditUserInfoM = EditUserInfoM() fun upInfo(activity: Activity, info: ResLoginInfoBean) { HttpDialogHelper.showDialog(activity, true, false) //如果是本地图片,先上传到七牛 if (info.avatar != null && !info.avatar.startsWith("http")) { val imgs = ArrayList<String>() imgs.add(info.avatar) QiNiuHelper.multQiNiuUpLoad(activity, imgs, object : QiNiuUpLoadListener { override fun complete(path: List<ResQiNiuBean>) { doReq(activity, info, path[0].key) } override fun error(error: String) { HttpDialogHelper.dismisss() NormalFunUtils.showToast(activity, error) } }) } else { doReq(activity, info, null) } } private fun doReq(activity: Activity, info: ResLoginInfoBean, avatar: String?) { val data = ReqEditUserInfo() data.avatar = avatar ?: info.avatar data.nickname = info.nickname data.gender = info.gender data.provinces = info.provinces data.city = info.city data.selfExp = info.selfExp data.selfInfo = info.selfInfo Log.e("csl", "更新个人资料:${JSON.toJSONString(data)}") OkGo.post<ResHttpResult>(EDITUSERINFO) .upJson(JSON.toJSONString(data)) .execute(object : HttpReqListener(activity) { override fun reqOk(result: ResHttpResult) { val backInfo = JSON.parseObject(result.data.toString(), ResLoginInfoBean::class.java) backInfo.updateAll() MsgDialogHelper.showStateDialog(activity, "资料更新成功", true, object : MsgDialogHelper.DialogOndismissListener { override fun onDismiss(context: Context) { activity.setResult(Activity.RESULT_OK) activity.finish() } }) } override fun withoutData(code: Int, msg: String) { NormalFunUtils.showToast(activity, msg) } override fun error(errorInfo: String) { NormalFunUtils.showToast(activity, errorInfo) } }) } }
apache-2.0
c654b7d46782945cc4d7ef4a3f70b8b9
33.188679
132
0.632073
4.656812
false
false
false
false
JakeWharton/AssistedInject
inflation-inject-processor/src/main/java/app/cash/inject/inflation/processor/AssistedInjection.kt
1
4469
package app.cash.inject.inflation.processor import app.cash.inject.inflation.processor.internal.applyEach import app.cash.inject.inflation.processor.internal.joinToCode import app.cash.inject.inflation.processor.internal.peerClassWithReflectionNesting import app.cash.inject.inflation.processor.internal.rawClassName import com.squareup.javapoet.AnnotationSpec import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import com.squareup.javapoet.TypeVariableName import javax.lang.model.element.Modifier.FINAL import javax.lang.model.element.Modifier.PRIVATE import javax.lang.model.element.Modifier.PUBLIC private val JAVAX_INJECT = ClassName.get("javax.inject", "Inject") internal val JAVAX_PROVIDER = ClassName.get("javax.inject", "Provider") /** The structure of an assisted injection factory. */ data class AssistedInjection( /** The type which will be instantiated inside the factory. */ val targetType: TypeName, /** TODO */ val dependencyRequests: List<DependencyRequest>, /** The factory interface type. */ val factoryType: TypeName, /** Name of the factory's only method. */ val factoryMethod: String, /** The factory method return type. [targetType] must be assignable to this type. */ val returnType: TypeName = targetType, /** * The factory method keys. These default to the keys of the assisted [dependencyRequests] * and when supplied must always match them, but the order is allowed to be different. */ val assistedKeys: List<Key> = dependencyRequests.filter { it.isAssisted }.map { it.key }, /** An optional `@Generated` annotation marker. */ val generatedAnnotation: AnnotationSpec? = null ) { private val keyToRequest = dependencyRequests.filter { it.isAssisted }.associateBy { it.key } init { check(keyToRequest.keys == assistedKeys.toSet()) { """ assistedKeys must contain the same elements as the assisted dependencyRequests. * assistedKeys: $assistedKeys * assisted dependencyRequests: ${keyToRequest.keys} """.trimIndent() } } /** The type generated from [brewJava]. */ val generatedType = targetType.rawClassName().assistedInjectFactoryName() private val providedKeys = dependencyRequests.filterNot { it.isAssisted } fun brewJava(): TypeSpec { return TypeSpec.classBuilder(generatedType) .addModifiers(PUBLIC, FINAL) .addSuperinterface(factoryType) .apply { if (generatedAnnotation != null) { addAnnotation(generatedAnnotation) } } .applyEach(providedKeys) { addField(it.providerType.withoutAnnotations(), it.name, PRIVATE, FINAL) } .addMethod(MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addAnnotation(JAVAX_INJECT) .applyEach(providedKeys) { addParameter(it.providerType, it.name) addStatement("this.$1N = $1N", it.name) } .build()) .addMethod(MethodSpec.methodBuilder(factoryMethod) .addAnnotation(Override::class.java) .addModifiers(PUBLIC) .returns(returnType) .apply { if (targetType is ParameterizedTypeName) { addTypeVariables(targetType.typeArguments.filterIsInstance<TypeVariableName>()) } } .applyEach(assistedKeys) { key -> val parameterName = keyToRequest.getValue(key).name addParameter(key.type, parameterName) } .addStatement("return new \$T(\n\$L)", targetType, dependencyRequests.map { it.argumentProvider }.joinToCode(",\n")) .build()) .build() } } private val DependencyRequest.providerType: TypeName get() { val type = if (key.useProvider) { ParameterizedTypeName.get(JAVAX_PROVIDER, key.type.box()) } else { key.type } key.qualifier?.let { return type.annotated(it) } return type } private val DependencyRequest.argumentProvider get() = CodeBlock.of(if (isAssisted || !key.useProvider) "\$N" else "\$N.get()", name) fun ClassName.assistedInjectFactoryName(): ClassName = peerClassWithReflectionNesting(simpleName() + "_InflationFactory")
apache-2.0
ec79438467e2f06d5e7b83273bf08a5d
36.872881
95
0.685388
4.597737
false
false
false
false
MoonCheesez/sstannouncer
sstannouncer/app/src/main/java/sst/com/anouncements/feed/model/Entry.kt
1
1265
package sst.com.anouncements.feed.model import android.os.Parcelable import android.text.format.DateUtils import kotlinx.android.parcel.Parcelize import org.apache.commons.text.StringEscapeUtils import java.text.SimpleDateFormat import java.util.* @Parcelize data class Entry( val id: String, val publishedDate: Date, val updatedDate: Date, val authorName: String, val url: String, val title: String, val content: String ) : Parcelable { val relativePublishedDate: String by lazy { relativeDate(publishedDate) } val contentWithoutHTML: String by lazy { // Remove any content in style tags var content = this.content.replace("<style[^>]*>.*</style>".toRegex(), "") // Remove HTML tags content = content.replace("<[^>]*>".toRegex(), "") // Unescape characters, e.g. converting &lt; to < StringEscapeUtils.unescapeHtml4(content).trim() } private fun relativeDate(date: Date): String { return DateUtils.getRelativeTimeSpanString(date.time).toString() } override fun equals(other: Any?) = other is Entry && id == other.id && updatedDate.compareTo(other.updatedDate) == 0 override fun hashCode() = (id + updatedDate).hashCode() }
mit
2c4e8b4a7a956044add492708083c255
29.878049
82
0.675099
4.347079
false
false
false
false
MaibornWolff/codecharta
analysis/import/CSVImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcemonitor/SourceMonitorImporter.kt
1
3614
package de.maibornwolff.codecharta.importer.sourcemonitor import de.maibornwolff.codecharta.importer.csv.CSVProjectBuilder import de.maibornwolff.codecharta.serialization.ProjectSerializer import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import de.maibornwolff.codecharta.translator.MetricNameTranslator import picocli.CommandLine import java.io.File import java.io.IOException import java.io.InputStream import java.io.PrintStream import java.util.concurrent.Callable @CommandLine.Command( name = "sourcemonitorimport", description = ["generates cc.json from sourcemonitor csv"], footer = ["Copyright(c) 2020, MaibornWolff GmbH"] ) class SourceMonitorImporter( private val output: PrintStream = System.out ) : Callable<Void>, InteractiveParser { @CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exits"]) private var help = false @CommandLine.Option(names = ["-nc", "--not-compressed"], description = ["save uncompressed output File"]) private var compress = true @CommandLine.Option(names = ["-o", "--output-file"], description = ["output File"]) private var outputFile: String? = null @CommandLine.Parameters(arity = "1..*", paramLabel = "FILE", description = ["sourcemonitor csv files"]) private var files: List<File> = mutableListOf() private val pathSeparator = '\\' private val csvDelimiter = ',' @Throws(IOException::class) override fun call(): Void? { val csvProjectBuilder = CSVProjectBuilder(pathSeparator, csvDelimiter, "File Name", sourceMonitorReplacement, getAttributeDescriptors()) files.map { it.inputStream() }.forEach<InputStream> { csvProjectBuilder.parseCSVStream(it) } val project = csvProjectBuilder.build(true) ProjectSerializer.serializeToFileOrStream(project, outputFile, output, compress) return null } private val sourceMonitorReplacement: MetricNameTranslator get() { val prefix = "sm_" val replacementMap = mutableMapOf<String, String>() replacementMap["Project Name"] = "" replacementMap["Checkpoint Name"] = "" replacementMap["Created On"] = "" replacementMap["Lines"] = "loc" replacementMap["Statements"] = "statements" replacementMap["Classes and Interfaces"] = "classes" replacementMap["Methods per Class"] = "functions_per_class" replacementMap["Average Statements per Method"] = "average_statements_per_function" replacementMap["Line Number of Most Complex Method*"] = "" replacementMap["Name of Most Complex Method*"] = "" replacementMap["Maximum Complexity*"] = "max_function_mcc" replacementMap["Line Number of Deepest Block"] = "" replacementMap["Maximum Block Depth"] = "max_block_depth" replacementMap["Average Block Depth"] = "average_block_depth" replacementMap["Average Complexity*"] = "average_function_mcc" for (i in 0..9) { replacementMap["Statements at block level $i"] = "statements_at_level_$i" } return MetricNameTranslator(replacementMap.toMap(), prefix) } companion object { @JvmStatic fun main(args: Array<String>) { CommandLine(SourceMonitorImporter()).execute(*args) } } override fun getDialog(): ParserDialogInterface = ParserDialog }
bsd-3-clause
149777fb683ce42de31e5504b0409845
40.54023
124
0.680133
4.910326
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/morse/MorseToExecutor.kt
1
2597
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.morse import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.common.utils.text.MorseUtils import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.MorseCommand class MorseToExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val textArgument = string("text", MorseCommand.I18N_PREFIX.Options.FromTextToMorse) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { val text = args[options.textArgument] when (val toMorseResult = MorseUtils.toMorse(text)) { is MorseUtils.ValidToMorseConversionResult -> { val toMorse = toMorseResult.morse val unknownCharacters = toMorseResult.unknownCharacters context.sendMessage { styled( content = "`$toMorse`", prefix = Emotes.Radio.toString() ) if (unknownCharacters.isNotEmpty()) { styled( content = context.i18nContext.get( MorseCommand.I18N_PREFIX.ToMorseWarningUnknownCharacters( unknownCharacters.joinToString("") ) ), prefix = Emotes.LoriSob ) } } } is MorseUtils.InvalidToMorseConversionResult -> { context.failEphemerally( prefix = Emotes.Error.asMention, content = context.i18nContext.get( MorseCommand.I18N_PREFIX.ToMorseFailUnknownCharacters ) ) } } } }
agpl-3.0
22439db66e1a7286557aaa5970fe7cd0
44.578947
114
0.633808
5.849099
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/wishlist/list/WishlistListFragment.kt
1
5117
package com.ghstudios.android.features.wishlist.list import android.app.Activity import androidx.lifecycle.Observer import android.content.Intent import android.os.Bundle import androidx.recyclerview.widget.ItemTouchHelper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.lifecycle.ViewModelProvider import com.ghstudios.android.ClickListeners.WishlistClickListener import com.ghstudios.android.RecyclerViewFragment import com.ghstudios.android.adapter.common.SimpleDiffRecyclerViewAdapter import com.ghstudios.android.adapter.common.SimpleViewHolder import com.ghstudios.android.adapter.common.SwipeReorderTouchHelper import com.ghstudios.android.data.classes.Wishlist import com.ghstudios.android.features.wishlist.detail.WishlistRenameDialogFragment import com.ghstudios.android.mhgendatabase.R import com.ghstudios.android.util.createSnackbarWithUndo /** Adapter used to render wishlists in a recyclerview */ class WishlistAdapter: SimpleDiffRecyclerViewAdapter<Wishlist>() { override fun areItemsTheSame(oldItem: Wishlist, newItem: Wishlist): Boolean { return oldItem.id == newItem.id } override fun onCreateView(parent: ViewGroup): View { val inflater = LayoutInflater.from(parent.context) return inflater.inflate(R.layout.fragment_wishlistmain_listitem, parent, false) } override fun bindView(viewHolder: SimpleViewHolder, data: Wishlist) { val view = viewHolder.itemView val wishlist = data // Set up the views val itemLayout = view.findViewById<View>(R.id.listitem) as LinearLayout val wishlistNameTextView = view.findViewById<View>(R.id.item_name) as TextView view.findViewById<View>(R.id.item_image).visibility = View.GONE // Bind views val cellText = wishlist.name wishlistNameTextView.text = cellText // Assign view tag and listeners view.tag = wishlist.id itemLayout.tag = wishlist.id itemLayout.setOnClickListener(WishlistClickListener(viewHolder.context, wishlist.id)) } } /** * Fragment used to display and manage a collection of wishlists */ class WishlistListFragment : RecyclerViewFragment() { companion object { const val DIALOG_WISHLIST_ADD = "wishlist_add" const val DIALOG_WISHLIST_COPY = "wishlist_copy" const val DIALOG_WISHLIST_DELETE = "wishlist_delete" const val DIALOG_WISHLIST_RENAME = "wishlist_rename" const val REQUEST_ADD = 0 const val REQUEST_RENAME = 1 const val REQUEST_COPY = 2 const val REQUEST_DELETE = 3 } val viewModel by lazy { ViewModelProvider(this).get(WishlistListViewModel::class.java) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) enableDivider() enableFab { showAddDialog() } val adapter = WishlistAdapter() setAdapter(adapter) val handler = ItemTouchHelper(SwipeReorderTouchHelper( afterSwiped = { val wishlistId = it.itemView.tag as Long val message = getString(R.string.wishlist_deleted) val operation = viewModel.startDeleteWishlist(wishlistId) val containerView = view.findViewById<ViewGroup>(R.id.recyclerview_container_main) containerView.createSnackbarWithUndo(message, operation) } )) handler.attachToRecyclerView(recyclerView) viewModel.wishlistData.observe(viewLifecycleOwner, Observer { if (it == null) return@Observer adapter.setItems(it) showEmptyView(show = it.isEmpty()) }) } private fun showAddDialog() { val dialog = WishlistAddDialogFragment() dialog.setTargetFragment(this@WishlistListFragment, REQUEST_ADD) dialog.show(parentFragmentManager, DIALOG_WISHLIST_ADD) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != Activity.RESULT_OK) return if (requestCode == REQUEST_ADD) { if (data!!.getBooleanExtra(WishlistAddDialogFragment.EXTRA_ADD, false)) { updateUI() } } else if (requestCode == REQUEST_RENAME) { // not used here if (data!!.getBooleanExtra(WishlistRenameDialogFragment.EXTRA_RENAME, false)) { updateUI() } } else if (requestCode == REQUEST_COPY) { // might be used here if (data!!.getBooleanExtra(WishlistCopyDialogFragment.EXTRA_COPY, false)) { updateUI() } } } override fun onResume() { super.onResume() // Check for dataset changes when the activity is resumed. // Not the best practice but the list will always be small. viewModel.reload() } private fun updateUI() { viewModel.reload() } }
mit
66b5db82d581c8ad445f7e79016c219c
35.81295
102
0.683408
4.90604
false
false
false
false
juntaki/springfennec
src/main/kotlin/com/juntaki/springfennec/util/PropertyUtil.kt
1
4780
/* * Copyright 2017 juntaki * * 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.juntaki.springfennec.util import io.swagger.models.properties.* import javax.lang.model.element.ElementKind import javax.lang.model.element.VariableElement import javax.lang.model.type.ArrayType import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror import javax.lang.model.util.ElementFilter import javax.lang.model.util.Elements import javax.lang.model.util.Types class PropertyUtil( private val elementUtils: Elements, private val typeUtils: Types ) { fun doEachClassField(className: String, fn: (VariableElement) -> Unit) { val typeElement = elementUtils.getTypeElement(className) ?: return ElementFilter.fieldsIn(typeElement.enclosedElements).forEach { it ?: return@forEach // enum class cannot converted to swagger spec automatically. // ApiParam.allowableValues should be used, but not implemented. if (elementUtils.getTypeElement(it.asType().toString())?.kind == ElementKind.ENUM) return@forEach fn(it) } } // return null only if tm is Void type fun getProperty(tm: TypeMirror): Property? { fun isAssignable(tm: TypeMirror, className: String): Boolean { return typeUtils.isAssignable(tm, elementUtils.getTypeElement(className).asType()) } fun isSameClassName(tm: TypeMirror, className: String): Boolean { return tm.toString() == className } if (isAssignable(tm, "java.time.LocalDateTime") || isAssignable(tm, "java.time.ZonedDateTime") || isAssignable(tm, "java.time.OffsetDateTime") || isAssignable(tm, "java.util.Date") || isSameClassName(tm, "org.joda.time.DateTime") ) { return DateTimeProperty() } if (isAssignable(tm, "java.time.LocalDate")) { return DateProperty() } if (isAssignable(tm, "java.lang.Boolean")) { return BooleanProperty() } if (isAssignable(tm, "java.lang.Byte")) { return ByteArrayProperty() } if (isAssignable(tm, "java.lang.Integer")) { return IntegerProperty() } if (isAssignable(tm, "java.lang.Long")) { return LongProperty() } if (isAssignable(tm, "java.lang.Float")) { return FloatProperty() } if (isAssignable(tm, "java.lang.Double")) { return DoubleProperty() } if (isAssignable(tm, "java.lang.String")) { return StringProperty() } if (isSameClassName(tm, "org.springframework.web.multipart.MultipartFile")) { return FileProperty() } // Array val listRegex = Regex("""^java.util.List|^java.util.ArrayList""") if (tm is DeclaredType && listRegex.containsMatchIn(tm.toString())) { val arrayProperty = ArrayProperty() arrayProperty.items = getProperty(tm.typeArguments[0]) return arrayProperty } if (tm is ArrayType) { val arrayProperty = ArrayProperty() arrayProperty.items = getProperty(tm.componentType) return arrayProperty } // Map val mapRegex = Regex("""^java.util.Map""") if (tm is DeclaredType && mapRegex.containsMatchIn(tm.toString())) { if (!isAssignable(tm.typeArguments[0], "java.lang.String")) { // TODO: I believe this is not implemented... but output is the same as springfox. is it correct? // TODO: Read JSON Schema and https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responses-definitions-object } val mapProperty = MapProperty() mapProperty.additionalProperties = getProperty(tm.typeArguments[1]) return mapProperty } // Void if (tm.toString() == "java.lang.Void") { return null } // Class val refProperty = RefProperty() refProperty.`$ref` = tm.toString() return refProperty } }
apache-2.0
6b6028339ce2f766443fb9d6cfabc34e
36.944444
147
0.619038
4.600577
false
false
false
false
mplatvoet/kovenant
projects/rx/src/main/kotlin/promises.kt
1
5426
/* * Copyright (c) 2016 Mark Platvoet<[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, * THE SOFTWARE. */ package nl.komponents.kovenant.rx import nl.komponents.kovenant.Promise import rx.Observable import rx.Producer import rx.Subscriber import rx.exceptions.Exceptions import java.util.concurrent.atomic.AtomicInteger /** * Turns an existing `Promise<V, E : Exception>` into an `Observable<V>`. * Note that by default the `Observable` is observed on the callback `Dispatcher` * of the `Promise` in question. * * @return The Observable backed by the Promise */ fun <V, E : Exception> Promise<V, E>.toObservable(): Observable<V> = Observable.create(PromiseOnSubscribe(this)) private class PromiseOnSubscribe<V, E : Exception>(private val promise: Promise<V, E>) : Observable.OnSubscribe<V> { override fun call(subscriber: Subscriber<in V>) { val producer = PromiseProducer<V, E>(subscriber) subscriber.setProducer(producer) if (promise.isDone()) { if (promise.isSuccess()) producer.setValue(promise.get()) else if (promise.isFailure()) producer.setError(promise.getError()) } else { promise success { producer.setValue(it) } promise fail { producer.setError(it) } } } private class PromiseProducer<V, E : Exception>(private val subscriber: Subscriber<in V>) : Producer { companion object { val error_result = 4 val value_result = 2 val has_request = 1 } private @Volatile var value: Any? = null private val state = AtomicInteger(0) override fun request(n: Long) { if (n < 0) throw IllegalArgumentException("n >= 0 required") if (n > 0) { while (true) { val oldState = state.get() if (oldState.isRequestSet()) return // request is already set, so return val newState = oldState or has_request if (state.compareAndSet(oldState, newState)) { if (oldState.isResolved()) emit() return // we are done } } } } private fun Int.isError() = hasFlag(error_result) private fun Int.isValue() = hasFlag(value_result) private fun Int.isResolved() = this >= value_result // yeah nasty right ;-) private fun Int.isRequestSet() = hasFlag(has_request) private fun Int.hasFlag(flag: Int) = this and flag == flag fun setError(error: E) { value = error setResolvedState(error_result) } fun setValue(value: V) { this.value = value setResolvedState(value_result) } private fun setResolvedState(flag: Int) { while (true) { val oldState = state.get() val newState = oldState or flag if (state.compareAndSet(oldState, newState)) { if (oldState.isRequestSet()) emit() return // we are done } if (oldState.isResolved()) { //sanity check against poor implemented Promises throw IllegalStateException("It shouldn't happen, but did...") } } } //This behaviour is mimicked from SingleDelayedProducer private fun emit() { val s = state.get() when { s.isValue() -> emitValue() s.isError() -> emitError() else -> throw IllegalStateException("It shouldn't happen, but did...") } } private fun emitError() { @Suppress("UNCHECKED_CAST") val e = value as E Exceptions.throwIfFatal(e) subscriber.onError(e) } //This behaviour is mimicked from SingleDelayedProducer private fun emitValue() { if (!subscriber.isUnsubscribed) { @Suppress("UNCHECKED_CAST") val v = value as V try { subscriber.onNext(v) } catch (e: Throwable) { Exceptions.throwOrReport(e, subscriber, v) return } } if (!subscriber.isUnsubscribed) { subscriber.onCompleted() } } } }
mit
b51d4fea4475ecf19da5d109a0dda9c7
35.416107
116
0.586067
4.806023
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/account/ApiAccountDataStore.kt
2
1252
package com.bl_lia.kirakiratter.data.repository.datasource.account import com.bl_lia.kirakiratter.data.cache.AccountCache import com.bl_lia.kirakiratter.domain.entity.Account import com.bl_lia.kirakiratter.domain.entity.Relationship import com.bl_lia.kirakiratter.domain.entity.Status import io.reactivex.Single class ApiAccountDataStore( private val accountService: AccountService, private val accountCache: AccountCache ) : AccountDataStore { override fun status(id: Int): Single<List<Status>> = accountService.status(id) override fun moreStatus(id: Int, maxId: Int?, sinceId: Int?): Single<List<Status>> = accountService.status(id, maxId, sinceId) override fun relationship(id: Int): Single<Relationship> = accountService.relationships(id) .flatMap { Single.just(it.first()) } override fun follow(id: Int): Single<Relationship> = accountService.follow(id) override fun unfollow(id: Int): Single<Relationship> = accountService.unfollow(id) override fun verifyCredentials(): Single<Account> = accountService.verifyCredentials() .doAfterSuccess { account -> accountCache.credentials = account } }
mit
cd4c8214ca63012dc3ce3bd75ea0f4c3
39.419355
130
0.705272
4.519856
false
false
false
false
spark/photon-tinker-android
cloudsdk/src/test/java/io/particle/android/sdk/cloud/TestData.kt
1
3559
package io.particle.android.sdk.cloud import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType import io.particle.android.sdk.cloud.ParticleDevice.VariableType const val DEVICE_ID_0 = "d34db33f52ca40bd34db33f0" const val DEVICE_ID_1 = "d34db33f52ca40bd34db33f1" internal val DEVICE_STATE_0 = DeviceState( DEVICE_ID_0, ParticleDeviceType.XENON.intValue, ParticleDeviceType.XENON.intValue, "64.124.183.01", null, "normal", "device0", true, false, null, null, "1.4.0", "1.4.4", setOf(), mapOf(), ParticleDeviceType.XENON, null, "XENKAB8D34DB33F", "ABCDEFG01234567", null, "1.4.0", null ) internal val DEVICE_STATE_1 = DeviceState( DEVICE_ID_1, ParticleDeviceType.ARGON.intValue, ParticleDeviceType.ARGON.intValue, "64.124.183.02", null, "normal", "device1", true, false, null, null, "1.4.2", "1.4.4", setOf(), mapOf(), ParticleDeviceType.ARGON, null, "ARGHABD34DB33F1", "ABCDEFG01234567", null, "1.4.2", null ) internal val DEVICE_STATE_1_FULL = DEVICE_STATE_1.copy( functions = setOf("digitalread", "digitalwrite", "analogread", "analogwrite"), variables = mapOf( "somebool" to VariableType.BOOLEAN, "someint" to VariableType.INT, "somedouble" to VariableType.DOUBLE, "somestring" to VariableType.STRING ) ) val DEVICE_0_JSON = """ { "id":"$DEVICE_ID_0", "name":"device0", "last_app":null, "last_ip_address":"64.124.183.01", "last_heard":null, "product_id":14, "connected":true, "platform_id":14, "cellular":false, "notes":null, "status":"normal", "serial_number":"XENKAB8D34DB33F", "mobile_secret":"ABCDEFG01234567", "current_build_target":"1.4.0", "system_firmware_version":"1.4.0", "default_build_target":"1.4.4" } """.trimIndent() val DEVICE_1_JSON = """ { "id":"$DEVICE_ID_1", "name":"device1", "last_app":null, "last_ip_address":"64.124.183.02", "last_heard":null, "product_id":12, "connected":true, "platform_id":12, "cellular":false, "notes":null, "status":"normal", "serial_number":"ARGHABD34DB33F1", "mobile_secret":"ABCDEFG01234567", "current_build_target":"1.4.2", "system_firmware_version":"1.4.2", "default_build_target":"1.4.4" } """.trimIndent() val DEVICE_1_FULL_JSON = """ { "id":"$DEVICE_ID_1", "name":"device1", "last_app":null, "last_ip_address":"64.124.183.02", "last_heard":null, "product_id":12, "connected":true, "platform_id":12, "cellular":false, "notes":null, "network": { "id":"d34db33fd34db33f0123456A", "name":"fakenet", "type":"micro_wifi", "role":{ "gateway":true, "state":"confirmed" } }, "status":"normal", "serial_number":"ARGHABD34DB33F1", "mobile_secret":"ABCDEFG01234567", "current_build_target":"1.4.2", "system_firmware_version":"1.4.2", "default_build_target":"1.4.4", "variables":{ "somebool":"bool", "someint":"int32", "somedouble":"double", "somestring":"string" }, "functions":[ "digitalread", "digitalwrite", "analogread", "analogwrite" ], "firmware_updates_enabled":true, "firmware_updates_forced":false } """.trimIndent() val DEVICE_LIST_JSON = """ [ $DEVICE_0_JSON, $DEVICE_1_JSON ] """.trimIndent()
apache-2.0
3c9547b53b04a47f05ba4985dab1f6bc
20.569697
82
0.58612
3.108297
false
false
false
false
zach-klippenstein/fraknums
app/src/main/kotlin/com/example/fragnums/MainActivity.kt
1
3413
package com.example.fragnums import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.View import android.view.animation.AnimationUtils.loadAnimation import android.widget.FrameLayout import com.squareup.enumsbatter.R import java.util.ArrayList import kotlin.properties.Delegates.notNull class MainActivity : AppCompatActivity() { private var backstack: ArrayList<BackstackFrame> = ArrayList() private var currentScreen: Screen = Screen.values.first() private val container by lazy { findViewById(R.id.main_container) as FrameLayout } private var currentView: View by notNull() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState != null) { currentScreen = Screen.values[savedInstanceState.getInt("currentScreen")] backstack = savedInstanceState.getParcelableArrayList<BackstackFrame>("backstack") } currentView = currentScreen.inflate(container) container.addView(currentView) currentScreen.bind(currentView) updateActionBar() } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("currentScreen", currentScreen.ordinal) outState.putParcelableArrayList("backstack", backstack) } override fun onDestroy() { super.onDestroy() currentScreen.unbind() } override fun onBackPressed() { if (backstack.size > 0) { goBack() return } super.onBackPressed() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { goBack() return true } else -> return super.onOptionsItemSelected(item) } } fun goTo(screen: Screen) { currentScreen.unbind() currentView.startAnimation(loadAnimation(this, R.anim.exit_forward)) container.removeView(currentView) val backstackFrame = backstackFrame(currentScreen, currentView) backstack.add(backstackFrame) currentScreen = screen currentView = currentScreen.inflate(container) currentView.startAnimation(loadAnimation(this, R.anim.enter_forward)) container.addView(currentView) currentScreen.bind(currentView) updateActionBar() } fun goBack() { currentScreen.unbind() currentView.startAnimation(loadAnimation(this, R.anim.exit_backward)) container.removeView(currentView) val latest = backstack.removeAt(backstack.size - 1) currentScreen = latest.screen currentView = currentScreen.inflate(container) currentView.startAnimation(loadAnimation(this, R.anim.enter_backward)) container.addView(currentView, 0) latest.restore(currentView) currentScreen.bind(currentView) updateActionBar() } private fun updateActionBar() { val actionBar = supportActionBar actionBar.setDisplayHomeAsUpEnabled(backstack.size != 0) var title: CharSequence? = currentScreen.title if (title == null) { title = getTitle() } actionBar.title = title } }
apache-2.0
91ebd3d20080c46372bfbd2d919a5b55
31.198113
94
0.67448
5.250769
false
false
false
false
greggigon/Home-Temperature-Controller
temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/model/Model.kt
1
4808
package io.dev.temperature.model import io.vertx.core.buffer.Buffer import io.vertx.core.eventbus.MessageCodec import io.vertx.core.json.JsonObject import java.time.Instant import java.time.LocalDateTime import java.time.LocalTime import java.time.format.DateTimeFormatter data class Temperature(val value: Float, val temperatureSet: Float, val heating: Boolean, val date: Instant = Instant.now()) { companion object { fun fromJson(jsonObject: JsonObject): Temperature { return Temperature( jsonObject.getFloat("value"), jsonObject.getFloat("setTemp"), jsonObject.getBoolean("heating"), Instant.parse(jsonObject.getString("date"))) } } fun toJson(): String { val json = toJsonObject() return json.encodePrettily() } fun toJsonObject(): JsonObject { return JsonObject().put("value", value) .put("setTemp", temperatureSet) .put("heating", heating) .put("date", date.toString()) } } data class Schedule(val active: Boolean = false, val days: List<ScheduleDay>) { companion object { fun fromJson(jsonObject: JsonObject): Schedule { val active = jsonObject.getBoolean("active") val days = jsonObject.getJsonArray("days").map { ScheduleDay.fromJson(it as JsonObject) } return Schedule(active, days) } } private fun flattenListOfScheduledHoursOfDays(dateTime: LocalDateTime, tillTheEndOfWeek: List<ScheduleDay>): List<NextScheduledTemp> { return tillTheEndOfWeek.mapIndexed { index, scheduleDay -> val date = dateTime.plusDays(index.toLong()).toLocalDate() scheduleDay.hours.map { hour -> NextScheduledTemp(LocalDateTime.of(date, hour.time), hour.temp) } }.flatMap { it } } private fun dateOfNextWeekMonday(dateTime: LocalDateTime): LocalDateTime { val daysToAdd = 8 - dateTime.dayOfWeek.value return dateTime.plusDays(daysToAdd.toLong()) } fun nextScheduledTemp(dateTime: LocalDateTime): NextScheduledTemp? { val flattenedHours = days.flatMap { it.hours } if (flattenedHours.size == 0) return null val dayIndex = dateTime.dayOfWeek.value - 1 val tillTheEndOfWeek = days.subList(dayIndex, days.size) val mappedRestOfTheWeek = flattenListOfScheduledHoursOfDays(dateTime, tillTheEndOfWeek) val nextPossibleSchedule = mappedRestOfTheWeek.find { it.time.isAfter(dateTime) } if (nextPossibleSchedule == null) { val nextWeeksDate = dateOfNextWeekMonday(dateTime) return flattenListOfScheduledHoursOfDays(nextWeeksDate, days).first() } return nextPossibleSchedule } } data class ScheduleDay(val name: String, val hours: List<ScheduleHour>) { companion object { fun fromJson(jsonObject: JsonObject): ScheduleDay { val name = jsonObject.getString("name") val hours = jsonObject.getJsonArray("hours").map { ScheduleHour.fromJson(it as JsonObject) } return ScheduleDay(name, hours) } } } data class ScheduleHour(val time: LocalTime, val temp: Float) { companion object { fun fromJson(jsonObject: JsonObject): ScheduleHour { val timeParts = jsonObject.getString("time").split(":") val temp = jsonObject.getFloat("temp") return ScheduleHour(LocalTime.of(timeParts[0].toInt(), timeParts[1].toInt()), temp) } } } data class NextScheduledTemp(val time: LocalDateTime, val temp: Float) { fun toJson(): JsonObject { return JsonObject() .put("time", time.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm"))) .put("temp", temp) } } class TemperatureCodec : MessageCodec<Temperature, Temperature> { override fun systemCodecID(): Byte { return -1 } override fun name(): String? { return Temperature::class.java.canonicalName } override fun transform(p0: Temperature?): Temperature? { return p0 } override fun decodeFromWire(p0: Int, p1: Buffer?): Temperature? { val value = p1?.getFloat(p0) val setTemp = p1?.getFloat(p0 + 4) val heating: Boolean = if (p1?.getByte(p0 + 8) == Byte.MIN_VALUE ) false else true val date = Instant.ofEpochMilli(p1?.getLong(p0 + 9)!!) return Temperature(value!!, setTemp!!, heating, date) } override fun encodeToWire(p0: Buffer?, p1: Temperature?) { p0?.appendFloat(p1?.value!!) p0?.appendFloat(p1?.temperatureSet!!) p0?.appendByte(if (p1?.heating!!) 0 else 1) p0?.appendLong(p1?.date?.toEpochMilli()!!) } }
mit
d34a04b24cc0257c612b9d0f28265e40
34.10219
138
0.641223
4.427256
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/pages/PostPage.kt
1
3212
package com.eden.orchid.posts.pages import com.eden.common.util.EdenUtils import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Archetypes import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.impl.relations.AssetRelation import com.eden.orchid.posts.PostCategoryArchetype import com.eden.orchid.posts.PostsGenerator import com.eden.orchid.posts.model.Author import com.eden.orchid.posts.model.CategoryModel @Archetypes( Archetype(value = PostCategoryArchetype::class, key = PostsGenerator.GENERATOR_KEY), Archetype(value = ConfigArchetype::class, key = "${PostsGenerator.GENERATOR_KEY}.postPages") ) @Description(value = "A blog post.", name = "Blog Post") class PostPage(resource: OrchidResource, val categoryModel: CategoryModel, title: String) : OrchidPage(resource, "post", title) { @Option @Description("The posts author. May be the `name` of a known author, or an anonymous Author config, only " + "used for this post, which is considered as a guest author." ) var author: Author? = null @Option @Description("A list of tags for this post, for basic taxonomic purposes. More complex taxonomic relationships " + "may be managed by other plugins, which may take post tags into consideration." ) lateinit var tags: Array<String> @Option @Description("A 'type' of post, such as 'gallery', 'video', or 'blog', which is used to determine the specific" + "post template to use for the Page Content." ) lateinit var postType: String @Option @Description("A fully-specified URL to a post's featured image, or a relative path to an Orchid image.") lateinit var featuredImage: AssetRelation @Option @Description("The permalink structure to use only for this blog post. This overrides the permalink structure set " + "in the category configuration." ) lateinit var permalink: String val category: String? get() { return categoryModel.key } val categories: Array<String> get() { return categoryModel.path.split("/").toTypedArray() } val year: Int get() { return publishDate.year } val month: Int get() { return publishDate.monthValue } val monthName: String get() { return publishDate.month.toString() } val day: Int get() { return publishDate.dayOfMonth } init { this.extractOptions(this.context, data) postInitialize(title) } override fun initialize(title: String?) { } override fun getTemplates(): List<String> { val templates = ArrayList<String>() if(!EdenUtils.isEmpty(postType)) { templates.add(0, "$key-type-$postType") } if(!EdenUtils.isEmpty(categoryModel.key)) { templates.add(0, "$key-${categoryModel.key!!}") } return templates } }
mit
179060778ce786eca174d281995f73b9
34.688889
120
0.68929
4.271277
false
false
false
false
SUPERCILEX/Robot-Scouter
library/core-data/src/main/java/com/supercilex/robotscouter/core/data/model/Teams.kt
1
9083
package com.supercilex.robotscouter.core.data.model import android.net.Uri import android.util.Patterns import com.firebase.ui.firestore.SnapshotParser import com.google.firebase.Timestamp import com.google.firebase.appindexing.Action import com.google.firebase.appindexing.FirebaseAppIndex import com.google.firebase.appindexing.FirebaseUserActions import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.SetOptions import com.google.firebase.firestore.ktx.toObject import com.supercilex.robotscouter.common.FIRESTORE_NUMBER import com.supercilex.robotscouter.common.FIRESTORE_OWNERS import com.supercilex.robotscouter.common.FIRESTORE_POSITION import com.supercilex.robotscouter.common.FIRESTORE_TEMPLATE_ID import com.supercilex.robotscouter.common.FIRESTORE_TIMESTAMP import com.supercilex.robotscouter.common.isSingleton import com.supercilex.robotscouter.common.second import com.supercilex.robotscouter.core.InvocationMarker import com.supercilex.robotscouter.core.data.QueryGenerator import com.supercilex.robotscouter.core.data.QueuedDeletion import com.supercilex.robotscouter.core.data.client.retrieveLocalMedia import com.supercilex.robotscouter.core.data.client.saveLocalMedia import com.supercilex.robotscouter.core.data.deepLink import com.supercilex.robotscouter.core.data.defaultTemplateId import com.supercilex.robotscouter.core.data.firestoreBatch import com.supercilex.robotscouter.core.data.getInBatches import com.supercilex.robotscouter.core.data.logAdd import com.supercilex.robotscouter.core.data.logFailures import com.supercilex.robotscouter.core.data.share import com.supercilex.robotscouter.core.data.teamDuplicatesRef import com.supercilex.robotscouter.core.data.teamsRef import com.supercilex.robotscouter.core.data.uid import com.supercilex.robotscouter.core.logBreadcrumb import com.supercilex.robotscouter.core.model.Scout import com.supercilex.robotscouter.core.model.Team import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.invoke import kotlinx.coroutines.launch import kotlinx.coroutines.tasks.await import java.io.File import java.util.Calendar import java.util.Date import java.util.concurrent.TimeUnit import kotlin.math.abs val teamParser = SnapshotParser { checkNotNull(it.toObject<Team>()) } val teamWithSafeDefaults: (number: Long, id: String) -> Team = { number, id -> Team().apply { this.id = id this.number = number owners = mapOf(checkNotNull(uid) to number) templateId = defaultTemplateId } } internal val teamsQueryGenerator: QueryGenerator = { "$FIRESTORE_OWNERS.${it.uid}".let { teamsRef.whereGreaterThanOrEqualTo(it, 0).orderBy(it) } } val Team.ref: DocumentReference get() = teamsRef.document(id) val Team.isOutdatedMedia: Boolean get() = retrieveLocalMedia() == null && (mediaYear < Calendar.getInstance().get(Calendar.YEAR) || media.isNullOrBlank()) val Team.displayableMedia get() = retrieveLocalMedia() ?: media private const val TEAM_FRESHNESS_DAYS = 4 internal val Team.isStale: Boolean get() = TimeUnit.MILLISECONDS.toDays( System.currentTimeMillis() - timestamp.time ) >= TEAM_FRESHNESS_DAYS fun Collection<Team>.getNames(): String { val sortedTeams = toMutableList() sortedTeams.sort() return when { sortedTeams.isSingleton -> sortedTeams.single().toString() sortedTeams.size == 2 -> "${sortedTeams.first()} and ${sortedTeams.second()}" else -> { val teamsMaxedOut = sortedTeams.size > 10 val size = if (teamsMaxedOut) 10 else sortedTeams.size val names = StringBuilder(4 * size) for (i in 0 until size) { names.append(sortedTeams[i].number) if (i < size - 1) names.append(", ") if (i == size - 2 && !teamsMaxedOut) names.append("and ") } if (teamsMaxedOut) names.append(" and more") names.toString() } } } internal fun Team.add() { id = teamsRef.document().id rawSet(refresh = true, new = true) logAdd() FirebaseUserActions.getInstance().end( Action.Builder(Action.Builder.ADD_ACTION) .setObject(toString(), deepLink) .setActionStatus(Action.Builder.STATUS_TYPE_COMPLETED) .build() ).logFailures("addTeam:addAction") } internal fun Team.update(newTeam: Team) { if (this == newTeam) { val timestamp = Timestamp.now() ref.update(FIRESTORE_TIMESTAMP, timestamp).logFailures("updateTeam", ref, timestamp) return } if (name == newTeam.name) { hasCustomName = false } else if (!hasCustomName) { name = newTeam.name } if (media == newTeam.media) { hasCustomMedia = false } else if (!hasCustomMedia) { media = newTeam.media } mediaYear = newTeam.mediaYear if (website == newTeam.website) { hasCustomWebsite = false } else if (!hasCustomWebsite) { website = newTeam.website } forceUpdate() } internal fun Team.updateTemplateId(id: String) { if (id == templateId) return templateId = id ref.update(FIRESTORE_TEMPLATE_ID, templateId).logFailures("updateTeamTemplate", ref, templateId) } fun Team.forceUpdate(refresh: Boolean = false) { rawSet(refresh, false) } suspend fun List<DocumentReference>.shareTeams( block: Boolean = false ) = share(block) { token, ids -> QueuedDeletion.ShareToken.Team(token, ids) } fun Team.copyMediaInfo(image: Uri, shouldUpload: Boolean) { media = image.path hasCustomMedia = true shouldUploadMediaToTba = shouldUpload mediaYear = Calendar.getInstance().get(Calendar.YEAR) } suspend fun Team.processPotentialMediaUpload() = Dispatchers.IO { val url = media if (url == null || !File(url).exists()) return@IO saveLocalMedia() media = null hasCustomMedia = false } fun Team.trash() { FirebaseAppIndex.getInstance().remove(deepLink).logFailures("trashTeam:delIndex") firestoreBatch { val newNumber = if (number == 0L) { -1 // Fatal flaw in our trashing architecture: -0 isn't a thing. } else { -abs(number) } update(ref, "$FIRESTORE_OWNERS.${checkNotNull(uid)}", newNumber) set(teamDuplicatesRef.document(checkNotNull(uid)), mapOf(id to newNumber), SetOptions.merge()) set(userDeletionQueue, QueuedDeletion.Team(ref.id).data, SetOptions.merge()) }.logFailures("trashTeam", ref, this) } fun untrashTeam(id: String) { GlobalScope.launch { val ref = teamsRef.document(id) val snapshot = try { ref.get().await() } catch (e: Exception) { logBreadcrumb("untrashTeam:get: ${ref.path}") throw InvocationMarker(e) } val newNumber = abs(checkNotNull(snapshot.getLong(FIRESTORE_NUMBER))) firestoreBatch { update(ref, "$FIRESTORE_OWNERS.${checkNotNull(uid)}", newNumber) update(teamDuplicatesRef.document(checkNotNull(uid)), id, newNumber) update(userDeletionQueue, id, FieldValue.delete()) }.logFailures("untrashTeam:set", id) } } internal fun Team.fetchLatestData() { if (!isStale || timestamp.time == 0L) return ref.update(FIRESTORE_TIMESTAMP, Date(0)).logFailures("fetchLatestData", ref) } suspend fun Team.getScouts(): List<Scout> = coroutineScope { val scouts = getScoutsQuery().getInBatches().map { scoutParser.parseSnapshot(it) } val metricsForScouts = scouts.map { async { getScoutMetricsRef(it.id).orderBy(FIRESTORE_POSITION).getInBatches() } }.awaitAll() scouts.mapIndexed { index, scout -> scout.copy(metrics = metricsForScouts[index].map { metricParser.parseSnapshot(it) }) } } suspend fun CharSequence.isValidTeamUri(): Boolean { val uri = toString().formatAsTeamUri() ?: return true if (Patterns.WEB_URL.matcher(uri).matches()) return true if (Dispatchers.IO { File(uri).exists() }) return true return false } suspend fun String.formatAsTeamUri(): String? { val trimmedUrl = trim() if (trimmedUrl.isBlank()) return null if (Dispatchers.IO { File(this@formatAsTeamUri).exists() }) return this return if (trimmedUrl.contains("http://") || trimmedUrl.contains("https://")) { trimmedUrl } else { "http://$trimmedUrl" } } private fun Team.rawSet(refresh: Boolean, new: Boolean) { timestamp = if (refresh) Date(0) else Date() if (new) { firestoreBatch { set(ref, this@rawSet) set(teamDuplicatesRef.document(checkNotNull(uid)), mapOf(id to number), SetOptions.merge()) } } else { ref.set(this) }.logFailures("setTeam", ref, this) }
gpl-3.0
c8b7f60735ce2395f4815ace5346dc3e
32.640741
100
0.693934
4.147489
false
false
false
false
Resonious/discord-talker
src/main/kotlin/net/resonious/talker/Speech.kt
1
2119
package net.resonious.talker import marytts.LocalMaryInterface import net.dv8tion.jda.core.audio.AudioSendHandler import net.dv8tion.jda.core.entities.Message import javax.sound.sampled.AudioInputStream import javax.sound.sampled.AudioSystem const val SEGMENT_SIZE = 3840 class Speech( val mary: LocalMaryInterface, val message: Message, val voice: Data.Voice, val onDone: (Speech) -> Unit ) : AudioSendHandler { val text: String = message.contentStripped var originalInputStream = generateAudio() var inputStream = originalInputStream var done = false val guild = message.guild private var ranCallback = false private var nextSegment = ByteArray(SEGMENT_SIZE) private val myFormat get() = inputStream.format private val inputFormat get() = AudioSendHandler.INPUT_FORMAT init { println("Received message: \"$text\"") // Convert input try { if (myFormat != inputFormat) { inputStream = AudioSystem.getAudioInputStream(inputFormat, inputStream) } } catch (e: Exception) { done = true throw e } } fun generateAudio(): AudioInputStream { mary.voice = voice.maryVoice mary.audioEffects = voice.maryEffects var inputText = text if (!inputText.endsWith('.')) inputText += '.' // TODO do more processing, maybe generate ssml doc return mary.generateAudio(inputText) } fun advanceSegment(): Boolean { if (done) return false nextSegment.fill(0) val bytesRead = inputStream.read(nextSegment) if (bytesRead < nextSegment.size) { done = true return bytesRead > 0 } else return true } override fun canProvide(): Boolean { if (!done) return advanceSegment() else if (!ranCallback) { ranCallback = true; onDone(this); return false } else return false } override fun provide20MsAudio(): ByteArray? { return nextSegment } }
gpl-3.0
2dccd5420cc9d8cce5308beaf26d67ab
25.17284
87
0.625295
4.64693
false
false
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/data/converters/SimpleDateConverter.kt
1
2094
package com.garpr.android.data.converters import com.garpr.android.data.models.SimpleDate import com.garpr.android.extensions.require import com.squareup.moshi.FromJson import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import com.squareup.moshi.ToJson import java.text.ParseException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone object SimpleDateConverter { private val UTC = TimeZone.getTimeZone("UTC") private val FORMAT = object : ThreadLocal<SimpleDateFormat>() { override fun initialValue(): SimpleDateFormat? { val format = SimpleDateFormat("MM/dd/yy", Locale.US) format.isLenient = false format.timeZone = UTC return format } } @FromJson fun fromJson(reader: JsonReader): SimpleDate? { when (val token = reader.peek()) { JsonReader.Token.NULL -> { return reader.nextNull() } JsonReader.Token.NUMBER -> { val timeLong = reader.nextLong() return SimpleDate(Date(timeLong)) } JsonReader.Token.STRING -> { val string = reader.nextString() val format = FORMAT.require() val date: Date? = try { format.parse(string) } catch (e: ParseException) { // this Exception can be safely ignored null } if (date != null) { return SimpleDate(date) } throw JsonDataException("Can't parse SimpleDate, unsupported format: \"$string\"") } else -> { throw JsonDataException("Can't parse SimpleDate, unsupported token: \"$token\"") } } } @ToJson fun toJson(writer: JsonWriter, value: SimpleDate?) { if (value != null) { writer.value(value.date.time) } } }
unlicense
b2eee53e206581766028d60cbc9762c9
28.083333
98
0.575454
4.997613
false
false
false
false
uber/RIBs
android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/off_game/OffGameView.kt
1
2525
/* * Copyright (C) 2021. Uber Technologies * * 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.uber.rib.compose.root.main.logged_in.off_game import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.uber.rib.compose.util.CustomButton import com.uber.rib.compose.util.EventStream @Composable fun OffGameView(viewModel: State<OffGameViewModel>, eventStream: EventStream<OffGameEvent>) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp, alignment = Alignment.Bottom), ) { Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(text = viewModel.value.playerOne) Text(text = "Win Count: ${viewModel.value.playerOneWins}") } Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(text = viewModel.value.playerTwo) Text(text = "Win Count: ${viewModel.value.playerTwoWins}") } CustomButton( analyticsId = "26882559-fc45", onClick = { eventStream.notify(OffGameEvent.StartGame) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "START GAME") } } } @Preview @Composable fun OffGameViewPreview() { val viewModel = remember { mutableStateOf(OffGameViewModel("James", "Alejandro", 3, 0)) } OffGameView(viewModel, EventStream()) }
apache-2.0
28aca95f06f1c42131eaca589e5899a4
36.686567
95
0.758812
4.125817
false
false
false
false