path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
examples/src/test/kotlin/examples/onnx/cv/OnnxResNetTestSuite.kt
JetBrains
249,948,572
false
null
/* * Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package examples.onnx.cv import examples.onnx.cv.custom.resnet50CustomPrediction import examples.onnx.cv.custom.resnet50additionalTraining import examples.onnx.cv.efficicentnet.efficientNet4LitePrediction import examples.onnx.cv.resnet.* import examples.onnx.cv.runImageRecognitionPrediction import org.jetbrains.kotlinx.dl.api.inference.onnx.ONNXModels import org.junit.jupiter.api.Test class OnnxResNetTestSuite { @Test fun resnet18predictionTest() { resnet18prediction() } @Test fun resnet18easyPredictionTest() { resnet18easyPrediction() } @Test fun resnet18v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet18v2()) } @Test fun resnet34predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet34()) } @Test fun resnet34v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet34v2()) } @Test fun resnet50predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet50()) } @Test fun resnet50v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet50v2()) } @Test fun resnet50additionalTrainingTest() { resnet50additionalTraining() } @Test fun resnet50CustomPredictionTest() { resnet50CustomPrediction() } @Test fun resnet101predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet101()) } @Test fun resnet101v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet101v2()) } @Test fun resnet152predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet152()) } @Test fun resnet152v2predictionTest() { runImageRecognitionPrediction(ONNXModels.CV.ResNet152v2()) } @Test fun efficientNet4LitePredictionTest(){ efficientNet4LitePrediction() } }
81
null
79
806
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
2,168
KotlinDL
Apache License 2.0
android/app/src/main/java/com/fabirt/debty/constant/K.kt
virendersran01
353,795,029
true
{"Kotlin": 119324}
package com.fabirt.debty.constant object K { const val DATABASE_NAME = "debty.db" // Must be the same as the declared in xml-v25/shortcuts.xml data attribute from intent. const val SHORTCUT_DATA_MOVEMENT_ASSISTANT = "debty.assistant.movement" // Must be the same as the declared manifest provider authorities attribute. const val FILE_PROVIDER_AUTHORITIES = "com.fabirt.fileprovider" const val APP_UPDATE_NOTIFICATION_CHANNEL_ID = "525479210" const val APP_UPDATE_NOTIFICATION_ID = 415021 }
0
null
0
1
6230c4caa0914ca2d7480d365287bae5a68fa897
524
debty-v2
MIT License
src/main/kotlin/monster/loli/catcatdmdata/entity/CatClient.kt
kokolokksk
473,437,812
false
null
package monster.loli.catcatdmdata.entity data class CatClient( var clientId:String = "", var ts:Long = 0, var ip:String = "", var userAgent:String = "", var version:String = "" )
0
Kotlin
0
0
009ae45ec7ceb767e24bacd0bafea5074268f42a
201
catcat-dm-data
MIT License
projects/forge/src/main/kotlin/site/siredvin/peripheralworks/client/model/FlexibleRealityAnchor.kt
SirEdvin
489,471,520
false
null
package site.siredvin.peripheralworks.client.model import net.minecraft.client.Minecraft import net.minecraft.client.multiplayer.ClientLevel import net.minecraft.client.renderer.RenderType import net.minecraft.client.renderer.block.model.BakedQuad import net.minecraft.client.renderer.block.model.ItemOverrides import net.minecraft.client.renderer.block.model.ItemTransforms import net.minecraft.client.renderer.texture.TextureAtlasSprite import net.minecraft.client.resources.model.BakedModel import net.minecraft.core.BlockPos import net.minecraft.core.Direction import net.minecraft.nbt.NbtUtils import net.minecraft.resources.ResourceLocation import net.minecraft.util.RandomSource import net.minecraft.world.entity.LivingEntity import net.minecraft.world.item.ItemStack import net.minecraft.world.level.BlockAndTintGetter import net.minecraft.world.level.block.state.BlockState import net.minecraftforge.client.ChunkRenderTypeSet import net.minecraftforge.client.model.IDynamicBakedModel import net.minecraftforge.client.model.data.ModelData import net.minecraftforge.client.model.data.ModelProperty import site.siredvin.peripheralium.common.blocks.BaseNBTBlock import site.siredvin.peripheralium.xplat.XplatRegistries import site.siredvin.peripheralworks.client.util.RenderUtils.getTexture import site.siredvin.peripheralworks.common.block.FlexibleRealityAnchor import site.siredvin.peripheralworks.common.blockentity.FlexibleRealityAnchorBlockEntity import site.siredvin.peripheralworks.common.setup.Blocks val emptyFlexibleRealityAnchorModel by lazy { Minecraft.getInstance().blockRenderer.getBlockModel(Blocks.FLEXIBLE_REALITY_ANCHOR.get().defaultBlockState()) } object FlexibleRealityAnchorModel : IDynamicBakedModel { val MIMIC = ModelProperty<BlockState>() override fun getQuads( state: BlockState?, side: Direction?, rand: RandomSource, extraData: ModelData, renderType: RenderType?, ): MutableList<BakedQuad> { val mimic = extraData.get(MIMIC) if (mimic != null && mimic.block !is FlexibleRealityAnchor) { val model: BakedModel = Minecraft.getInstance().blockRenderer.getBlockModel(mimic) return model.getQuads(mimic, side, rand, extraData, renderType) } return mutableListOf() } override fun useAmbientOcclusion(): Boolean = true override fun isGui3d(): Boolean = true override fun usesBlockLight(): Boolean = false override fun isCustomRenderer(): Boolean = false override fun getRenderTypes(state: BlockState, rand: RandomSource, data: ModelData): ChunkRenderTypeSet { return ChunkRenderTypeSet.of(RenderType.cutout()) } override fun getParticleIcon(): TextureAtlasSprite = getTexture(ResourceLocation("minecraft:block/stone")) override fun getTransforms(): ItemTransforms = emptyFlexibleRealityAnchorModel.transforms override fun getOverrides(): ItemOverrides = FlexibleRealityAnchorItemOverrides override fun getModelData( level: BlockAndTintGetter, pos: BlockPos, state: BlockState, modelData: ModelData, ): ModelData { val blockEntity = level.getBlockEntity(pos) if (blockEntity !is FlexibleRealityAnchorBlockEntity || blockEntity.mimic == null) return super.getModelData(level, pos, state, modelData) return modelData.derive().with(MIMIC, blockEntity.mimic).build() } } object FlexibleRealityAnchorItemOverrides : ItemOverrides() { override fun resolve( pModel: BakedModel, pStack: ItemStack, pLevel: ClientLevel?, pEntity: LivingEntity?, pSeed: Int, ): BakedModel? { val mimic = pStack.getTagElement(BaseNBTBlock.INTERNAL_DATA_TAG)?.getCompound( FlexibleRealityAnchorBlockEntity.MIMIC_TAG, ) ?: return emptyFlexibleRealityAnchorModel if (mimic.isEmpty) return emptyFlexibleRealityAnchorModel val mimicState = NbtUtils.readBlockState(XplatRegistries.BLOCKS, mimic) if (mimicState.isAir) return emptyFlexibleRealityAnchorModel return Minecraft.getInstance().blockRenderer.getBlockModel(mimicState) } }
3
null
3
9
a59b8b79e5df1de388bba9fb0d8effe5763e569b
4,170
UnlimitedPeripheralWorks
MIT License
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/entities/LinkedListEntity.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.entities import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityWithPersistentId import com.intellij.workspaceModel.storage.impl.* internal data class LinkedListEntityId(val name: String) : PersistentEntityId<LinkedListEntity>() { override val parentId: PersistentEntityId<*>? get() = null override val presentableName: String get() = name } @Suppress("unused") internal class LinkedListEntityData : WorkspaceEntityData.WithCalculablePersistentId<LinkedListEntity>() { lateinit var name: String lateinit var next: LinkedListEntityId override fun createEntity(snapshot: WorkspaceEntityStorage): LinkedListEntity { return LinkedListEntity(name, next).also { addMetaData(it, snapshot) } } override fun persistentId(): LinkedListEntityId = LinkedListEntityId(name) } internal class LinkedListEntity( val name: String, val next: LinkedListEntityId ) : WorkspaceEntityWithPersistentId, WorkspaceEntityBase() { override fun persistentId(): LinkedListEntityId = LinkedListEntityId(name) } internal class ModifiableLinkedListEntity : ModifiableWorkspaceEntityBase<LinkedListEntity>() { var name: String by EntityDataDelegation() var next: LinkedListEntityId by EntityDataDelegation() } internal fun WorkspaceEntityStorageBuilderImpl.addLinkedListEntity(name: String, next: LinkedListEntityId) = addEntity(ModifiableLinkedListEntity::class.java, SampleEntitySource("test")) { this.name = name this.next = next }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,773
intellij-community
Apache License 2.0
domain/src/main/kotlin/no/nav/su/se/bakover/domain/behandling/BehandlingsinformasjonTestdataBuilder.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.domain.behandling import org.jetbrains.annotations.TestOnly /** * Dette er kanskje ikke den beste plassen å legge ting som kun skal brukes i tester. * Se også SøknadInnholdTestdataBuilder */ @TestOnly fun Behandlingsinformasjon.withAlleVilkårOppfylt() = Behandlingsinformasjon( flyktning = Behandlingsinformasjon.Flyktning( status = Behandlingsinformasjon.Flyktning.Status.VilkårOppfylt, begrunnelse = flyktning?.begrunnelse, ), lovligOpphold = Behandlingsinformasjon.LovligOpphold( status = Behandlingsinformasjon.LovligOpphold.Status.VilkårOppfylt, begrunnelse = lovligOpphold?.begrunnelse, ), fastOppholdINorge = Behandlingsinformasjon.FastOppholdINorge( status = Behandlingsinformasjon.FastOppholdINorge.Status.VilkårOppfylt, begrunnelse = fastOppholdINorge?.begrunnelse, ), institusjonsopphold = Behandlingsinformasjon.Institusjonsopphold( status = Behandlingsinformasjon.Institusjonsopphold.Status.VilkårOppfylt, begrunnelse = institusjonsopphold?.begrunnelse, ), formue = Behandlingsinformasjon.Formue( status = Behandlingsinformasjon.Formue.Status.VilkårOppfylt, verdier = Behandlingsinformasjon.Formue.Verdier( verdiIkkePrimærbolig = formue?.verdier?.verdiIkkePrimærbolig ?: 0, verdiEiendommer = formue?.verdier?.verdiEiendommer ?: 0, verdiKjøretøy = formue?.verdier?.verdiKjøretøy ?: 0, innskudd = formue?.verdier?.innskudd ?: 0, verdipapir = formue?.verdier?.verdipapir ?: 0, pengerSkyldt = formue?.verdier?.pengerSkyldt ?: 0, kontanter = formue?.verdier?.kontanter ?: 0, depositumskonto = formue?.verdier?.depositumskonto ?: 0, ), epsVerdier = null, begrunnelse = formue?.begrunnelse, ), personligOppmøte = Behandlingsinformasjon.PersonligOppmøte( status = Behandlingsinformasjon.PersonligOppmøte.Status.MøttPersonlig, begrunnelse = personligOppmøte?.begrunnelse, ), ) @TestOnly fun Behandlingsinformasjon.withAlleVilkårAvslått() = Behandlingsinformasjon( flyktning = Behandlingsinformasjon.Flyktning( status = Behandlingsinformasjon.Flyktning.Status.VilkårIkkeOppfylt, begrunnelse = flyktning?.begrunnelse, ), lovligOpphold = Behandlingsinformasjon.LovligOpphold( status = Behandlingsinformasjon.LovligOpphold.Status.VilkårIkkeOppfylt, begrunnelse = lovligOpphold?.begrunnelse, ), fastOppholdINorge = Behandlingsinformasjon.FastOppholdINorge( status = Behandlingsinformasjon.FastOppholdINorge.Status.VilkårIkkeOppfylt, begrunnelse = fastOppholdINorge?.begrunnelse, ), institusjonsopphold = Behandlingsinformasjon.Institusjonsopphold( status = Behandlingsinformasjon.Institusjonsopphold.Status.VilkårIkkeOppfylt, begrunnelse = institusjonsopphold?.begrunnelse, ), formue = Behandlingsinformasjon.Formue( status = Behandlingsinformasjon.Formue.Status.VilkårIkkeOppfylt, verdier = Behandlingsinformasjon.Formue.Verdier( verdiIkkePrimærbolig = formue?.verdier?.verdiIkkePrimærbolig ?: 90000000, verdiEiendommer = formue?.verdier?.verdiEiendommer ?: 0, verdiKjøretøy = formue?.verdier?.verdiKjøretøy ?: 0, innskudd = formue?.verdier?.innskudd ?: 0, verdipapir = formue?.verdier?.verdipapir ?: 0, pengerSkyldt = formue?.verdier?.pengerSkyldt ?: 0, kontanter = formue?.verdier?.kontanter ?: 0, depositumskonto = formue?.verdier?.depositumskonto ?: 0, ), epsVerdier = null, begrunnelse = formue?.begrunnelse, ), personligOppmøte = Behandlingsinformasjon.PersonligOppmøte( status = Behandlingsinformasjon.PersonligOppmøte.Status.IkkeMøttPersonlig, begrunnelse = personligOppmøte?.begrunnelse, ), ) @TestOnly fun Behandlingsinformasjon.withAvslåttFlyktning(): Behandlingsinformasjon { return withAlleVilkårOppfylt().patch( Behandlingsinformasjon( flyktning = Behandlingsinformasjon.Flyktning( status = Behandlingsinformasjon.Flyktning.Status.VilkårIkkeOppfylt, begrunnelse = flyktning?.begrunnelse, ), ), ) } @TestOnly fun withVilkårIkkeVurdert() = Behandlingsinformasjon( flyktning = null, lovligOpphold = null, fastOppholdINorge = null, institusjonsopphold = null, formue = null, personligOppmøte = null, )
6
Kotlin
0
0
b0864f973c8986f58af07c4bc7f601caa602dbfc
4,909
su-se-bakover
MIT License
platform/collaboration-tools/src/com/intellij/collaboration/async/CoroutineUtil.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.collaboration.async import com.intellij.collaboration.util.ComputedResult import com.intellij.collaboration.util.HashingUtil import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.intellij.platform.util.coroutines.childScope import com.intellij.util.cancelOnDispose import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.HashingStrategy import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.future.asDeferred import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.jetbrains.annotations.ApiStatus import java.util.concurrent.CompletableFuture import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext inline fun <reified T> T.classAsCoroutineName() = CoroutineName(T::class.java.name) inline fun <reified T> classAsCoroutineName() = CoroutineName(T::class.java.name) /** * Prefer creating a service to supply a parent scope */ @ApiStatus.Obsolete @Suppress("FunctionName") fun DisposingMainScope(parentDisposable: Disposable): CoroutineScope { return MainScope().also { Disposer.register(parentDisposable) { it.cancel() } } } /** * Prefer creating a service to supply a parent scope */ @ApiStatus.Obsolete fun Disposable.disposingMainScope(): CoroutineScope = DisposingMainScope(this) /** * Prefer creating a service to supply a parent scope */ @ApiStatus.Obsolete fun Disposable.disposingScope(context: CoroutineContext = SupervisorJob()): CoroutineScope = CoroutineScope(context).also { Disposer.register(this) { it.cancel() } } @OptIn(InternalCoroutinesApi::class) @ApiStatus.Experimental fun CoroutineScope.nestedDisposable(): Disposable { val job = coroutineContext[Job] require(job != null) { "Found no Job in context: $coroutineContext" } return Disposer.newDisposable().also { job.invokeOnCompletion(onCancelling = true, handler = { _ -> Disposer.dispose(it) }) } } fun CoroutineScope.cancelledWith(disposable: Disposable): CoroutineScope = apply { val job = coroutineContext[Job] requireNotNull(job) { "Coroutine scope without a parent job $this" } job.cancelOnDispose(disposable, false) } fun CoroutineScope.launchNow(context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> Unit): Job = launch(context, CoroutineStart.UNDISPATCHED, block) /** * Similar to [launchIn], but starts the collection with [CoroutineStart.UNDISPATCHED] and allows overriding context */ fun <T> Flow<T>.launchNowIn(scope: CoroutineScope, context: CoroutineContext = EmptyCoroutineContext): Job = scope.launch(context, CoroutineStart.UNDISPATCHED) { collect() } @ApiStatus.Experimental fun <T1, T2, R> combineState(scope: CoroutineScope, state1: StateFlow<T1>, state2: StateFlow<T2>, transform: (T1, T2) -> R): StateFlow<R> = combine(state1, state2, transform) .stateIn(scope, SharingStarted.Eagerly, transform(state1.value, state2.value)) @ApiStatus.Experimental fun <T1, T2, T3, R> combineState(scope: CoroutineScope, state1: StateFlow<T1>, state2: StateFlow<T2>, state3: StateFlow<T3>, transform: (T1, T2, T3) -> R): StateFlow<R> = combine(state1, state2, state3, transform) .stateIn(scope, SharingStarted.Eagerly, transform(state1.value, state2.value, state3.value)) @ApiStatus.Experimental suspend fun <T1, T2> combineAndCollect( flow1: Flow<T1>, flow2: Flow<T2>, action: suspend (T1, T2) -> Unit ) { return combine(flow1, flow2) { value1, value2 -> value1 to value2 }.collect { (value1, value2) -> action(value1, value2) } } @ApiStatus.Experimental suspend fun <T1, T2, T3> combineAndCollect( flow1: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, action: suspend (T1, T2, T3) -> Unit ) { return combine(flow1, flow2, flow3) { value1, value2, value3 -> Triple(value1, value2, value3) }.collect { (value1, value2, value3) -> action(value1, value2, value3) } } fun Flow<Boolean>.inverted() = map { !it } @ApiStatus.Experimental fun <T, M> StateFlow<T>.mapState( scope: CoroutineScope, mapper: (value: T) -> M ): StateFlow<M> = map { mapper(it) }.stateIn(scope, SharingStarted.Eagerly, mapper(value)) @ApiStatus.Experimental fun <T, M> StateFlow<T>.mapState(mapper: (value: T) -> M): StateFlow<M> = DerivedStateFlow(map(mapper)) { mapper(value) } @ApiStatus.Experimental fun <T1, T2, R> StateFlow<T1>.combineState(other: StateFlow<T2>, combiner: (T1, T2) -> R): StateFlow<R> = DerivedStateFlow(combine(other, combiner)) { combiner(value, other.value) } /** * Special state flow which value is supplied by [valueSupplier] and collection is delegated to [source] * * [valueSupplier] should NEVER THROW to avoid contract violation * * * https://github.com/Kotlin/kotlinx.coroutines/issues/2631#issuecomment-870565860 */ private class DerivedStateFlow<T>( private val source: Flow<T>, private val valueSupplier: () -> T ) : StateFlow<T> { override val value: T get() = valueSupplier() override val replayCache: List<T> get() = listOf(value) @InternalCoroutinesApi override suspend fun collect(collector: FlowCollector<T>): Nothing { coroutineScope { source.distinctUntilChanged().stateIn(this).collect(collector) } } } @ApiStatus.Experimental fun <T, R> Flow<T>.mapScoped(mapper: CoroutineScope.(T) -> R): Flow<R> = mapScoped2(mapper) @ApiStatus.Experimental private fun <T, R> Flow<T>.mapScoped2(mapper: suspend CoroutineScope.(T) -> R): Flow<R> = flow { coroutineScope { var lastScope: CoroutineScope? = null val breaker = MutableSharedFlow<R>(1) try { launchNow { collect { state -> lastScope?.cancelAndJoinSilently() lastScope = childScope().apply { launchNow { val result = mapper(state) breaker.emit(result) } } } } breaker.collect(this@flow) } finally { lastScope?.cancelAndJoinSilently() } } } /** * Performs mapping only if the source value is not null */ @ApiStatus.Experimental fun <T, R> Flow<T?>.mapNullable(mapper: (T) -> R): Flow<R?> = map { it?.let(mapper) } /** * Performs mapping only if the source value is not null */ @OptIn(ExperimentalCoroutinesApi::class) @ApiStatus.Experimental fun <T, R> Flow<T?>.mapNullableLatest(mapper: suspend (T) -> R): Flow<R?> = mapLatest { if (it != null) mapper(it) else null } @ApiStatus.Experimental fun <T, R> Flow<T?>.mapNullableScoped(mapper: CoroutineScope.(T) -> R): Flow<R?> = mapScoped2 { if (it == null) null else mapper(it) } @ApiStatus.Experimental suspend fun <T> Flow<T>.collectScoped(block: suspend CoroutineScope.(T) -> Unit) = mapScoped2(block).collect() @ApiStatus.Experimental suspend fun <T> Flow<T>.collectWithPrevious(initial: T, collector: suspend (prev: T, current: T) -> Unit) { var prev = initial collect { collector(prev, it) prev = it } } @ApiStatus.Experimental fun <T> Flow<T>.withInitial(initial: T): Flow<T> = flow { emit(initial) emitAll(this@withInitial) } /** * In principle, it is an analogue of [stateIn] with [SharingStarted.Eagerly], * with a notable difference being that a [defaultValue] may never be emitted if a value is already available in the source flow */ fun <T> Flow<T>.stateInNow(cs: CoroutineScope, defaultValue: T): StateFlow<T> { val result = MutableStateFlow(defaultValue) cs.launchNow { collect(result) } return result.asStateFlow() } /** * Lazy shared flow that logs all exceptions as errors and never throws (beside cancellation) */ fun <T> Flow<T>.modelFlow(cs: CoroutineScope, log: Logger): SharedFlow<T> = catch { log.error(it) }.shareIn(cs, SharingStarted.Lazily, 1) /** * Associate each *item* [T] *key* [K] in the iterable from the receiver flow (source list) with a *value* [V] * Keys are distinguished by a [hashingStrategy] * * When a new iterable is received: * * a new [CoroutineScope] and a new value is created via [valueExtractor] for new items * * existing values are updated via [update] if it was supplied * * values for missing items are removed and destroyed via [destroy] * * Order of the values in the resulting map is the same as in the source iterable * All [CoroutineScope]'s of values are only active while the resulting flow is being collected */ fun <T, K, V> Flow<Iterable<T>>.associateCachingBy(keyExtractor: (T) -> K, hashingStrategy: HashingStrategy<K>, valueExtractor: CoroutineScope.(T) -> V, destroy: suspend V.() -> Unit, update: (suspend V.(T) -> Unit)? = null) : Flow<Map<K, V>> = flow { coroutineScope { val container = MappingScopedItemsContainer(this, keyExtractor, hashingStrategy, valueExtractor, destroy, update) launchNow { collect { items -> container.update(items) } } container.mappingState.collect { emit(it) } } } /** * Allows mapping a collection of items [T] to scoped (coroutine scope bound) values [V] * An intermittent key [K] is used to uniquely identify items * * @param cs parent scope for value scopes * @param keyExtractor should be a quick-to-run function extracting a key from item * @param hashingStrategy strategy used to compare keys * @param mapper factory function to create a value from item * @param destroy destructor function to destroy a value * @param update function used to update value if a new item is supplied for the existing key */ class MappingScopedItemsContainer<T, K, V>( private val cs: CoroutineScope, private val keyExtractor: (T) -> K, private val hashingStrategy: HashingStrategy<K>, private val mapper: CoroutineScope.(T) -> V, private val destroy: suspend V.() -> Unit, private val update: (suspend V.(T) -> Unit)? = null ) { private val _mappingState = MutableStateFlow<Map<K, ScopingWrapper<V>>>(emptyMap()) val mappingState: StateFlow<Map<K, V>> = _mappingState.mapState { it.mapValues { (_, value) -> value.value } } private val mapGuard = Mutex() suspend fun update(items: Iterable<T>) = mapGuard.withLock { withContext(NonCancellable) { val currentMap = _mappingState.value var hasStructureChanges = false val newItemsSet = CollectionFactory.createLinkedCustomHashingStrategySet(hashingStrategy).also { items.mapTo(it, keyExtractor) } val result = createLinkedMap<K, ScopingWrapper<V>>(hashingStrategy) // destroy missing for ((key, scopedValue) in currentMap) { if (!newItemsSet.contains(key)) { hasStructureChanges = true scopedValue.value.destroy() scopedValue.cancel() } else { result[key] = scopedValue } } // add new or update existing for (item in items) { val itemKey = keyExtractor(item) val existing = result[itemKey] if (existing == null) { val valueScope = cs.childScope() result[itemKey] = ScopingWrapper(valueScope, mapper(valueScope, item)) hasStructureChanges = true } else { // if not inferring nullability fsr update?.let { existing.value.it(item) } result[itemKey] = existing } } if (hasStructureChanges) { _mappingState.value = result } } } suspend fun addIfAbsent(item: T): V = mapGuard.withLock { withContext(NonCancellable) { val key = keyExtractor(item) _mappingState.value[key]?.value ?: _mappingState.updateAndGet { val valueScope = cs.childScope() val newValue = ScopingWrapper(valueScope, mapper(valueScope, item)) it + (key to newValue) }[key]!!.value } } companion object { fun <T, V> byIdentity(cs: CoroutineScope, mapper: CoroutineScope.(T) -> V) = MappingScopedItemsContainer(cs, { it }, HashingStrategy.identity(), mapper, {}) } } private data class ScopingWrapper<T>(val scope: CoroutineScope, val value: T) { suspend fun cancel() = scope.cancelAndJoinSilently() } private fun <T, R> createLinkedMap(hashingStrategy: HashingStrategy<T>): MutableMap<T, R> = CollectionFactory.createLinkedCustomHashingStrategyMap(hashingStrategy) /** * @see associateCachingBy * * Shorthand for cases where key is the same as item destructor simply cancels the value scope */ private fun <T, R> Flow<Iterable<T>>.associateCaching(hashingStrategy: HashingStrategy<T>, mapper: CoroutineScope.(T) -> R, update: (suspend R.(T) -> Unit)? = null): Flow<Map<T, R>> { return associateCachingBy({ it }, hashingStrategy, { mapper(it) }, { }, update) } fun <ID : Any, T, R> Flow<Iterable<T>>.mapCaching(sourceIdentifier: (T) -> ID, mapper: CoroutineScope.(T) -> R, destroy: suspend R.() -> Unit, update: (suspend R.(T) -> Unit)? = null): Flow<List<R>> = associateCachingBy(sourceIdentifier, HashingStrategy.canonical(), mapper, destroy, update).map { it.values.toList() } /** * Creates a list of model objects from DTOs */ fun <T, R> Flow<Iterable<T>>.mapDataToModel(sourceIdentifier: (T) -> Any, mapper: CoroutineScope.(T) -> R, update: (suspend R.(T) -> Unit)): Flow<List<R>> = associateCaching(HashingUtil.mappingStrategy(sourceIdentifier), mapper, update).map { it.values.toList() } /** * Create a list of view models from models */ fun <T, R> Flow<Iterable<T>>.mapModelsToViewModels(mapper: CoroutineScope.(T) -> R): Flow<List<R>> = associateCaching(HashingStrategy.identity(), mapper).map { it.values.toList() } fun <T> Flow<Collection<T>>.mapFiltered(predicate: (T) -> Boolean): Flow<List<T>> = map { it.filter(predicate) } /** * Treats 'this' flow as representing a single list of results. Meaning each emitted value is accumulated * with the previous ones into a single list and re-emitted. */ fun <T> Flow<List<T>>.collectBatches(): Flow<List<T>> { val result = mutableListOf<T>() return transform { result.addAll(it) emit(result.toList()) } } /** * Hack class to wrap any type to ensure equality checking is done through referential equality only. */ private class ReferentiallyComparedValue<T : Any>(val value: T) { override fun equals(other: Any?): Boolean = value === other override fun hashCode(): Int = System.identityHashCode(value) } /** * Transforms a flow of consecutive successes. The flow is reset when a failure is encountered if [resetOnFailure] is `true`. * This means that, if [resetOnFailure] is `true`, the [transformer] block is called once for every series of consecutive * successes. If it is `false`, the [transformer] block is called only once with a flow that receives every success value. * * This acts as a replacement of consecutive `asResultFlow` and `throwFailure` and avoids that exceptions cancel the flow. */ @JvmName("transformConsecutiveResultSuccesses") fun <T, R> Flow<Result<T>>.transformConsecutiveSuccesses( resetOnFailure: Boolean = true, transformer: suspend Flow<T>.() -> Flow<R> ): Flow<Result<R>> = channelFlow { val successFlows = MutableStateFlow(ReferentiallyComparedValue(MutableSharedFlow<T>(1))) launchNow { successFlows .collectLatest { successes -> successes.value .transformer() .collect { send(Result.success(it)) } } } collect { it.fold( onSuccess = { v -> successFlows.value.value.emit(v) }, onFailure = { ex -> if (resetOnFailure) { successFlows.value = ReferentiallyComparedValue(MutableSharedFlow(1)) } send(Result.failure(ex)) } ) } } /** * Transforms a flow of consecutive successes. The flow is reset when a failure is encountered if [resetOnFailure] is `true`. * This means that, if [resetOnFailure] is `true`, the [transformer] block is called once for every series of consecutive * successes. If it is `false`, the [transformer] block is called only once with a flow that receives every success value. */ fun <T, R> Flow<ComputedResult<T>>.transformConsecutiveSuccesses( resetOnFailure: Boolean = true, transformer: suspend Flow<T>.() -> Flow<R> ): Flow<ComputedResult<R>> = channelFlow { val successFlows = MutableStateFlow(ReferentiallyComparedValue(MutableSharedFlow<T>(1))) launchNow { successFlows .collectLatest { successes -> successes.value .transformer() .collect { send(ComputedResult.success(it)) } } } collect { it.result?.fold( onSuccess = { v -> successFlows.value.value.emit(v) }, onFailure = { ex -> if (resetOnFailure) { successFlows.value = ReferentiallyComparedValue(MutableSharedFlow(1)) } send(ComputedResult.failure(ex)) } ) } } /** * Transforms the flow of some computation requests to a flow of computation states of this request * Will not emit "loading" state if the computation was completed before handling its state */ @JvmName("futureComputationState") @OptIn(ExperimentalCoroutinesApi::class) fun <T> Flow<CompletableFuture<T>>.computationState(): Flow<ComputedResult<T>> = transformLatest { request -> if (!request.isDone) { emit(ComputedResult.loading()) } try { val value = request.asDeferred().await() emit(ComputedResult.success(value)) } catch (e: Exception) { if (!CompletableFutureUtil.isCancellation(e)) { emit(ComputedResult.failure(e)) } } } /** * Transforms the flow of some computation requests to a flow of computation states of this request * Will not emit "loading" state if the computation was completed before handling its state */ @OptIn(ExperimentalCoroutinesApi::class) fun <T> Flow<Deferred<T>>.computationState(): Flow<ComputedResult<T>> = transformLatest { request -> if (!request.isCompleted) { emit(ComputedResult.loading()) } try { val value = request.await() emit(ComputedResult.success(value)) } catch (e: Exception) { if (e !is CancellationException) { emit(ComputedResult.failure(e)) } } } /** * Maps the flow of requests to a flow of successfully computed values */ fun <T> Flow<CompletableFuture<T>>.values(): Flow<T> = mapNotNull { try { it.asDeferred().await() } catch (_: Throwable) { null } } /** * Maps values in the flow to successful results and catches and wraps any exception into a failure result. */ fun <T> Flow<T>.asResultFlow(): Flow<Result<T>> = map { Result.success(it) }.catch { emit(Result.failure(it)) } /** * Maps a flow or results to a flow of a mapped result */ fun <T, R> Flow<Result<T>>.mapCatching(mapper: suspend (T) -> R): Flow<Result<R>> = map { it.mapCatching { value -> mapper(value) } } /** * Maps a flow or results to a flow of values from successful results. Failure results are re-thrown as exceptions. */ fun <T> Flow<Result<T>>.throwFailure(): Flow<T> = map { it.getOrThrow() } /** * Cancel the scope, await its completion but ignore the completion exception if any to void cancelling the caller */ suspend fun CoroutineScope.cancelAndJoinSilently() { val cs = this cs.coroutineContext[Job]?.cancelAndJoinSilently() ?: error("Missing Job in $this") } /** * Cancel the job, await its completion but ignore the completion exception if any to void cancelling the caller */ suspend fun Job.cancelAndJoinSilently() { val job = this try { job.cancelAndJoin() } catch (ignored: Exception) { } } /** * Await the deferred value and cancel if the waiting was canceled */ suspend fun <T> Deferred<T>.awaitCancelling(): T { return try { await() } catch (ce: CancellationException) { if (!isCompleted) cancel() throw ce } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
20,793
intellij-community
Apache License 2.0
src/main/kotlin/fr/chezbazar/aoc15/day1/Day1.kt
chezbazar
728,404,822
false
{"Kotlin": 100278}
package fr.chezbazar.aoc15.day1 import fr.chezbazar.computeFrom fun main() { computeFrom("aoc15/day1/input.txt") { println(computeFloor(it)) println(computeFirstBasementIndex(it)) } } fun computeFloor(entry: String) = entry.count { it == '(' } - entry.count { it == ')' } fun computeFirstBasementIndex(entry: String): Int { var currentFloor = 0 var nbInstructions = 0 entry.forEach { nbInstructions++ if (it == '(') currentFloor++ else currentFloor-- if (currentFloor < 0) return nbInstructions } throw Exception("Should have returned before") }
0
Kotlin
0
0
6d8a40f2cf8b56fb36ad2aae77bfd1e4142ab92e
617
adventofcode
MIT License
sqlite-embedder-chicory/src/jvmMain/kotlin/ChicoryRuntimeInstance.kt
illarionov
769,429,996
false
{"Kotlin": 1560774}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.chicory import ru.pixnews.wasm.sqlite.open.helper.WasmSqliteOpenHelperDsl import ru.pixnews.wasm.sqlite.open.helper.embedder.SqliteRuntimeInstance @WasmSqliteOpenHelperDsl public interface ChicoryRuntimeInstance : SqliteRuntimeInstance
4
Kotlin
0
3
35c3019efe126bba3e8973d54c2a3d4454c0ccb1
554
wasm-sqlite-open-helper
Apache License 2.0
src/loops/for.kt
anish-2903
742,851,112
false
{"Kotlin": 12545, "Shell": 131}
package loops fun main(args: Array<String>) { for ( i in 1..10) { println("i = $i") } for (i in 1 until 10) { println(i) } for (i in 10 downTo 1) { println(i) } for (i in 1 until 10 step 2) { println(i) } for (i in 1..10) { println(i) } }
0
Kotlin
0
0
b51f8ee901fdd262b48967d00b91239bbc3b53ac
324
Kotlin
MIT License
src/chain-wallet-libs/bindings/wallet-cordova/src/android/WalletPlugin.kt
input-output-hk
545,813,891
false
{"Rust": 8682970, "Python": 573625, "Shell": 103176, "Kotlin": 69222, "JavaScript": 64915, "CSS": 40161, "Nix": 31072, "Earthly": 29378, "Objective-C": 25263, "C": 20776, "TypeScript": 16582, "Handlebars": 13966, "Dockerfile": 10644, "PLpgSQL": 8202, "Perl": 1296}
package com.iohk.jormungandr_wallet; import android.util.Base64 import android.util.Log import org.apache.cordova.* import org.json.JSONException import org.json.JSONObject import java.text.Normalizer import java.text.Normalizer.Form import java.util.concurrent.atomic.AtomicInteger class WalletPlugin /** * Constructor. */ : CordovaPlugin() { @ExperimentalUnsignedTypes private val wallets: MutableMap<Int, Wallet> = mutableMapOf() private var nextWalletId = AtomicInteger() @ExperimentalUnsignedTypes private val settingsPool: MutableMap<Int, Settings> = mutableMapOf() private var nextSettingsId = AtomicInteger() @ExperimentalUnsignedTypes private val pendingTransactionsPool: MutableMap<Int, List<List<UByte>>> = mutableMapOf() private var nextPendingTransactionsId = AtomicInteger() @ExperimentalUnsignedTypes private val proposalPool: MutableMap<Int, Proposal> = mutableMapOf() private var nextProposalId = AtomicInteger() @ExperimentalUnsignedTypes private val conversionPool: MutableMap<Int, Conversion> = mutableMapOf() private var nextConversionId = AtomicInteger() /** * Sets the context of the Command. This can then be used to do things like get * file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ override fun initialize(cordova: CordovaInterface?, webView: CordovaWebView?) { super.initialize(cordova, webView) Log.d(TAG, "Initializing wallet plugin") } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into * JavaScript. * @return True if the action was valid, false if not. */ @ExperimentalUnsignedTypes @Throws(JSONException::class) override fun execute( action: String, args: CordovaArgs, callbackContext: CallbackContext ): Boolean { Log.d(TAG, "action: $action") when (action) { "WALLET_IMPORT_KEYS" -> walletImportKeys(args, callbackContext) "WALLET_RESTORE" -> walletRestore(args, callbackContext) "SYMMETRIC_CIPHER_DECRYPT" -> symmetricCipherDecrypt(args, callbackContext) "SETTINGS_NEW" -> settingsNew(args, callbackContext) "SETTINGS_GET" -> settingsGet(args, callbackContext) "WALLET_RETRIEVE_FUNDS" -> walletRetrieveFunds(args, callbackContext) "WALLET_VOTE" -> walletVote(args, callbackContext) "WALLET_TOTAL_FUNDS" -> walletTotalFunds(args, callbackContext) "WALLET_SPENDING_COUNTER" -> walletSpendingCounter(args, callbackContext) "WALLET_ID" -> walletId(args, callbackContext) "WALLET_SET_STATE" -> walletSetState(args, callbackContext) "WALLET_PENDING_TRANSACTIONS" -> walletPendingTransactions(args, callbackContext) "WALLET_CONFIRM_TRANSACTION" -> walletConfirmTransaction(args, callbackContext) "WALLET_CONVERT" -> walletConvert(args, callbackContext) "CONVERSION_TRANSACTIONS_SIZE" -> conversionTransactionsSize(args, callbackContext) "CONVERSION_TRANSACTIONS_GET" -> conversionTransactionsGet(args, callbackContext) "CONVERSION_IGNORED" -> conversionIgnored(args, callbackContext) "PENDING_TRANSACTIONS_SIZE" -> pendingTransactionsSize(args, callbackContext) "PENDING_TRANSACTIONS_GET" -> pendingTransactionsGet(args, callbackContext) "BLOCK_DATE_FROM_SYSTEM_TIME" -> blockDateFromSystemTime(args, callbackContext) "MAX_EXPIRATION_DATE" -> maxExpirationDate(args, callbackContext) "PROPOSAL_NEW_PUBLIC" -> proposalNewPublic(args, callbackContext) "PROPOSAL_NEW_PRIVATE" -> proposalNewPrivate(args, callbackContext) "FRAGMENT_ID" -> fragmentId(args, callbackContext) "WALLET_DELETE" -> walletDelete(args, callbackContext) "SETTINGS_DELETE" -> settingsDelete(args, callbackContext) "PROPOSAL_DELETE" -> proposalDelete(args, callbackContext) "PENDING_TRANSACTIONS_DELETE" -> pendingTransactionsDelete(args, callbackContext) "CONVERSION_DELETE" -> conversionDelete(args, callbackContext) else -> { Log.w(TAG, "not found: $action") return false } } return true } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletImportKeys(args: CordovaArgs, callbackContext: CallbackContext) { val accountKey = args.getArrayBuffer(0).toUByteArray().toList() val utxoKeys = args.getArrayBuffer(1).toUByteArray() val mappedKeys = utxoKeys.chunked(64).map { SecretKeyEd25519Extended(it) } try { val walletId = nextWalletId.incrementAndGet() wallets[walletId] = Wallet(SecretKeyEd25519Extended(accountKey), mappedKeys) callbackContext.success(walletId.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletRestore(args: CordovaArgs, callbackContext: CallbackContext) { val mnemonics = args.getString(0) cordova.threadPool.execute { try { val normalized: String = Normalizer.normalize(mnemonics, Form.NFKD) val wallet = Wallet.fromMnemonics(normalized, emptyList()) val walletId = nextWalletId.incrementAndGet() wallets[walletId] = wallet callbackContext.success(walletId) } catch (e: Exception) { callbackContext.error(e.message) } } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun symmetricCipherDecrypt(args: CordovaArgs, callbackContext: CallbackContext) { val password = args.getArrayBuffer(0).toUByteArray() val ciphertext = args.getArrayBuffer(1).toUByteArray() try { val decrypted = symmetricCipherDecrypt(password.toList(), ciphertext.toList()).toUByteArray() .toByteArray() callbackContext.success(decrypted) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun settingsNew(args: CordovaArgs, callbackContext: CallbackContext) { val block0Hash = args.getArrayBuffer(0).toUByteArray().toList() val discriminationInput = args.getInt(1) val fees = args[2] as JSONObject val block0Date = args.getString(3).toULong() val slotDuration = args.getString(4).toUByte() val era = args[5] as JSONObject val transactionMaxExpiryEpochs = args.getString(6).toUByte() try { val constant = fees.getString("constant").toULong() val coefficient = fees.getString("coefficient").toULong() val certificate = fees.getString("certificate").toULong() val certificatePoolRegistration = fees.getString("certificatePoolRegistration").toULong() val certificateStakeDelegation = fees.getString("certificateStakeDelegation").toULong() val certificateOwnerStakeDelegation = fees.getString("certificateOwnerStakeDelegation").toULong() val certificateVotePlan = fees.getString("certificateVotePlan").toULong() val certificateVoteCast = fees.getString("certificateVoteCast").toULong() val linearFees: LinearFee = LinearFee( constant, coefficient, certificate, PerCertificateFee( certificatePoolRegistration.toULong(), certificateStakeDelegation.toULong(), certificateOwnerStakeDelegation.toULong() ), PerVoteCertificateFee( certificateVotePlan.toULong(), certificateVoteCast.toULong() ) ) val discrimination: Discrimination = if (discriminationInput == 0) Discrimination.PRODUCTION else Discrimination.TEST val timeEra = TimeEra( era.getString("epochStart").toUInt(), era.getString("slotStart").toULong(), era.getString("slotsPerEpoch").toUInt() ) val settingsInit = SettingsRaw( linearFees, discrimination, block0Hash, block0Date, slotDuration, timeEra, transactionMaxExpiryEpochs ) val settingsId = nextSettingsId.incrementAndGet() settingsPool[settingsId] = Settings(settingsInit) callbackContext.success(settingsId.toString()) } catch (e: java.lang.Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun settingsGet(args: CordovaArgs, callbackContext: CallbackContext) { val settingsId = args.getInt(0) try { val settings = settingsPool[settingsId] val settingsRaw = settings?.settingsRaw() val fees = settingsRaw?.fees val discrimination: Discrimination? = settingsRaw?.discrimination val block0Hash = settingsRaw?.block0Hash?.toUByteArray() val feesJson = JSONObject().put("constant", fees?.constant.toString()) .put("coefficient", fees?.coefficient.toString()) .put("certificate", fees?.certificate.toString()) .put( "certificatePoolRegistration", fees?.perCertificateFees?.certificatePoolRegistration.toString() ) .put( "certificateStakeDelegation", fees?.perCertificateFees?.certificateStakeDelegation.toString() ) .put( "certificateOwnerStakeDelegation", fees?.perCertificateFees?.certificateOwnerStakeDelegation.toString() ) .put( "certificateVotePlan", fees?.perVoteCertificateFees?.certificateVotePlan.toString() ) .put( "certificateVoteCast", fees?.perVoteCertificateFees?.certificateVoteCast.toString() ) val result: JSONObject = JSONObject().put("fees", feesJson) .put( "discrimination", if (discrimination === Discrimination.PRODUCTION) 0 else 1 ) .put( "block0Hash", Base64.encodeToString( block0Hash?.asByteArray(), Base64.NO_WRAP ) ) callbackContext.success(result) } catch (e: java.lang.Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletRetrieveFunds(args: CordovaArgs, callbackContext: CallbackContext) { val walletPtr = args.getInt(0) val block0 = args.getArrayBuffer(1).toUByteArray().toList() val wallet = wallets[walletPtr] cordova.threadPool.execute { try { val settingsId = nextSettingsId.incrementAndGet() val settings: Settings = wallet?.retrieveFunds(block0)!! settingsPool[settingsId] = settings callbackContext.success(settingsId.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletVote(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val settingsId = args.getInt(1) val proposalId = args.getInt(2) val choice = args.getString(3).toUByte() val expirationDate = args[4] as JSONObject val epoch = expirationDate.getString("epoch").toUInt() val slot = expirationDate.getString("slot").toUInt() val wallet = wallets[walletId] val settings = settingsPool[settingsId] val proposal = proposalPool[proposalId] val validUntil = BlockDate(epoch, slot) try { val tx = wallet?.vote(settings!!, proposal!!, choice, validUntil) callbackContext.success(tx?.toUByteArray()?.toByteArray()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletTotalFunds(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val wallet = wallets[walletId] try { callbackContext.success(wallet?.totalValue().toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletSpendingCounter(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val wallet = wallets[walletId] try { callbackContext.success(wallet?.spendingCounter().toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletId(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val wallet = wallets[walletId] try { val id = wallet?.accountId()?.toUByteArray()?.toByteArray() callbackContext.success(id) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletSetState(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val value = args.getString(1).toULong() val counter = args.getString(2).toUInt() try { wallets[walletId]?.setState(value, counter) callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletPendingTransactions(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val wallet = wallets[walletId] try { val pendingTransactions = wallet?.pendingTransactions()!! val pid = nextPendingTransactionsId.incrementAndGet() pendingTransactionsPool[pid] = pendingTransactions callbackContext.success(pid) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletConfirmTransaction(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val fragmentId = args.getArrayBuffer(1).toUByteArray() val wallet = wallets[walletId] try { wallet?.confirmTransaction(fragmentId.toList()) callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletConvert(args: CordovaArgs, callbackContext: CallbackContext) { val walletId = args.getInt(0) val settingsId = args.getInt(1) val expirationDate = args[2] as JSONObject val epoch = expirationDate.getString("epoch").toULong() val slot = expirationDate.getString("slot").toULong() val wallet = wallets[walletId] val settings = settingsPool[settingsId] cordova.threadPool.execute { try { val conversion = wallet?.convert( settings!!, BlockDate( epoch.toUInt(), slot.toUInt() ) ) val conversionId = nextConversionId.incrementAndGet() conversionPool[conversionId] = conversion!! callbackContext.success(conversionId.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun pendingTransactionsSize(args: CordovaArgs, callbackContext: CallbackContext) { val pendingTransactionsId = args.getInt(0) val pendingTransactions = pendingTransactionsPool[pendingTransactionsId] try { val size = pendingTransactions?.size callbackContext.success(size.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun pendingTransactionsGet(args: CordovaArgs, callbackContext: CallbackContext) { val pendingTransactionsId = args.getInt(0) val index = args.getInt(1) try { val transaction = pendingTransactionsPool[pendingTransactionsId]?.get(index) callbackContext.success(transaction?.toUByteArray()?.toByteArray()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun blockDateFromSystemTime(args: CordovaArgs, callbackContext: CallbackContext) { val settingsId = args.getInt(0) val unixEpoch = args.getString(1).toULong() val settings = settingsPool[settingsId] try { val blockDate = blockDateFromSystemTime(settings!!, unixEpoch) val json = JSONObject().put("epoch", blockDate.epoch.toString()).put( "slot", blockDate.slot.toString() ) callbackContext.success(json) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun maxExpirationDate(args: CordovaArgs, callbackContext: CallbackContext) { val settingsId = args.getInt(0) val unixEpoch = args.getString(1).toULong() val settings = settingsPool[settingsId] try { val blockDate = maxExpirationDate(settings!!, unixEpoch) val json = JSONObject().put("epoch", blockDate.epoch.toString()).put( "slot", blockDate.slot.toString() ) callbackContext.success(json) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun proposalNewPublic(args: CordovaArgs, callbackContext: CallbackContext) { val votePlanId = args.getArrayBuffer(0).toUByteArray().toList() val index = args.getString(1).toUByte() val numChoices = args.getString(2).toUByte() try { val proposal = Proposal(votePlanId, index, numChoices, PayloadTypeConfig.Public) val proposalId = nextProposalId.incrementAndGet() proposalPool[proposalId] = proposal callbackContext.success(proposalId.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun proposalNewPrivate(args: CordovaArgs, callbackContext: CallbackContext) { val votePlanId = args.getArrayBuffer(0).toUByteArray().toList() val index = args.getString(1).toUByte() val numChoices = args.getString(2).toUByte() val encryptingVoteKey = args.getString(3) try { val proposal = Proposal( votePlanId, index, numChoices, PayloadTypeConfig.Private( encryptingVoteKey ) ) val proposalId = nextProposalId.incrementAndGet() proposalPool[proposalId] = proposal callbackContext.success(proposalId.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun fragmentId(args: CordovaArgs, callbackContext: CallbackContext) { val transaction = args.getArrayBuffer(0).toUByteArray().toList() try { val fragment = Fragment(transaction) val id = fragment.id() fragment.destroy() callbackContext.success(id.toUByteArray().toByteArray()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun conversionTransactionsSize(args: CordovaArgs, callbackContext: CallbackContext) { val conversionId = args.getInt(0) val conversion = conversionPool[conversionId] try { callbackContext.success(conversion?.fragments?.size.toString()) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun conversionTransactionsGet(args: CordovaArgs, callbackContext: CallbackContext) { val conversionId = args.getInt(0) val index = args.getInt(1) val conversion = conversionPool[conversionId] try { val transaction: ByteArray? = conversion?.fragments?.get(index)?.serialize()?.toUByteArray()?.toByteArray() callbackContext.success(transaction) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun conversionIgnored(args: CordovaArgs, callbackContext: CallbackContext) { val conversionId = args.getInt(0) val conversion = conversionPool[conversionId] try { val value = conversion?.ignoredValue val count = conversion?.ignoredCount val json = JSONObject().put("value", value).put("ignored", count) callbackContext.success(json) } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun walletDelete(args: CordovaArgs, callbackContext: CallbackContext) { val walletId: Int = args.getInt(0) try { wallets[walletId]?.destroy() callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun settingsDelete(args: CordovaArgs, callbackContext: CallbackContext) { val settingsId: Int = args.getInt(0) try { settingsPool[settingsId]?.destroy() callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun proposalDelete(args: CordovaArgs, callbackContext: CallbackContext) { val proposalId: Int = args.getInt(0) try { proposalPool.remove(proposalId) callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun pendingTransactionsDelete(args: CordovaArgs, callbackContext: CallbackContext) { val pid: Int = args.getInt(0) try { pendingTransactionsPool.remove(pid) callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } @ExperimentalUnsignedTypes @Throws(JSONException::class) private fun conversionDelete(args: CordovaArgs, callbackContext: CallbackContext) { val cid: Int = args.getInt(0) try { conversionPool.remove(cid) callbackContext.success() } catch (e: Exception) { callbackContext.error(e.message) } } companion object { const val TAG = "WALLET" } }
10
Rust
3
38
f17b5103f8529b5efe05ecb1564d182bbae136ed
25,038
catalyst-core
Apache License 2.0
app/src/main/java/com/alexvt/datapoints/entrypoints/DataPointCollectionTimeEventReceiver.kt
alex-vt
711,487,667
false
{"Kotlin": 19854}
package com.alexvt.datapoints.entrypoints import android.app.Activity import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Environment import android.os.IBinder import android.os.PowerManager import com.alexvt.datapoints.R import com.alexvt.datapoints.datacollection.recordDataPoint import com.alexvt.datapoints.datacollection.scheduleSingleCollectionAtNextMinuteStart import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class DataPointCollectionTimeEventReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { scheduleSingleCollectionAtNextMinuteStart(context) val isFilesystemAccessible = Environment.isExternalStorageManager() val isPowerSaving = (context.getSystemService(Context.POWER_SERVICE) as PowerManager).isPowerSaveMode val isIneligibleForDataPointCollection = !isFilesystemAccessible || isPowerSaving if (isIneligibleForDataPointCollection) { return } @OptIn(DelicateCoroutinesApi::class) GlobalScope.launch(Dispatchers.IO) { Intent(context, DataPointCollectionForegroundService::class.java).run { context.startForegroundService(this) val recordingStartTimeMillis = System.currentTimeMillis() recordDataPoint(recordingStartTimeMillis, context) val minUserInteractionDelayMillis = 5000L val remainingUserInteractionDelay = minUserInteractionDelayMillis - (System.currentTimeMillis() - recordingStartTimeMillis) delay(remainingUserInteractionDelay) context.stopService(this@run) } } } } class DataPointCollectionForegroundService : Service() { override fun onCreate() { super.onCreate() val dataPointCollectionChannelId = "DataPointCollection" (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) .createNotificationChannel( NotificationChannel( dataPointCollectionChannelId, "Data Point Collection", NotificationManager.IMPORTANCE_LOW, ) ) val notification = Notification.Builder(this, dataPointCollectionChannelId) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle("Data Point Collection") .setContentText("Collecting data point from device sensors in background...") .build() val dataPointCollectionNotificationId = 1 (getSystemService(Activity.NOTIFICATION_SERVICE) as NotificationManager) .cancel(dataPointCollectionNotificationId) startForeground(dataPointCollectionNotificationId, notification) } override fun onBind(intent: Intent?): IBinder? = null }
0
Kotlin
0
0
9285ad5055334807cad6cbe4f7c18fcd35d5aa1d
3,231
DataPoints
MIT License
src/test/kotlin/info/dgjones/barnable/concept/VariableSpaceTest.kt
jonesd
442,279,905
false
{"Kotlin": 474251}
/* * Copyright 2020 David G Jones * * 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 info.dgjones.barnable.concept import info.dgjones.barnable.episodic.EpisodicMemory import info.dgjones.barnable.nlp.TextSentence import info.dgjones.barnable.nlp.WordElement import info.dgjones.barnable.parser.* import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.lang.IllegalStateException class VariableSpaceTest { var space = VariableSpace(); @BeforeEach fun setup() { space = VariableSpace() } @Test fun `Can record and lookup variables`() { val variable = CompletableVariable("testField", space, "testVar") space.declareVariable(variable) assertSame(variable, space.getVariable("testVar")) } @Test() fun `Looking up unknown variable fails`() { assertThrows(NoSuchElementException::class.java, { space.getVariable("unknownVar") }) } @Test fun `Cannot replace variable`() { val variable = CompletableVariable("testField", space, "testVar") space.declareVariable(variable) assertThrows(IllegalStateException::class.java, { val overwrite = CompletableVariable("otherField", space, "testVar") space.declareVariable(overwrite) }) } @Test fun `Id sequence takes into account declared variables`() { assertEquals(1, space.nextVariableIndex()) space.declareVariable(CompletableVariable("field", space, "testVar")) assertEquals(2, space.nextVariableIndex()) } } class CompletableVariableTest { var space: VariableSpace = VariableSpace() // Word Context val defHolder = ConceptHolder(9) val testElement = WordElement("one", "", "","") val workingMemory = WorkingMemory() val sentenceContext = SentenceContext(TextSentence("test", listOf(testElement)), workingMemory, EpisodicMemory()) val wordContext = WordContext(0, "test", defHolder, sentenceContext) enum class TestFields(override val fieldName: String): Fields { // Related episodic concept identity Source("source"), Dependent1("dep1"), Dependent2("dep2") } @BeforeEach fun setup() { space = VariableSpace() } @Test fun `Create Variable Slot with name`() { var variable = CompletableVariable(TestFields.Source.fieldName, space, "testVar") assertEquals(Slot("source", Concept("*VAR.testVar*")), variable.sourceReference.variableSlot) } @Test fun `Create Variable Slot with generated name`() { var variable = CompletableVariable(TestFields.Source.fieldName, space) assertEquals(Slot("source", Concept("*VAR.1*")), variable.sourceReference.variableSlot) } @Test fun `Resolve variable`() { var variable = CompletableVariable(TestFields.Source.fieldName, space, "testVar") variable.complete(ConceptHolder(1, Concept("testResult")), wordContext) assertEquals(Slot("source", Concept("testResult")), variable.sourceReference.variableSlot) } @Test fun `Resolved variable value can be transformed`() { val upperCaseTransformer = ConceptTransformer { if (it != null) Concept(it.name.toUpperCase()) else null } var variable = CompletableVariable(TestFields.Source.fieldName, space, sourceExpression = upperCaseTransformer) variable.complete(ConceptHolder(1, Concept("testResult")), wordContext) assertEquals(Slot("source", Concept("TESTRESULT")), variable.sourceReference.variableSlot) } @Test fun `Can update dependent reference with resolved value`() { var source = CompletableVariable(TestFields.Source.fieldName, space, "testVar") var dependentSlot = source.addVariableReference(TestFields.Dependent1) assertEquals(Slot(TestFields.Dependent1, Concept("*VAR.testVar*")), dependentSlot) source.complete(ConceptHolder(1, Concept("resolvedValue")), wordContext) assertEquals(Slot(TestFields.Source, Concept("resolvedValue")), source.sourceReference.variableSlot) assertEquals(Slot(TestFields.Dependent1, Concept("resolvedValue")), dependentSlot) } @Test fun `Preserve changed dependent references if they no longer reference variable`() { var source = CompletableVariable(TestFields.Source.fieldName, space, "testVar") var dependentSlot = source.addVariableReference(TestFields.Dependent1) assertEquals(Slot(TestFields.Dependent1, Concept("*VAR.testVar*")), dependentSlot) dependentSlot.value = Concept("manualUpdate") source.complete(ConceptHolder(1, Concept("resolvedValue")), wordContext) assertEquals(Slot(TestFields.Source, Concept("resolvedValue")), source.sourceReference.variableSlot) assertEquals(Slot(TestFields.Dependent1, Concept("manualUpdate")), dependentSlot) } @Test fun `Should mark embedded resolved source concept as being Inside`() { var variable = CompletableVariable(TestFields.Source.fieldName, space, "testVar") val conceptHolder = ConceptHolder(1, Concept("testResult")) variable.complete(conceptHolder, wordContext) assertEquals(Slot(TestFields.Source, Concept("testResult")), variable.sourceReference.variableSlot) assertTrue(conceptHolder.hasFlag(ParserFlags.Inside)) } @Test fun `Can inject resolved value into provided Concept`() { var variable = CompletableVariable(TestFields.Source.fieldName, space, "testVar") val conceptHolder = ConceptHolder(1, Concept("testResult")) conceptHolder.value?.value("testChild", Concept("testChildValue")) val replacementConcept = Concept("replacementRoot") replacementConcept.value("replacementChild", Concept("replacementChildValue")) replacementConcept.value("testChild", conceptHolder.value) variable.overwriteResolvedHolder = replacementConcept variable.complete(conceptHolder, wordContext) val expectedSlot = Slot(TestFields.Source, Concept("replacementRoot")) expectedSlot.value?.value("replacementChild", Concept("replacementChildValue")) expectedSlot.value?.value("testChild", Concept("testResult")) expectedSlot.value?.value("testChild")?.value("testChild", Concept("testChildValue")) assertEquals(expectedSlot, variable.sourceReference.variableSlot) } } class VariableReferenceTest { }
1
Kotlin
0
0
b5b7453e2fe0b2ae7b21533db1b2b437b294c63f
7,036
barnable
Apache License 2.0
src/main/kotlin/io/github/raeperd/realworldspringbootkotlin/infrastructure/jpa/UserJpaRepository.kt
raeperd
495,124,396
false
null
package io.github.raeperd.realworldspringbootkotlin.infrastructure.jpa import io.github.raeperd.realworldspringbootkotlin.domain.Password import io.github.raeperd.realworldspringbootkotlin.domain.User import io.github.raeperd.realworldspringbootkotlin.domain.UserRepository import org.springframework.data.jpa.repository.EntityGraph import org.springframework.data.jpa.repository.JpaRepository class UserJpaRepository( private val userEntityRepository: UserEntityRepository ) : UserRepository { override fun saveNewUser(email: String, username: String, password: Password): User { return createUserEntity(email, username, password) .let { user -> userEntityRepository.save(user) } } override fun findUserByEmail(email: String): User? { return userEntityRepository.findFirstByEmail(email) } override fun findUserById(id: Long): User? { return userEntityRepository.findFirstById(id) } override fun findUserByUsername(name: String): User? { return userEntityRepository.findFirstByUsername(name) } override fun saveUser(user: User): User { if (user is UserEntity) { return userEntityRepository.save(user) } throw IllegalArgumentException("Invalid user argument. expected UserEntity but ${user.javaClass} given") } private fun createUserEntity(email: String, username: String, password: Password): UserEntity { return UserEntity( email = email, username = username, password = <PASSWORD>, bio = "", image = null ) } } interface UserEntityRepository : JpaRepository<UserEntity, Long> { @EntityGraph(attributePaths = ["followingUsers"]) fun findFirstByEmail(email: String): User? @EntityGraph(attributePaths = ["followingUsers"]) fun findFirstByUsername(username: String): User? @EntityGraph(attributePaths = ["followingUsers"]) fun findFirstById(id: Long): User? }
0
Kotlin
2
6
8e6b63905816d94a2b34f21ba8f8b208adf5640b
2,001
realworld-springboot-kotlin
MIT License
libs/core/src/main/kotlin/micro/apps/core/extensions.kt
xmlking
236,108,779
false
null
package micro.apps.core import java.time.DayOfWeek import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.temporal.TemporalAdjusters import java.util.Date import java.util.Locale import java.util.Optional /** * Format an Instant as an ISO8601 timestamp */ fun Instant.toISO8601(): String = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") .withZone(ZoneId.of("UTC")).format(this) /** * Format a LocalDate in ISO8601 format */ fun LocalDate.toISO8601(): String = DateTimeFormatter.ofPattern("yyyy-MM-dd") .withZone(ZoneId.of("UTC")).format(this) /** * Find the day of week of an Instant */ fun Instant.firstDayOfWeek(): LocalDate = this.atZone(ZoneId.of("UTC")).toLocalDate() .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) /** * Execute a block of code when a variable is not null */ fun <T : Any> T?.whenNotNull(callback: (it: T) -> Unit) { if (this != null) callback(this) } /** * Execute a block of code when a variable is null */ fun <T : Any> T?.whenNull(callback: () -> Unit) { this ?: callback() } /** * Create PST Date */ fun dateOf(year: Int, month: Int, day: Int): Date = Date.from(LocalDate.of(year, month, day).atStartOfDay(ZoneId.of("America/Los_Angeles")).toInstant()) /** * convert java.util.Optional to kotlin Nullable and vice versa * val msg: Something? = optional.toNullable() // the type is enforced */ fun <T : Any> Optional<T>.toNullable(): T? = orElse(null) fun <T : Any> T?.toOptional(): Optional<T> = Optional.ofNullable(this) /** * Get property value dynamically from Any object. * Usage: * val p = Person("Jane", true) * val name = p.getThroughReflection<String>("name") * val employed = p.getThroughReflection<Boolean>("employed") */ inline fun <reified T : Any> Any.getThroughReflection(propertyName: String): T? { val getterName = "get" + propertyName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } return try { javaClass.getMethod(getterName).invoke(this) as? T } catch (e: NoSuchMethodException) { null } }
9
null
11
48
135c0f6b8ccfe17121a367bbfdd8024c77ea3c51
2,173
micro-apps
MIT License
app/src/main/java/com/duckduckgo/app/global/view/DividerAdapter.kt
cmonfortep
252,403,423
true
{"Kotlin": 6042652, "HTML": 42259, "Java": 35279, "JavaScript": 8281, "Ruby": 7654, "C++": 1820, "CMake": 1298, "Shell": 784}
/* * Copyright (c) 2021 DuckDuckGo * * 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.duckduckgo.app.global.view import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.duckduckgo.app.browser.databinding.ViewItemDividerBinding class DividerAdapter : RecyclerView.Adapter<DividerAdapter.DividerViewHolder>() { class DividerViewHolder(binding: ViewItemDividerBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): DividerViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ViewItemDividerBinding.inflate(inflater, parent, false) return DividerViewHolder(binding) } override fun onBindViewHolder( holder: DividerViewHolder, position: Int ) { // noop } override fun getItemCount(): Int = 1 }
5
Kotlin
0
3
228a1217aad96d19f90750d94664b7a4a5744c9a
1,473
Android
Apache License 2.0
app/src/main/java/com/iamageo/nottye/Utils.kt
iamageo
530,276,279
false
{"Kotlin": 72534, "HTML": 7664}
package com.iamageo.nottye import com.iamageo.nottye.ui.theme.* class Utils { companion object { val NottyeColors = listOf( RedA100, PinkA100, PurpleA100, DeepPurpleA100, IndigoA100, BlueA100 ) } }
0
Kotlin
0
2
3e9de7c362fae74b5a73057ce196de88297185e3
295
Nottye
Apache License 2.0
gitnote-jetbrains/src/main/kotlin/io/cjlee/gitnote/jcef/protocol/JcefInjectionLoadHandler.kt
cjlee38
780,015,519
false
{"Kotlin": 37601, "Rust": 19519, "JavaScript": 11779, "HTML": 896}
package io.cjlee.gitnote.jcef.protocol import com.intellij.ui.jcef.JBCefJSQuery import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter /** * This class is responsible for injecting the JavaScript bridge into the loaded page. */ class JcefInjectionLoadHandler( private val jsQuery: JBCefJSQuery, ): CefLoadHandlerAdapter() { override fun onLoadingStateChange( browser: CefBrowser?, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean ) { if (!isLoading) { // The page has finished loading injectJavascriptBridge(browser, jsQuery) } } private fun injectJavascriptBridge(browser: CefBrowser?, jsQuery: JBCefJSQuery) { // TODO : might need to handle response/error val script = """window.sendMessageToIde = function(type, payload, id) { const msg = JSON.stringify({type, payload, id}); ${jsQuery.inject("msg")} }""".trimIndent() browser?.executeJavaScript(script, browser.url, 0) } }
2
Kotlin
0
2
c355dfdf7727a61b3e20b33a7344e46252458b1b
1,084
gitnote
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/wilderness/lundail.plugin.kts
2011Scape
578,880,245
false
null
import gg.rsmod.plugins.content.mechanics.shops.CoinCurrency val lundail = Npcs.LUNDAIL create_shop( "Lundail's Arena-side Rune Shop", currency = CoinCurrency(), purchasePolicy = PurchasePolicy.BUY_STOCK, containsSamples = false, ) { items[0] = ShopItem(Items.FIRE_RUNE, amount = 1000, sellPrice = 17, buyPrice = 5) items[1] = ShopItem(Items.WATER_RUNE, amount = 1000, sellPrice = 17, buyPrice = 5) items[2] = ShopItem(Items.AIR_RUNE, amount = 100, sellPrice = 17, buyPrice = 5) items[3] = ShopItem(Items.EARTH_RUNE, amount = 100, sellPrice = 17, buyPrice = 5) items[4] = ShopItem(Items.MIND_RUNE, amount = 100, sellPrice = 17, buyPrice = 5) items[5] = ShopItem(Items.BODY_RUNE, amount = 100, sellPrice = 16, buyPrice = 4) items[6] = ShopItem(Items.NATURE_RUNE, amount = 300, sellPrice = 372, buyPrice = 111) items[7] = ShopItem(Items.CHAOS_RUNE, amount = 300, sellPrice = 140, buyPrice = 42) items[8] = ShopItem(Items.LAW_RUNE, amount = 100, sellPrice = 378, buyPrice = 113) items[9] = ShopItem(Items.COSMIC_RUNE, amount = 100, sellPrice = 232, buyPrice = 69) items[10] = ShopItem(Items.DEATH_RUNE, amount = 300, sellPrice = 310, buyPrice = 93) } on_npc_option(lundail, option = "talk-to") { player.queue { lundailDialogue(this) } } on_npc_option(lundail, option = "trade") { player.openShop("Lundail's Arena-side Rune Shop") } suspend fun lundailDialogue(it: QueueTask) { it.chatNpc("How can I help you, brave adventurer?") val option = it.options("What are you selling?", "What's that big old building above us?", "Claim free runes.") // TODO: ADD Claim free runes option after coding wilderness tasks. when (option) { 1 -> whatAreYouSelling(it) 2 -> whatsThatBigOldBuilding(it) } } suspend fun whatAreYouSelling(it: QueueTask) { it.chatPlayer("What are you selling?") it.chatNpc( "I sell rune stones. I've got some good stuff,", "some really powerful little rocks. Take a look.", ) it.player.openShop("Lundail's Arena-side Rune Shop") } suspend fun whatsThatBigOldBuilding(it: QueueTask) { it.chatPlayer("What's that big old building above us?") it.chatNpc( "That, my friend, is the mage battle arena.", "Top mages come from all over Gielinor to compete", "in the arena.", ) it.chatPlayer("Wow.") it.chatNpc("Few return, most get fried, hence the smell.") it.chatPlayer("Hmmm.. I did notice.") // End of dialogue }
39
null
143
34
e5400cc71bfa087164153d468979c5a3abc24841
2,522
game
Apache License 2.0
ndarray/ndarray-core/src/jvmMain/kotlin/io/kinference/ndarray/extensions/sum/SumExtension.kt
JetBrains-Research
244,400,016
false
{"Kotlin": 2301067, "Python": 4774, "JavaScript": 2402, "Dockerfile": 683}
package io.kinference.ndarray.extensions.sum import io.kinference.ndarray.arrays.* import io.kinference.primitives.types.DataType suspend fun List<NumberNDArrayCore>.sum(): NumberNDArrayCore { if (isEmpty()) error("Array for sum operation must have at least one element") if (size == 1) return single() val inputType = this.first().type require(this.all { it.type == inputType }) { "Input tensors must have the same data type" } return when (inputType) { DataType.DOUBLE -> (this as List<DoubleNDArray>).sum() DataType.FLOAT -> (this as List<FloatNDArray>).sum() else -> error("Unsupported data type in sum operation, tensors must have Float or Double data type, current is $inputType") } } suspend fun Array<out NumberNDArrayCore>.sum() = this.toList().sum() suspend fun sumOf(vararg inputs: NumberNDArrayCore) = inputs.sum()
7
Kotlin
7
154
92b4073ca46d410934f3b03eae61e05412467aec
881
kinference
Apache License 2.0
pageable2sources_ignite_cacheable/customer-nonpageable/src/main/kotlin/br/com/vagai/customer/mapper/ContactMapper.kt
viniciustoni
251,750,270
false
null
package br.com.vagai.customer.mapper import br.com.vagai.customer.dto.ContactDto import br.com.vagai.customer.entity.Contact import org.springframework.stereotype.Component @Component class ContactMapper(val clientMapper: ClientMapper, val countryMapper: CountryMapper) { fun contactToContactDto(contact: Contact): ContactDto = ContactDto( contact.id, contact.type, contact.contactValue, contact.phoneNumber, contact.extension, contact.country?.let { countryMapper.countryToCountryDto(it) }, clientMapper.clientToClientDto(contact.client)) fun contactDtoToContact(contactDto: ContactDto): Contact = Contact( contactDto.id, contactDto.type, contactDto.contactValue, contactDto.phoneNumber, contactDto.extension, contactDto.countryDto?.let { countryMapper.countryDtoToCountry(it) }, clientMapper.clientDtoToClient(contactDto.clientDto)) }
0
Kotlin
0
0
8dcd2b54b4bd91bef9357468f15c1cba7affdebb
1,036
kotlin-samples
MIT License
ViewPager22/app/src/main/java/com/app/mytaxi/di/module/ApplicationModule.kt
ajaypro
225,294,116
false
{"Java": 469931, "Kotlin": 294438}
package com.app.mytaxi.di.module import android.app.Application import android.content.Context import com.app.mytaxi.BuildConfig import com.app.mytaxi.MyTaxiApplication import com.app.mytaxi.data.NetworkService import com.app.mytaxi.data.Networking import com.app.mytaxi.di.ApplicationContext import com.app.mytaxi.utils.network.NetworkHelper import com.app.mytaxi.utils.rx.RxSchedulerProvider import com.app.mytaxi.utils.rx.SchedulerProvider import dagger.Module import dagger.Provides import io.reactivex.disposables.CompositeDisposable import javax.inject.Singleton /** * Created by <NAME> on 25-11-2019, 14:18 */ @Module class ApplicationModule(private val application: MyTaxiApplication) { @Provides fun provideCompositeDisposable(): CompositeDisposable = CompositeDisposable() @Singleton @Provides fun providesApplication(): Application = application @Singleton @Provides @ApplicationContext fun providesContext(): Context = application @Singleton @Provides fun providesNetworkService(): NetworkService = Networking.create( BuildConfig.BASE_URL, application.cacheDir, 10 * 10 * 1024 // 10mb ) @Singleton @Provides fun provideNetworkHelper(): NetworkHelper = NetworkHelper(application) /*@Provides fun providesGeoLocation(): GeoLocation = GeoLocation(application)*/ @Provides fun provideSchedulerProvider(): SchedulerProvider = RxSchedulerProvider() }
1
null
1
1
768b70f957cfd6198ad3594c7c50f741542ca674
1,500
ViewPager2
Apache License 2.0
ANT-Android-App/data/src/main/java/com/fredprojects/ant/data/repository/ArticleRepository.kt
FredNekrasov
857,490,850
false
{"Kotlin": 44158, "C#": 33647, "Java": 31851}
package com.fredprojects.ant.data.repository import com.fredprojects.ant.data.local.ArticleDao import com.fredprojects.ant.data.mappers.toEntity import com.fredprojects.ant.data.mappers.toModel import com.fredprojects.ant.data.remote.dto.ArticleDto import com.fredprojects.ant.domain.models.Article import com.fredprojects.ant.domain.repository.IArticleRepository import com.fredprojects.ant.domain.utils.ActionStatus import com.fredprojects.ant.domain.utils.ActionStatus.* import com.fredprojects.ant.domain.utils.ConnectionStatus.* import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.* import io.ktor.client.request.get import io.ktor.serialization.JsonConvertException import kotlinx.coroutines.flow.* /** * This class implements IArticleRepository interface * @param dao is an ArticleDao class. It is used to get data from the database and add data to the database * @param client is a HttpClient. It is used to get data from the server * @see IArticleRepository */ class ArticleRepository( private val dao: ArticleDao, private val client: HttpClient ) : IArticleRepository { /** * Get list of articles from the database and return it as a flow if there is no internet connection. * If there is internet connection, get list of articles from the server and return it as a flow * @see IArticleRepository.getList * @return a flow of ActionStatus */ override fun getList() : Flow<ActionStatus<Article>> = flow { val articleList = dao.getAllArticles().map { it.toModel() } emit(Loading(articleList)) val articleDtoList = client.get("/api/v1/chapter").body<List<ArticleDto>?>() if(!articleDtoList.isNullOrEmpty()) { articleDtoList.forEach { dao.deleteArticle(it.id) dao.upsertArticle(it.toEntity()) } emit(Success(articleDtoList.map { it.toModel() })) } else emit(Error(articleList, NO_DATA)) }.catch { ex -> val articleList = dao.getAllArticles().map { it.toModel() } when(ex) { is ServerResponseException -> emit(Error(articleList, CONNECTION_ERROR)) is RedirectResponseException -> emit(Error(articleList, CONNECTION_ERROR)) is HttpRequestTimeoutException -> emit(Error(articleList, CONNECTION_ERROR)) is ClientRequestException -> emit(Error(articleList, NO_INTERNET)) is JsonConvertException -> emit(Error(articleList, SERIALIZATION_ERROR)) else -> emit(Error(articleList, UNKNOWN)) } } }
0
Kotlin
0
1
462a4fb94240f20efda8527470567fc1e97c8a61
2,594
ANT
MIT License
app/src/main/java/com/example/appwritedemoapplication/ui/Functions/FunctionsViewModel.kt
appwrite
357,670,112
false
null
package com.example.appwritedemoapplication.ui.Functions import android.text.Editable import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.appwritedemoapplication.utils.Client import com.example.appwritedemoapplication.utils.Event import io.appwrite.exceptions.AppwriteException import io.appwrite.services.Functions import kotlinx.coroutines.launch import org.json.JSONObject class FunctionsViewModel : ViewModel() { private val _error = MutableLiveData<Event<AppwriteException>>().apply { value = null } val error: LiveData<Event<AppwriteException>> = _error private val _response = MutableLiveData<Event<String>>().apply { value = null } val response: LiveData<Event<String>> = _response private val functionsService by lazy { Functions(Client.client) } fun createExecution(id: Editable?) { viewModelScope.launch { try { val response = functionsService.createExecution(id.toString()) var json = response.body?.string() ?: "" json = JSONObject(json).toString(4) _response.postValue(Event(json)) } catch (e: AppwriteException) { _error.postValue(Event(e)) } } } fun listExecutions(id: Editable?) { viewModelScope.launch { try { val response = functionsService.listExecutions(id.toString()) var json = response.body?.string() ?: "" json = JSONObject(json).toString(4) _response.postValue(Event(json)) } catch (e: AppwriteException) { _error.postValue(Event(e)) } } } fun getExecution(functionId: Editable? , executionId: Editable?) { viewModelScope.launch { try { val response = functionsService.getExecution(functionId.toString(), executionId.toString()) var json = response.body?.string() ?: "" json = JSONObject(json).toString(4) _response.postValue(Event(json)) } catch (e: AppwriteException) { _error.postValue(Event(e)) } } } }
0
null
9
9
a9e6ac8d72bbe49d6ef21bb4d6fced8b79fccb31
2,340
demo-getstarted-with-android
MIT License
src/nativeGen/kotlin/godot/EditorFileDialog.kt
piiertho
237,614,467
true
{"Kotlin": 5300589}
// DO NOT EDIT, THIS FILE IS GENERATED FROM api.json package godot import gdnative.godot_method_bind import godot.core.Godot import godot.core.PoolStringArray import godot.core.Variant import godot.core.VariantArray import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.reflect.KCallable import kotlinx.cinterop.CFunction import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.CPointer import kotlinx.cinterop.cstr import kotlinx.cinterop.invoke import kotlinx.cinterop.memScoped import kotlinx.cinterop.reinterpret open class EditorFileDialog( _handle: COpaquePointer ) : ConfirmationDialog(_handle) { var access: Access get() { return getAccess() } set(value) { setAccess(value.value) } var currentDir: String get() { return getCurrentDir() } set(value) { setCurrentDir(value) } var currentFile: String get() { return getCurrentFile() } set(value) { setCurrentFile(value) } var currentPath: String get() { return getCurrentPath() } set(value) { setCurrentPath(value) } var disableOverwriteWarning: Boolean get() { return isOverwriteWarningDisabled() } set(value) { setDisableOverwriteWarning(value) } var displayMode: DisplayMode get() { return getDisplayMode() } set(value) { setDisplayMode(value.value) } var mode: Mode get() { return getMode() } set(value) { setMode(value.value) } var showHiddenFiles: Boolean get() { return isShowingHiddenFiles() } set(value) { setShowHiddenFiles(value) } /** * EditorFileDialog::dir_selected signal */ val signalDirSelected: Signal1<String> = Signal1("dir_selected") /** * EditorFileDialog::file_selected signal */ val signalFileSelected: Signal1<String> = Signal1("file_selected") /** * EditorFileDialog::files_selected signal */ val signalFilesSelected: Signal1<PoolStringArray> = Signal1("files_selected") fun addFilter(filter: String) { val _arg = Variant.new(filter) __method_bind.addFilter.call(this._handle, listOf(_arg)) } fun clearFilters() { __method_bind.clearFilters.call(this._handle) } fun getAccess(): Access { val _ret = __method_bind.getAccess.call(this._handle) return EditorFileDialog.Access.from(_ret.asInt()) } fun getCurrentDir(): String { val _ret = __method_bind.getCurrentDir.call(this._handle) return _ret.asString() } fun getCurrentFile(): String { val _ret = __method_bind.getCurrentFile.call(this._handle) return _ret.asString() } fun getCurrentPath(): String { val _ret = __method_bind.getCurrentPath.call(this._handle) return _ret.asString() } fun getDisplayMode(): DisplayMode { val _ret = __method_bind.getDisplayMode.call(this._handle) return EditorFileDialog.DisplayMode.from(_ret.asInt()) } fun getMode(): Mode { val _ret = __method_bind.getMode.call(this._handle) return EditorFileDialog.Mode.from(_ret.asInt()) } fun getVbox(): VBoxContainer { val _ret = __method_bind.getVbox.call(this._handle) return _ret.asObject(::VBoxContainer)!! } fun invalidate() { __method_bind.invalidate.call(this._handle) } fun isOverwriteWarningDisabled(): Boolean { val _ret = __method_bind.isOverwriteWarningDisabled.call(this._handle) return _ret.asBoolean() } fun isShowingHiddenFiles(): Boolean { val _ret = __method_bind.isShowingHiddenFiles.call(this._handle) return _ret.asBoolean() } fun setAccess(access: Int) { val _arg = Variant.new(access) __method_bind.setAccess.call(this._handle, listOf(_arg)) } fun setCurrentDir(dir: String) { val _arg = Variant.new(dir) __method_bind.setCurrentDir.call(this._handle, listOf(_arg)) } fun setCurrentFile(file: String) { val _arg = Variant.new(file) __method_bind.setCurrentFile.call(this._handle, listOf(_arg)) } fun setCurrentPath(path: String) { val _arg = Variant.new(path) __method_bind.setCurrentPath.call(this._handle, listOf(_arg)) } fun setDisableOverwriteWarning(disable: Boolean) { val _arg = Variant.new(disable) __method_bind.setDisableOverwriteWarning.call(this._handle, listOf(_arg)) } fun setDisplayMode(mode: Int) { val _arg = Variant.new(mode) __method_bind.setDisplayMode.call(this._handle, listOf(_arg)) } fun setMode(mode: Int) { val _arg = Variant.new(mode) __method_bind.setMode.call(this._handle, listOf(_arg)) } fun setShowHiddenFiles(show: Boolean) { val _arg = Variant.new(show) __method_bind.setShowHiddenFiles.call(this._handle, listOf(_arg)) } enum class DisplayMode( val value: Int ) { DISPLAY_THUMBNAILS(0), DISPLAY_LIST(1); companion object { fun from(value: Int): DisplayMode { for (enumValue in values()) { if (enumValue.value == value) { return enumValue } } throw AssertionError("""Unsupported enum value: $value""") } } } enum class Mode( val value: Int ) { MODE_OPEN_FILE(0), MODE_OPEN_FILES(1), MODE_OPEN_DIR(2), MODE_OPEN_ANY(3), MODE_SAVE_FILE(4); companion object { fun from(value: Int): Mode { for (enumValue in values()) { if (enumValue.value == value) { return enumValue } } throw AssertionError("""Unsupported enum value: $value""") } } } enum class Access( val value: Int ) { ACCESS_RESOURCES(0), ACCESS_USERDATA(1), ACCESS_FILESYSTEM(2); companion object { fun from(value: Int): Access { for (enumValue in values()) { if (enumValue.value == value) { return enumValue } } throw AssertionError("""Unsupported enum value: $value""") } } } companion object { val ACCESS_FILESYSTEM: Int = 2 val ACCESS_RESOURCES: Int = 0 val ACCESS_USERDATA: Int = 1 val DISPLAY_LIST: Int = 1 val DISPLAY_THUMBNAILS: Int = 0 val MODE_OPEN_ANY: Int = 3 val MODE_OPEN_DIR: Int = 2 val MODE_OPEN_FILE: Int = 0 val MODE_OPEN_FILES: Int = 1 val MODE_SAVE_FILE: Int = 4 /** * Container for method_bind pointers for EditorFileDialog */ private object __method_bind { val addFilter: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "add_filter".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method add_filter" } } val clearFilters: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "clear_filters".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method clear_filters" } } val getAccess: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_access".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_access" } } val getCurrentDir: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_current_dir".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_current_dir" } } val getCurrentFile: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_current_file".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_current_file" } } val getCurrentPath: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_current_path".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_current_path" } } val getDisplayMode: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_display_mode".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_display_mode" } } val getMode: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_mode".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_mode" } } val getVbox: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "get_vbox".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_vbox" } } val invalidate: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "invalidate".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method invalidate" } } val isOverwriteWarningDisabled: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "is_overwrite_warning_disabled".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method is_overwrite_warning_disabled" } } val isShowingHiddenFiles: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "is_showing_hidden_files".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method is_showing_hidden_files" } } val setAccess: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_access".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_access" } } val setCurrentDir: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_current_dir".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_current_dir" } } val setCurrentFile: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_current_file".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_current_file" } } val setCurrentPath: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_current_path".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_current_path" } } val setDisableOverwriteWarning: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_disable_overwrite_warning".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_disable_overwrite_warning" } } val setDisplayMode: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_display_mode".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_display_mode" } } val setMode: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_mode".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_mode" } } val setShowHiddenFiles: CPointer<godot_method_bind> get() = memScoped { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("EditorFileDialog".cstr.ptr, "set_show_hidden_files".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_show_hidden_files" } }} } }
0
null
0
1
3a8c598040f9b47b2b8cf8f5432543f61d6f83e8
13,167
godot-kotlin
MIT License
jps-plugin/testData/incremental/withJava/other/classToPackageFacade/A.kt
JakeWharton
99,388,807
false
null
open class A { companion object { @JvmStatic fun f() {} @JvmStatic fun g() {} } fun h() {} }
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
138
kotlin
Apache License 2.0
libraries/timeline-view/src/main/java/com/trendyol/timelineview/TimelineItemViewState.kt
Trendyol
220,991,853
false
{"Kotlin": 321758}
package com.trendyol.timelineview import android.graphics.Color import android.view.View class TimelineItemViewState( private val timelineItem: TimelineItem, val dotSize: Float, val borderWidth: Float, val textSize: Float, val lineWidth: Float, val fontFamily: String, val maxLineCount: Int ) { fun getOutsideColor(): Int = Color.parseColor(timelineItem.outsideColor) fun getInsideColor(): Int = Color.parseColor(timelineItem.insideColor) fun getText(): String = timelineItem.text.replaceFirst(" ","\n") fun getTextColor(): Int = Color.parseColor(timelineItem.textColor) fun getStartLineColor(): Int = Color.parseColor(timelineItem.startLineColor ?: hexColorWhite) fun getEndLineColor(): Int = Color.parseColor(timelineItem.endLineColor ?: hexColorWhite) fun getStartLineVisibility(): Int = if (timelineItem.startLineColor != null) View.VISIBLE else View.GONE fun getEndLineVisibility(): Int = if (timelineItem.endLineColor != null) View.VISIBLE else View.GONE fun getOutsideDotSize(): Float = dotSize fun getInsideDotSize(): Float = dotSize - (borderWidth * 2) fun getShadowDotSize(): Float = dotSize + borderWidth fun getItemWidth(): Float = dotSize + borderWidth + lineWidth fun getItemMaxLineCount(): Int = maxLineCount companion object { private const val hexColorWhite = "#000000" } }
3
Kotlin
18
210
33add825e423a7e08a0ca4f1c8c0e6df940281f2
1,435
android-ui-components
Apache License 2.0
app/src/main/java/com/example/kphrase/PhrasesViewRecyclerViewAdapter.kt
ElPhilipp
188,347,379
false
null
package com.example.kphrase import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.BounceInterpolator import android.view.animation.ScaleAnimation import android.widget.* import androidx.cardview.widget.CardView import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.example.kphrase.Fragments.MainFragmentDirections import com.example.kphrase.Fragments.PhraseListFragmentDirections import com.example.kphrase.Tools.isInList import com.example.kphrase.Tools.posInList import kotlinx.android.synthetic.main.list_view.view.* class PhrasesViewRecyclerViewAdapter(val item: ArrayList<Categories>, val context: Context?) : RecyclerView.Adapter<PhrasesViewRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_view, parent, false), item, context) } override fun getItemCount(): Int { return item.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.item.text = item[position].ENG_NAME holder.subitem.text = item[position].ENG_KOR_NAME holder.button_favorite.isChecked = isInList(item[position]) } class ViewHolder(view: View, item: ArrayList<Categories>, context: Context?) : RecyclerView.ViewHolder(view) { var layout: RelativeLayout var text: TextView var button_favorite: ToggleButton val item = view.item!! val subitem = view.subitem init { layout = view.findViewById(R.id.card) text = view.findViewById(R.id.item) button_favorite = view.findViewById(R.id.button_favorite) val scaleAnimation = ScaleAnimation( 0.7f, 1.0f, 0.7f, 1.0f, Animation.RELATIVE_TO_SELF, 0.7f, Animation.RELATIVE_TO_SELF, 0.7f ) scaleAnimation.duration = 500 val bounceInterpolator = BounceInterpolator() scaleAnimation.interpolator = bounceInterpolator button_favorite.setOnCheckedChangeListener(object : View.OnClickListener, CompoundButton.OnCheckedChangeListener { override fun onCheckedChanged(p0: CompoundButton?, p1: Boolean) { if(!button_favorite.isPressed) { return } p0?.startAnimation(scaleAnimation) if (p1) Favorites.fav.add(item[adapterPosition]) else Favorites.fav.removeAt(posInList(item[adapterPosition])) } override fun onClick(p0: View?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }) text.setOnClickListener { //view.isEnabled = false val phrases = PhraseListFragmentDirections.actionPhraseListFragmentToTranslatorFragment(item[adapterPosition]) view.findNavController().navigate(phrases) } layout.setOnClickListener { //view.isEnabled = false val phrases = PhraseListFragmentDirections.actionPhraseListFragmentToTranslatorFragment(item[adapterPosition]) view.findNavController().navigate(phrases) } } } }
0
Kotlin
0
0
65b9027fe82579f997e18695f55dc2e3d07279b2
3,777
K-Phrase
MIT License
common/src/commonMain/kotlin/io/github/oxiadenine/chainpass/repository/ChainRepository.kt
oxiadenine
737,791,464
false
{"Kotlin": 216996}
package io.github.oxiadenine.chainpass.repository import io.github.oxiadenine.chainpass.ChainTable import io.github.oxiadenine.chainpass.Database import io.github.oxiadenine.chainpass.Storage import kotlinx.serialization.Serializable import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.selectAll @Serializable data class ChainEntity( val id: String, val name: String, val key: String, val salt: String, ) class ChainRepository(private val database: Database, val storage: Storage) { suspend fun create(chainEntity: ChainEntity) = database.transaction { ChainTable.insert { statement -> statement[id] = chainEntity.id statement[name] = chainEntity.name statement[key] = chainEntity.key statement[salt] = chainEntity.salt } Unit } suspend fun getAll() = database.transaction { ChainTable.selectAll().map { record -> ChainEntity( record[ChainTable.id], record[ChainTable.name], record[ChainTable.key], record[ChainTable.salt] ) } } suspend fun getOne(id: String) = runCatching { database.transaction { val record = ChainTable.select { ChainTable.id eq id }.first() ChainEntity( record[ChainTable.id], record[ChainTable.name], record[ChainTable.key], record[ChainTable.salt] ) } } suspend fun delete(id: String) = database.transaction { ChainTable.deleteWhere { ChainTable.id eq id } Unit } }
0
Kotlin
0
0
d2901846ee427d831ca800527bed0ed909b65b8b
1,816
chain-pass
Apache License 2.0
src/main/kotlin/theme/Typography.kt
oss-review-toolkit
436,895,138
false
{"Kotlin": 278352}
@file:Suppress("MagicNumber") package org.ossreviewtoolkit.workbench.theme import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.Column import androidx.compose.material.Text import androidx.compose.material.Typography import androidx.compose.runtime.Composable import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import org.ossreviewtoolkit.workbench.composables.Preview val Typography = Typography( h1 = TextStyle( fontWeight = FontWeight.Light, fontSize = 48.sp, letterSpacing = (-1.5).sp ), h2 = TextStyle( fontWeight = FontWeight.Light, fontSize = 32.sp, letterSpacing = (-0.5).sp ), h3 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 24.sp, letterSpacing = 0.sp ), h4 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 20.sp, letterSpacing = 0.25.sp ), h5 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.sp ), h6 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 0.15.sp ), subtitle1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 13.sp, letterSpacing = 0.15.sp ), subtitle2 = TextStyle( fontWeight = FontWeight.Medium, fontSize = 12.sp, letterSpacing = 0.1.sp ), body1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 13.sp, letterSpacing = 0.5.sp ), body2 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp, letterSpacing = 0.25.sp ), button = TextStyle( fontWeight = FontWeight.Medium, fontSize = 12.sp, letterSpacing = 1.25.sp ), caption = TextStyle( fontWeight = FontWeight.Normal, fontSize = 11.sp, letterSpacing = 0.4.sp ), overline = TextStyle( fontWeight = FontWeight.Normal, fontSize = 10.sp, letterSpacing = 1.5.sp ) ) @Composable @Preview private fun TypographyPreview() { Preview { Column { Text("Header 1", style = Typography.h1) Text("Header 2", style = Typography.h2) Text("Header 3", style = Typography.h3) Text("Header 4", style = Typography.h4) Text("Header 5", style = Typography.h5) Text("Header 6", style = Typography.h6) Text("Subtitle 1", style = Typography.subtitle1) Text("Subtitle 2", style = Typography.subtitle2) Text("Body 1", style = Typography.body1) Text("Body 2", style = Typography.body2) Text("Button", style = Typography.button) Text("Caption", style = Typography.caption) Text("Overline", style = Typography.overline) } } }
6
Kotlin
4
26
38dd099eb5c6e7656a8bbe2614842bae048a78f1
3,079
ort-workbench
Apache License 2.0
IEAATParser/src/main/kotlin/nl/utwente/fmt/ieaatparser/eom/PVAIExporter.kt
SwiftPengu
75,495,277
false
null
package nl.utwente.fmt.ieaatparser.eom import nl.utwente.fmt.ieaatparser.io.IEaatParts import nl.utwente.fmt.ieaatparser.prm.exportPVA import org.eclipse.emf.common.util.URI import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl import org.eclipse.emf.ecore.util.EcoreUtil import pva.PVAContainer import pvai.PVAIContainer import java.io.File fun exportPVAI(parts: IEaatParts, exportedPRM: PVAContainer?, outFile: File, pvaOutFile: File? = null) { println("Generating pvai") val startTime = System.currentTimeMillis() val pva = exportedPRM ?: exportPVA(parts,pvaOutFile) println("Obtaining the PVA model took ${System.currentTimeMillis() - startTime}ms") outFile.delete() val pvai = EOMParser(pva,parts).parse() //Transform to analysis metamodel exportPVAItoXMI(pvai, outFile, pva) println("Transforming the EOM took ${System.currentTimeMillis() - startTime}ms") } /** * Exports the given model to the given file in the XMI format */ fun exportPVAItoXMI(model : PVAIContainer, location: File, pva : PVAContainer) { println("Attempting PVAI serialization") val outURI = URI.createFileURI(location.absolutePath) ResourceSetImpl().createResource(outURI).apply { this.contents += model println("Starting exporting...") pva.eResource().unload() //unload the PVA before exporting, so proxy references are created location.outputStream().use { oStream -> this.save(oStream, mapOf<Any, Any>()) } println("Finished exporting") }.unload() } fun loadPVAIfromXMI(location: File): PVAIContainer { println("Starting reading .pvai file") val outURI = URI.createFileURI(location.absolutePath) val resourceSet = ResourceSetImpl() val resource = resourceSet.getResource(outURI,true) //Fixes unresolved proxies by resolving them (somehow has to be done manually) EcoreUtil.UnresolvedProxyCrossReferencer.find(resource).forEach { unresolvedProxy -> unresolvedProxy.value.single().set( EcoreUtil.resolve(unresolvedProxy.key,resourceSet) ) } val result = resource.contents.first() as PVAIContainer println("Finished reading .pvai file") return result }
0
Kotlin
0
0
253c1965cc7cdf3f9091e9e9fcd23c64c3ec03a7
2,233
ProbabilisticVulnerabilityAnalysis
MIT License
appreader/src/main/java/com/ul/ims/gmdl/reader/viewmodel/NfcScanViewModel.kt
prashantkspatil
284,531,234
true
{"Kotlin": 1392515, "Java": 421643}
/* * Copyright (C) 2019 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.ul.ims.gmdl.reader.viewmodel import androidx.lifecycle.ViewModel import com.ul.ims.gmdl.cbordata.deviceEngagement.DeviceEngagement class NfcScanViewModel : ViewModel() { fun validateNfcEngagement(deviceEngagementBytes: ByteArray?): DeviceEngagement { val builder = DeviceEngagement.Builder() deviceEngagementBytes?.let { builder.decode(it) } return builder.build() } }
0
null
0
0
a6c3a6077ef5e7774ff70929ae4f33968ce6f598
1,036
mdl-ref-apps
Apache License 2.0
src/test/java/kotlinx/reflect/lite/unusedTestData/callBy/defaultInSuperClass.kt
Kotlin
41,860,868
false
{"Kotlin": 516851, "Java": 75}
/* * Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package tests.callBy.defaultInSuperClass open class A { open fun foo(a: String, b: String = "b") = b + a } class B : A() { override fun foo(a: String, b: String) = a + b } fun box(): String { val f = B::foo assert("ab" == f.callBy(mapOf( f.parameters.first() to B(), f.parameters.single { it.name == "a" } to "a" ))) return "OK" }
3
Kotlin
13
156
32ffe53981eb559939b6c2f15661138661b31bc6
487
kotlinx.reflect.lite
Apache License 2.0
app/src/main/java/com/kaedenoki/moviecorner/data/general/Home.kt
Kaede-No-Ki
290,696,286
false
null
package com.kaedenoki.moviecorner.data.general data class Home( val list: List<ItemHome>? = mutableListOf() ) data class ItemHome( // banner, item, title val type: Int, val data: Any )
8
Kotlin
8
43
ea72dc71dfc43e41a6566428db69c139c474df6e
203
moviecorner-app
MIT License
src/main/kotlin/bvanseg/kotlincommons/grouping/collection/SizedList.kt
bvanseg
211,717,677
false
null
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package bvanseg.kotlincommons.grouping.collection import java.util.LinkedList /** * A very minimal class that limits the number of elements that can be added to it. * * @author bright_spark * @since 1.0.1 */ class SizedList<T>(private val maxSize: Int) : LinkedList<T>() { /** * Adds an element to the list. If the current size of the list exceeds the max size, the head element of the list * will be dropped. */ override fun add(element: T): Boolean { // TODO: It's possible the size value could have changed at this point to be over the max size, in which case // This would lead to the list no longer being limited. if (this.size == maxSize) { this.removeAt(0) } return super.add(element) } // TODO: addAll implementations can bypass the limit, therefore they need to be overridden and dealt with. }
0
Kotlin
0
1
f02d97922c743fffc0c520ed2be30ad6b95dd8a3
2,023
KotlinCommons
MIT License
src/main/kotlin/net/liyze/basin/core/scan/ServerCommand.kt
Liyze09
637,435,463
false
{"Kotlin": 102032, "JavaScript": 2722, "HTML": 1238}
/* * Copyright (c) 2023 Liyze09 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.liyze.basin.core.scan import net.liyze.basin.core.Command import net.liyze.basin.http.HttpServer import org.slf4j.Logger class ServerCommand : Command { override fun run(args: List<String?>, logger: Logger) { if (args.isNotEmpty()) HttpServer.stop() else HttpServer.start() } override fun getName(): String { return "http" } }
0
Kotlin
0
1
b67a8fc817a3f1f805cc973c071429af453e2d74
979
Basin
Apache License 2.0
libs/trezor/src/commonMain/kotlin/kosh/libs/trezor/cmds/expect.kt
niallkh
855,100,709
false
{"Kotlin": 1845307, "Swift": 768}
package kosh.libs.trezor.cmds import com.squareup.wire.Message internal inline fun <reified T : Message<*, *>> Message<*, *>.expect(): T = this as? T ?: unexpectedError<T>() internal inline fun <reified T : Message<*, *>> Message<*, *>.unexpectedError(): Nothing { error("Unexpected response: ${this::class.simpleName}, expected: ${T::class.simpleName}") } internal inline fun <reified T : Message<*, *>> Message<*, *>.expectOrNull(): T? = this as? T
0
Kotlin
0
3
2be90c7ce7775a76d44fac4cae3a6777d6e9c7f7
468
kosh
MIT License
PineLib/src/main/java/com/blueberrysolution/pinelib19/sqlite/mylib/model/SelectModel.kt
leaptochina
228,527,202
false
null
package com.blueberrysolution.pinelib19.sqlite.mylib.model import android.database.Cursor import com.blueberrysolution.pinelib19.activity.A import com.blueberrysolution.pinelib19.addone.convert.AnyToString import com.blueberrysolution.pinelib19.debug.G import com.blueberrysolution.pinelib19.reflection.ReflectHelper import com.blueberrysolution.pinelib19.sqlite.mylib.user_extend_models.BModel open class SelectModel<T: BModel>: BaseModel<T>(){ // SQL表达式 private var selectSql = "SELECT%DISTINCT% %FIELD% FROM " + "%TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%" protected var isSelectCount = false; protected var whereCondition: String? = ""; protected var fields: Array<String> = arrayOf(); protected var distinct: Boolean = false; protected var groupBy: String? = null; protected var having: String?= null; protected var orderBy: String? = null; protected var limit: Int = -1; protected var selectResult = ArrayList<T>(); fun where(key: String, flag: String, value1: Any, value2: Any? = null): M<T> { var condition = ""; parseWhereItem(key, flag, value1) return this as M<T>; } fun select(): ArrayList<T> { setupSelectTemplate(); return doSelect(selectSql); } fun setupSelectTemplate(){ selectSql = selectSqlTemplate; selectSql = selectSql.replace("%TABLE%", parseTable()); selectSql = selectSql.replace("%DISTINCT%", parseDistinct()); selectSql = selectSql.replace("%FIELD%", parseField()); selectSql = selectSql.replace("%JOIN%", parseJoin()); selectSql = selectSql.replace("%WHERE%", parseWhere()); selectSql = selectSql.replace("%GROUP%", parseGroup()); selectSql = selectSql.replace("%HAVING%", parseHaving()); selectSql = selectSql.replace("%ORDER%", parseOrder()); selectSql = selectSql.replace("%LIMIT%", parseLimit()); selectSql = selectSql.replace("%UNION%", parseUnion()); selectSql = selectSql.replace("%LOCK%", parseLock()); selectSql = selectSql.replace("%COMMENT%", parseComment()); selectSql = selectSql.replace("%FORCE%", parseForce()); } fun count(): Int{ isSelectCount = true; var result = select(); return (result[0] as BModel).result_count; } //获取目前表的所有列 列名 类型 fun getTableColumns(): ArrayList<String>{ setupSelectTemplate(); var arrayList = ArrayList<String>(); var r = A.db().rawQuery(selectSql, arrayOf()) r.columnNames.map { arrayList.add(it); } return arrayList; } fun doSelect(sql: String): ArrayList<T>{ G.d(selectSql); var r = A.db().rawQuery(selectSql, arrayOf()) selectResult = ArrayList<T>(); while (r.moveToNext()) { var result = HashMap<String, String?>(); var obj = createKClassInstance(); for (x in 0..(r.columnCount - 1)) { var key = r.getColumnName(x); var value = ""; var type = r.getType(x); var valueConverted: Any? = null; if (type == Cursor.FIELD_TYPE_NULL) { valueConverted = null; } else if (type == Cursor.FIELD_TYPE_BLOB) { valueConverted = r.getBlob(x); } else if (type == Cursor.FIELD_TYPE_FLOAT) { valueConverted = r.getFloat(x); } else if (type == Cursor.FIELD_TYPE_INTEGER) { valueConverted = r.getInt(x); } else if (type == Cursor.FIELD_TYPE_STRING) { valueConverted = r.getString(x); } result.put(key, AnyToString.toString(valueConverted)) ReflectHelper.setValue(kclass, obj as Any, key, valueConverted); } ReflectHelper.setValue(kclass, obj as Any, "oldValues", result); selectResult.add(obj); } return selectResult; } fun find(): T?{ limit = 1; var selectResult = select(); if (selectResult.count() >= 1) { return selectResult[0]; }else{ return null; } } fun find(id: Int): T?{ return where("id", id).find(); } fun parseDistinct(): String { return if (distinct) { " DISTINCT " } else {""}; } fun parseField(): String{ var fieldsStr = ""; if (fields.count() == 0) fieldsStr = "*"; else { fields.map{ key -> if (!fieldsStr.equals("")){ fieldsStr = fieldsStr + ","; } fieldsStr = fieldsStr + key + " AS " + key; } } if (isSelectCount){ fieldsStr = "COUNT(" + fieldsStr + ") AS result_count" } return fieldsStr; } fun parseJoin() : String{ return ""; } fun parseWhere(): String{ // // if (!soft_delete.equals("")) { // parseWhereItem(soft_delete, "is", null) // } return whereCondition!!; } fun parseWhereItem(field: String, rule: String, value: Any?){ var ruleChecked = rule.toLowerCase(); var valueChecked: String = anyToString(value) var r = "`" + field + "`" + ruleChecked + valueChecked; if (whereCondition.equals("")) { whereCondition = " WHERE (" + r + ")" } else{ whereCondition = whereCondition + " AND (" + r + ")" } } fun parseGroup(): String { return ""; } fun parseHaving(): String { return ""; } fun parseOrder(): String { return ""; } fun parseLimit(): String { if (limit < 0){ return "" } return " LIMIT " + limit.toString(); } fun parseUnion(): String { return ""; } fun parseLock(): String { return ""; } fun parseComment(): String { return ""; } fun parseForce(): String { return ""; } fun where(key: String, value: Any): M<T> { return where(key, "=", value); } companion object { var selectSqlTemplate = "SELECT%DISTINCT% %FIELD% FROM " + "%TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%" } }
0
Kotlin
0
0
b7ccb0b4259c3e17f71a677bdbc6388bb92d9841
6,549
celo_test
Apache License 2.0
src/test/kotlin/org/openrewrite/java/testing/cleanup/TestsShouldIncludeAssertionsTest.kt
openrewrite
295,620,416
false
null
/* * Copyright 2021 the original author or authors. * <p> * 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 * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openrewrite.java.testing.cleanup import org.junit.jupiter.api.Test import org.openrewrite.Parser import org.openrewrite.Recipe import org.openrewrite.java.JavaParser import org.openrewrite.java.JavaRecipeTest class TestsShouldIncludeAssertionsTest : JavaRecipeTest { override val parser: JavaParser = JavaParser.fromJavaVersion() .classpath("junit", "mockito-all", "hamcrest", "assertj-core") .dependsOn( listOf( Parser.Input.fromString( """ package org.learning.math; public interface MyMathService { Integer addIntegers(String i1, String i2); } """ ) ) ) .build() override val recipe: Recipe get() = TestsShouldIncludeAssertions() @Test fun noAssertions() = assertChanged( before = """ import org.junit.jupiter.api.Test; public class AaTest { @Test public void methodTest() { Integer it = Integer.valueOf("2"); System.out.println(it); } } """, after = """ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; public class AaTest { @Test public void methodTest() { assertDoesNotThrow(() -> { Integer it = Integer.valueOf("2"); System.out.println(it); }); } } """ ) @Test fun hasAssertDoesNotThrowAssertion() = assertUnchanged( before = """ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; public class AaTest { @Test public void methodTest() { assertDoesNotThrow(() -> { Integer it = Integer.valueOf("2"); System.out.println(it); }); } } """ ) @Test fun assertJAssertion() = assertUnchanged( before = """ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class A { @Test public void test() { assertThat(notification()).isEqualTo(1); } private Integer notification() { return 1; } } """ ) @Test fun hamcrestAssertion() = assertUnchanged( before = """ import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class ATest { @Test public void methodTest() { Integer i1 = Integer.valueOf("1"); Integer i2 = Integer.valueOf("1"); assertThat(i1, equalTo(i2)); } } """ ) @Test fun hasAssertion() = assertUnchanged( before = """ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class AaTest { @Test public void methodTest() { assertEquals(1,1); } } """ ) @Test fun hasMockitoVerify() = assertUnchanged( before = """ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.learning.math.MyMathService; import static org.mockito.Mockito.when; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; class AaTest { @Mock MyMathService myMathService; @Test public void verifyTest() { when(myMathService.addIntegers("1", "2")).thenReturn(3); Integer i = myMathService.addIntegers("1", "2"); verify(myMathService, times(1)); } } """ ) @Test fun hasMockitoDoesNotValidate() = assertChanged( before = """ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.learning.math.MyMathService; import static org.mockito.Mockito.when; import org.learning.math.Stuff; class AaTest { @Mock MyMathService myMathService; @Test public void methodTest() { when(myMathService.addIntegers("1", "2")).thenReturn(3); myMathService.addIntegers("1", "2"); } } """, after = """ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.learning.math.MyMathService; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.Mockito.when; import org.learning.math.Stuff; class AaTest { @Mock MyMathService myMathService; @Test public void methodTest() { assertDoesNotThrow(() -> { when(myMathService.addIntegers("1", "2")).thenReturn(3); myMathService.addIntegers("1", "2"); }); } } """ ) }
4
null
11
22
90e2f6c34622b0bc46981b8250dc0556e1cea74c
6,645
rewrite-testing-frameworks
Apache License 2.0
src/main/kotlin/no/nav/helse/risk/RiverEnvironment.kt
navikt
252,136,318
false
null
package no.nav.helse.risk import org.apache.kafka.clients.CommonClientConfigs import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.config.SaslConfigs import org.apache.kafka.common.config.SslConfigs import org.apache.kafka.common.serialization.StringDeserializer import org.apache.kafka.common.serialization.StringSerializer import org.slf4j.LoggerFactory import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* data class ServiceUser( val username: String, val password: String ) { override fun toString() = "ServiceUser:$username" } private val log = LoggerFactory.getLogger(RiverEnvironment::class.java) private val isKafkaCloud:Boolean = systemEnvOrDefault("KAFKA_CLOUD_RIVER", "false") == "true" fun riskRiverTopic(): String = if (isKafkaCloud) "risk.helse-risk-river" else "helse-risk-river-v1" internal class RiverEnvironment( private val kafkaClientId: String ) { val vaultBase = "/var/run/secrets/nais.io/kafkauser" val vaultBasePath: Path = Paths.get(vaultBase) private fun readServiceUserCredentials() = ServiceUser( username = Files.readString(vaultBasePath.resolve("username")), password = Files.readString(vaultBasePath.resolve("password")) ) fun createKafkaEnvironment() : KafkaRiverEnvironment = if (isKafkaCloud) { KafkaRiverEnvironment( kafkaProducer = KafkaProducer(kafkaProducerConfig()), kafkaConsumer = KafkaConsumer(kafkaConsumerConfig()) ) } else { readServiceUserCredentials().let { kafkaUser -> return KafkaRiverEnvironment( kafkaProducer = KafkaProducer(kafkaProducerConfig(kafkaUser)), kafkaConsumer = KafkaConsumer(kafkaConsumerConfig(kafkaUser)) ) } } private fun kafkaProducerConfig(serviceUser: ServiceUser? = null, brokers: String? = null) = Properties().apply { if (isKafkaCloud) { log.info("RIVER-PRODUCER: Using Kafka Cloud") putAll(commonCloudKafkaConfig()) } else { log.info("RIVER-PRODUCER: Using Kafka OnPrem") requireNotNull(serviceUser) putAll(commonOnPremKafkaConfig(serviceUser, brokers)) } put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer::class.java) put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonObjectSerializer::class.java) put(ProducerConfig.ACKS_CONFIG, "all") put(ProducerConfig.CLIENT_ID_CONFIG, "$kafkaClientId-producer") } private fun kafkaConsumerConfig(serviceUser: ServiceUser? = null, brokers: String? = null) = Properties().apply { if (isKafkaCloud) { log.info("RIVER-CONSUMER: Using Kafka Cloud") putAll(commonCloudKafkaConfig()) } else { log.info("RIVER-CONSUMER: Using Kafka OnPrem") requireNotNull(serviceUser) putAll(commonOnPremKafkaConfig(serviceUser, brokers)) } put(ConsumerConfig.GROUP_ID_CONFIG, "$kafkaClientId-consumer") put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer::class.java) put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonObjectDeserializer::class.java) put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1000") put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest") //put("default.deserialization.exception.handler", LogAndContinueExceptionHandler::class.java) } private fun commonOnPremKafkaConfig(serviceUser: ServiceUser, brokers: String?) = Properties().apply { put("application.id", kafkaClientId) put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, systemEnvOrDefault("KAFKA_SECURITY_PROTOCOL_CONFIG", "SASL_SSL")) put(SaslConfigs.SASL_MECHANISM, "PLAIN") put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, brokers ?: systemEnv("KAFKA_BOOTSTRAP_SERVERS")) put(SaslConfigs.SASL_JAAS_CONFIG, "org.apache.kafka.common.security.plain.PlainLoginModule required " + "username=\"${serviceUser.username}\" password=\"${serviceUser.password}\";") } private fun commonCloudKafkaConfig() = Properties().apply { put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, systemEnv("KAFKA_BROKERS")) put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL") put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, "") put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "jks") put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12") put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, systemEnv("KAFKA_TRUSTSTORE_PATH")) put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, systemEnv("KAFKA_CREDSTORE_PASSWORD")) put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, systemEnv("KAFKA_KEYSTORE_PATH")) put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, systemEnv("KAFKA_CREDSTORE_PASSWORD")) } } private fun systemEnvOrDefault(name: String, default: String) = System.getenv(name) ?: default private fun systemEnv(name: String) = System.getenv(name) ?: error("Mangler env var '$name'")
0
Kotlin
0
0
f012686021129568d6826c6d838e9666e560b5b2
5,369
helse-riskvurderer-basis
MIT License
clvr-back/tic-tac-toe/src/main/kotlin/com/clvr/ttt/common/Dataclasses.kt
spbu-math-cs
698,591,633
false
{"Kotlin": 94320, "TypeScript": 49419, "JavaScript": 8395, "Python": 8353, "CSS": 738}
package com.clvr.ttt.common import com.clvr.platform.api.Template import com.clvr.platform.api.TemplateHeader import com.clvr.platform.api.TemplateId import kotlinx.serialization.Serializable @Serializable data class QuizQuestion( val topic: String, val statement: String, val answer: String, val hints: List<String> ) @Serializable data class TicTacToeTemplate( override val id: TemplateId, val questions: Array<Array<QuizQuestion>>, val gridSide: Int, val templateTitle: String?, val templateComment: String?, val templateAuthor: String? ) : Template { override val header: TemplateHeader get() = TemplateHeader(templateTitle ?: "", id.id, "") } @Serializable data class QuizCellInfo( val row: Int, val column: Int, val topic: String, val question: String, val hints: List<String>, val answer: String ) @Serializable data class QuizCompleteInfo( val id: String, val name: String, val comment: String, val board: List<QuizCellInfo> )
16
Kotlin
0
0
d5b1b910047bf60d22f628c20ebda1d329d743f5
1,072
ig-platform
Apache License 2.0
testdata/custom-prop/example-custom-01.kt
kamildoleglo
360,485,696
true
{"Kotlin": 94830}
// Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. // This file was automatically generated from custom-prop.in.md by Knit tool. Do not edit. package com.example.exampleCustom01 import java.util.* fun result() = listOf("Hello", "World")
0
Kotlin
0
0
f0ff1dcec40acc37a3e6315136297b9e01d12a2a
291
kotlinx-knit
Apache License 2.0
Mobile/SimplexLudum/composeApp/src/androidMain/kotlin/palbp/laboratory/simplexludum/previews/MyCollectionScreenPreview.kt
palbp
463,200,783
false
{"Kotlin": 797660, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Swift": 594, "Makefile": 383}
package palbp.laboratory.simplexludum.previews import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import palbp.laboratory.simplexludum.ui.common.theme.SimplexLudumTheme import palbp.laboratory.simplexludum.ui.mycollection.MyCollectionScreen @Preview(showBackground = true, showSystemUi = true, name = "Home Tab") @Composable fun MyCollectionScreenPreview() { SimplexLudumTheme { MyCollectionScreen().Content() } }
1
Kotlin
0
4
c19e8a32939945f2dbe50c79ad192cfb22ba7faf
474
laboratory
MIT License
src/main/kotlin/no/nav/paw/arbeidssokerregisteret/eksternt/api/config/Config.kt
navikt
706,209,067
false
{"Kotlin": 19472, "Dockerfile": 601}
package no.nav.paw.arbeidssokerregisteret.eksternt.api.config data class Config( val authProviders: AuthProviders ) data class AuthProviders( val maskinporten: AuthProvider ) data class AuthProvider( val name: String, val discoveryUrl: String, val tokenEndpointUrl: String, val clientId: String, val claims: List<String> ) data class ServiceClientConfig( val url: String, val scope: String )
1
Kotlin
0
0
82584516cf226bb6b62dbeb207fa15ea4a0138c6
432
paw-arbeidssokerregisteret-eksternt-api
MIT License
src/main/kotlin/com/sam/structure/bridge/material/Paper.kt
SymphonyZhang
566,757,181
false
null
package com.sam.structure.bridge.material class Paper:Material { override fun draw() { print("用纸箱") } }
0
Kotlin
0
0
b3d54708118e0d3741bcf93be84df0a25723963b
120
Design_Pattern
Apache License 2.0
user/service/src/main/kotlin/io/nanfeng/user/biz/domain/client/entity/OAuth2ClientEntity.kt
wine-area
642,665,898
false
null
package io.nanfeng.user.biz.domain.client.entity import io.hypersistence.utils.hibernate.type.json.JsonType import io.nanfeng.common.data.jpa.domain.BaseEntity import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.Table import org.hibernate.annotations.Type import java.io.Serializable import java.time.Instant @Entity @Table(name = "oauth2_client") class OAuth2ClientEntity : BaseEntity(), Serializable { @Column(name = "client_id", unique = true, updatable = false) lateinit var clientId: String lateinit var clientIdIssuedAt: Instant lateinit var clientSecret: String lateinit var clientSecretExpiresAt: Instant lateinit var clientName: String @Type(JsonType::class) @Column(columnDefinition = "json") var clientAuthenticationMethods: Set<String> = emptySet() @Type(JsonType::class) @Column(columnDefinition = "json") var authorizationGrantTypes: Set<String> = emptySet() @Type(JsonType::class) @Column(columnDefinition = "json") var redirectUris: Set<String> = emptySet() @Type(JsonType::class) @Column(columnDefinition = "json") var scopes: Set<String> = emptySet() @Type(JsonType::class) @Column(columnDefinition = "json") lateinit var clientSettings: OAuth2ClientSettingsEntity @Type(JsonType::class) @Column(columnDefinition = "json") lateinit var tokenSettings: OAuth2TokenSettingsEntity companion object { private const val serialVersionUID = 8481969837769002598L } }
0
Kotlin
0
0
be12804eb55a4f625724f5069b7b4f6945d1e4ae
1,549
sain
MIT License
src/main/kotlin/com/kk/routes/PlayerRoutes.kt
Aptivist
595,759,352
false
null
package com.kk.routes import com.kk.controllers.PlayerController import com.kk.controllers.events.GameEventPlayer import com.kk.controllers.events.mapper.toEvent import com.kk.data.models.AddPlayerRequest import com.kk.data.models.PlayerUser import com.kk.data.models.RoomConnectionStatus import com.kk.data.models.events.PlayerEvent import com.kk.data.models.toBaseResult import io.ktor.server.routing.* import io.ktor.server.websocket.* import io.ktor.websocket.* import org.koin.ktor.ext.inject import java.util.* import kotlin.random.Random fun Route.playerRouting(){ val playerController by inject<PlayerController>() webSocket("/player") { val (name,code) = receiveDeserialized<AddPlayerRequest>() val player = PlayerUser(id = generateRandomCode(), name =name, points = 0, session = this, code = code) playerController.tryJoinRoom(player) try { while (true){ val event = receiveDeserialized<PlayerEvent>().toEvent(player) if(event is GameEventPlayer.OnRetryJoinRoom){ player.code = event.code } playerController.onEventPlayer(event) } } catch (e: Exception){ playerController.removeFromGameRoom(player) player.session.close() } } } private fun generateRandomCode(): String { val charPool : List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9') return (1..8) .map { _ -> Random.nextInt(0, charPool.size) } .map(charPool::get) .joinToString("") .uppercase(Locale.getDefault()) }
0
Kotlin
0
1
03748ab7ca5ba366c66458df2e15c1a7c81add73
1,617
KK_backend
MIT License
src/test/Crc32Tests.kt
RJPlog
770,314,216
false
{"Kotlin": 2220}
import org.junit.Test import org.junit.Assert.assertEquals import java.util.zip.CRC32 class Crc32Tests { @Test fun testEmptyString() { val crc = crc32("") println("testEmptyString: expected: 0L, was: $crc") assertEquals(0L, crc) } @Test fun testSingleCharacter() { val crc = crc32("A") assertEquals(3554254475L, crc) } @Test fun testMultipleCharacters() { val crc = crc32("Hello, World!") assertEquals(3964322768L, crc) } }
9
Kotlin
0
0
644feda6ed09d9487649101eae49510a70b29df1
521
test_github_actions
MIT License
domain/impl/src/main/kotlin/dev/yacsa/domain/impl/usecase/update/CheckUpdateUseCaseImpl.kt
andrew-malitchuk
589,720,124
false
null
package dev.yacsa.domain.impl.usecase.update import arrow.core.Either import dev.yacsa.domain.error.DataError import dev.yacsa.domain.error.DomainError import dev.yacsa.domain.impl.mapper.update.CheckUpdateDomainRepoMapper import dev.yacsa.domain.model.update.CheckUpdateDomainModel import dev.yacsa.domain.usecase.update.CheckUpdateUseCase import dev.yacsa.repository.repository.CheckUpdateRepository import javax.inject.Inject class CheckUpdateUseCaseImpl @Inject constructor( private val checkUpdateRepository: CheckUpdateRepository, private val checkUpdateDomainRepoMapper: CheckUpdateDomainRepoMapper, ) : CheckUpdateUseCase { override suspend fun invoke(): Either<DomainError, CheckUpdateDomainModel> { return try { val result = checkUpdateRepository.checkUpdate("1") result.fold( { Either.Left(DataError(it)) }, { result -> val output = checkUpdateDomainRepoMapper.toDomain(result) Either.Right(output) }, ) } catch (ex: Exception) { Either.Left(DataError(ex)) } } }
0
Kotlin
0
0
e35620cf1c66b4f76f0ed30d9c6d499acd134403
1,189
yet-another-compose-showcase-app
MIT License
src/main/kotlin/com/example/coreweb/domains/contacts/models/dtos/ContactDto.kt
teambankrupt
292,072,114
false
{"Kotlin": 287703, "Java": 61650, "HTML": 22230}
package com.example.coreweb.domains.contacts.models.dtos import com.example.coreweb.commons.Constants import com.example.coreweb.domains.base.models.dtos.BaseDto import com.example.coreweb.domains.globaladdresss.models.dtos.GlobalAddressDto import com.example.coreweb.domains.globaladdresss.models.entities.GlobalAddress import com.fasterxml.jackson.annotation.JsonProperty import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import javax.validation.constraints.Email import javax.validation.constraints.Min import javax.validation.constraints.NotNull @ApiModel( value = Constants.Swagger.CONTACT, description = "Api to Create/Read/Update/Delete " + Constants.Swagger.CONTACT ) class ContactDto : BaseDto() { @NotNull @ApiModelProperty(example = "Mr. X", required = true) lateinit var name: String @NotNull @ApiModelProperty(example = "01918283837", required = true) lateinit var phone: String @Email @ApiModelProperty(example = "<EMAIL>") var email: String? = null @ApiModelProperty(required = true) @NotNull @JsonProperty("address") lateinit var address: GlobalAddressDto @ApiModelProperty(required = true) @JsonProperty("user_id") @NotNull @Min(1) var userId: Long = 0 }
3
Kotlin
0
2
e6613a4ac6cac29a67029d9073b53c1a2aa3767f
1,295
coreweb
Apache License 2.0
app/src/main/kotlin/com/codeka/picscan/model/ImageFilterType.kt
codeka
328,104,934
false
null
package com.codeka.picscan.model enum class ImageFilterType { None, Test }
0
Kotlin
0
0
97ed19362b4c499068fdb911f84558800875d59f
79
picscan
Apache License 2.0
app/src/main/kotlin/com/codeka/picscan/model/ImageFilterType.kt
codeka
328,104,934
false
null
package com.codeka.picscan.model enum class ImageFilterType { None, Test }
0
Kotlin
0
0
97ed19362b4c499068fdb911f84558800875d59f
79
picscan
Apache License 2.0
app/src/main/java/com/concordium/wallet/data/room/AccountWithTransfersDao.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.data.room import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction @Dao interface AccountWithTransfersDao { @Transaction @Query("SELECT * FROM account_table") fun getAccountsWithTransfers(): List<AccountWithTransfers> }
77
Kotlin
1
6
cf482234db350007bdfef2540e16b07bfa174d03
293
concordium-reference-wallet-android
Apache License 2.0
app/src/main/java/com/example/githubuserapp/ui/detail/viewmodel/ReposViewModel.kt
tiochoirul
577,171,560
false
{"Kotlin": 54315}
package com.example.githubuserapp.ui.detail.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.githubuserapp.api.ApiConfig import com.example.githubuserapp.data.response.RepositoryResponseItem import com.example.githubuserapp.ui.events.Event import retrofit2.Call import retrofit2.Callback import retrofit2.Response class ReposViewModel: ViewModel() { private val _repository = MutableLiveData<ArrayList<RepositoryResponseItem>>() val repository: LiveData<ArrayList<RepositoryResponseItem>> = _repository private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> = _isLoading private val _snackbarText = MutableLiveData<Event<String>>() val snackbarText: LiveData<Event<String>> = _snackbarText fun getRepository(userName: String) { _isLoading.value = true val client = ApiConfig.getApiService().getRepositoryUser(userName) client.enqueue(object : Callback<ArrayList<RepositoryResponseItem>> { override fun onResponse( call: Call<ArrayList<RepositoryResponseItem>>, response: Response<ArrayList<RepositoryResponseItem>> ) { _isLoading.value = false if (response.isSuccessful) { _repository.postValue(response.body()) } else { Log.d(TAG, "onFailure: ${response.message()}") _snackbarText.value = Event("onFailure: ${response.message()}") } } override fun onFailure(call: Call<ArrayList<RepositoryResponseItem>>, t: Throwable) { _isLoading.value = false Log.d(TAG, "onFailure: ${t.message}") _snackbarText.value = Event("onFailure: ${t.message}") } }) } companion object { private const val TAG = "RepositoryViewModel" } }
0
Kotlin
0
1
e28ca727d16b8cec39d3fc34e7d468084f017394
2,019
githubsearch-app
MIT License
smash-ranks-android/app/src/test/java/com/garpr/android/data/models/AvatarTest.kt
charlesmadere
41,832,700
true
null
package com.garpr.android.data.models import com.garpr.android.test.BaseTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test class AvatarTest : BaseTest() { companion object { private val AVATAR_1 = Avatar(null, null, null, null) private val AVATAR_2 = Avatar("large", "medium", "original", "small") private val AVATAR_3 = Avatar(null, "medium", "original", "small") private val AVATAR_4 = Avatar(" ", null, "", "small") private val AVATAR_5 = Avatar("", " ", "original", null) private val AVATAR_6 = Avatar() } @Test fun testMediumButFallbackToNull1() { assertNull(AVATAR_1.largeButFallbackToMediumThenOriginalThenSmall) } @Test fun testMediumButFallbackToNull2() { assertNull(AVATAR_6.largeButFallbackToMediumThenOriginalThenSmall) } @Test fun testLargeButFallbackToLarge() { assertEquals("large", AVATAR_2.largeButFallbackToMediumThenOriginalThenSmall) } @Test fun testLargeButFallbackToMedium() { assertEquals("medium", AVATAR_3.largeButFallbackToMediumThenOriginalThenSmall) } @Test fun testLargeButFallbackToSmall() { assertEquals("small", AVATAR_4.largeButFallbackToMediumThenOriginalThenSmall) } @Test fun testLargeButFallbackToOriginal() { assertEquals("original", AVATAR_5.largeButFallbackToMediumThenOriginalThenSmall) } }
0
Kotlin
0
9
151b2a0f9b4d38be60c3f73344ca444f17810bfd
1,466
smash-ranks-android
The Unlicense
src/main/kotlin/com/ingresso/greatrebirth/common/tile/TileAltarRebirth.kt
Shusharu
857,046,407
false
{"Kotlin": 31101, "Java": 3685}
package com.ingresso.greatrebirth.common.tile import com.ingresso.greatrebirth.Main import com.ingresso.greatrebirth.common.container.ContainerAltarRebirth import net.minecraft.core.BlockPos import net.minecraft.nbt.CompoundTag import net.minecraft.network.chat.Component import net.minecraft.world.MenuProvider import net.minecraft.world.entity.player.Inventory import net.minecraft.world.entity.player.Player import net.minecraft.world.inventory.AbstractContainerMenu import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.minecraftforge.fluids.FluidType import wayoftime.bloodmagic.altar.IBloodAltar import wayoftime.bloodmagic.common.tile.TileInventory class TileAltarRebirth( type: BlockEntityType<*>, pos: BlockPos, state: BlockState ) : TileInventory(type, 1, "rebirthaltar", pos, state), MenuProvider, IBloodAltar { private var bloodAmount = 0 constructor(pos: BlockPos, state: BlockState) : this(Main.TILE_ALTAR_REBIRTH.get(), pos, state) override fun serialize(tag: CompoundTag): CompoundTag { super.serialize(tag) tag.putInt("bloodAmount", bloodAmount) return tag } override fun deserialize(tag: CompoundTag) { super.deserialize(tag) bloodAmount = tag.getInt("bloodAmount") } override fun getCapacity(): Int = FluidType.BUCKET_VOLUME * 100 override fun getCurrentBlood(): Int = bloodAmount override fun getTier(): Int = 5 override fun getProgress(): Int = 0 override fun getSacrificeMultiplier(): Float = 0f override fun getSelfSacrificeMultiplier(): Float = 0f override fun getOrbMultiplier(): Float = 0f override fun getDislocationMultiplier(): Float = 0f override fun getConsumptionMultiplier(): Float = 0f override fun getConsumptionRate(): Float = 0f override fun getChargingRate(): Int = 0 override fun getChargingFrequency(): Int = 0 override fun getTotalCharge(): Int = 0 override fun getLiquidRequired(): Int = 0 override fun getBufferCapacity(): Int = 0 override fun sacrificialDaggerCall(amount: Int, isSacrifice: Boolean) { if (bloodAmount < capacity) { bloodAmount += amount } } override fun startCycle() { } override fun checkTier() { } override fun isActive(): Boolean = false override fun setActive() {} override fun fillMainTank(amount: Int): Int { TODO("Not yet implemented") } override fun requestPauseAfterCrafting(cooldown: Int) { } override fun createMenu( id: Int, inv: Inventory, player: Player ): AbstractContainerMenu = ContainerAltarRebirth(id, this, inv) override fun getDisplayName(): Component = Component.literal("Rebirth Altar") }
0
Kotlin
0
0
a84ca8ccaf517abb27f20e8aef0c9e160d835386
2,839
Great-Rebirth
MIT License
domain/src/main/kotlin/com/lukelorusso/domain/functions/StatementSingle.kt
lukelorusso
277,556,469
false
null
package com.lukelorusso.domain.functions import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.SingleSource import io.reactivex.rxjava3.plugins.RxJavaPlugins /** * Copyright (C) 2020 <NAME> * Licensed under the Apache License Version 2.0 * * Imperative statements expressed as Single operators. * inspiration from https://github.com/akarnokd/RxJava2Extensions */ object StatementSingle { /** * Return an Single that emits the emissions from one specified * Single if a condition evaluates to true, or from another specified * Single otherwise. * * @param <R> the result value type * @param condition the condition that decides which Observable to emit the emissions from * @param then the Single sequence to emit to if `condition` is `true` * @param orElse the Single sequence to emit to if `condition` is `false` * @return an Single that mimics either the `then` or `orElse` Single depending on a condition function */ fun <R : Any> ifThen( condition: Boolean, then: SingleSource<out R>, orElse: Single<out R> ): Single<R> = RxJavaPlugins.onAssembly(SingleIfThen(condition, then, orElse)) }
0
null
49
4
932fe4a62057ae1cb43e9c249e819a2b3c69b375
1,216
ColorBlindClickAndroid
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/swipeback/app/SwipeBackActivityBase.kt
altaf933
122,962,254
false
{"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 485, "XML": 261, "Java": 4}
package io.github.feelfreelinux.wykopmobilny.ui.swipeback.app import io.github.feelfreelinux.wykopmobilny.ui.swipeback.SwipeBackLayout interface SwipeBackActivityBase { fun getSwipeBackLayout() : SwipeBackLayout? fun scrollToFinishActivity() fun setSwipeBackEnable(isEnabled : Boolean) }
1
null
1
1
0c2d9fc015a5bef5b258481e4233d04ab5705a49
301
WykopMobilny
MIT License
system-service/permission-manager/src/main/kotlin/org/a_cyb/sayitalarm/system_service/permission_manager/PermissionChecker.kt
a-cyborg
751,578,623
false
{"Kotlin": 716805}
/* * Copyright (c) 2024 <NAME> / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package org.a_cyb.sayitalarm.system_service.permission_manager import android.Manifest import android.app.AlarmManager import android.app.NotificationManager import android.content.Context import android.content.pm.PackageManager.PERMISSION_DENIED import android.os.Build import android.os.PowerManager class PermissionChecker( private val context: Context, ) : PermissionManagerContract.PermissionCheckerContract { override fun getMissingEssentialPermission(): List<String> { val missingPermissions = mutableListOf<String>() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val alarmManager = context.getSystemService(AlarmManager::class.java) if (!alarmManager.canScheduleExactAlarms()) { missingPermissions.add(Manifest.permission.SCHEDULE_EXACT_ALARM) } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { val postNotificationPermission = Manifest.permission.POST_NOTIFICATIONS if (context.checkSelfPermission(postNotificationPermission) == PERMISSION_DENIED) { missingPermissions.add(postNotificationPermission) } } if (context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PERMISSION_DENIED) { missingPermissions.add(Manifest.permission.RECORD_AUDIO) } return missingPermissions } override fun getMissingPermission(): List<String> { val missingPermissions = mutableListOf<String>() val powerManager = context.getSystemService(PowerManager::class.java) if (!powerManager.isIgnoringBatteryOptimizations(context.packageName)) { missingPermissions.add(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) } val notificationManager = context.getSystemService(NotificationManager::class.java) if (!notificationManager.isNotificationPolicyAccessGranted) { missingPermissions.add(Manifest.permission.ACCESS_NOTIFICATION_POLICY) } val audioFilePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.READ_MEDIA_AUDIO } else { Manifest.permission.READ_EXTERNAL_STORAGE } if (context.checkSelfPermission(audioFilePermission) == PERMISSION_DENIED) { missingPermissions.add(audioFilePermission) } return missingPermissions } }
0
Kotlin
0
0
f20079c06adf86e8297ab8322887c875715e6cd1
2,616
SayItAlarm
Apache License 2.0
app/src/main/java/com/bannanguy/task1androidapp/ui/cityList/CitiesListViewModel.kt
vvban
759,158,591
false
{"Kotlin": 23658}
package com.bannanguy.task1androidapp.ui.cityList import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.bannanguy.task1androidapp.api.weather.WeatherAPI import com.bannanguy.task1androidapp.data.* import com.bannanguy.task1androidapp.utils.ConfigPropertiesUtils import java.io.File class CitiesListViewModel( private val dataSource: CityDataSource, private val cacheDir: File ) : ViewModel() { private val citiesWeatherInfoLiveData: MutableLiveData<List<CityWeatherInfo>> by lazy { MutableLiveData<List<CityWeatherInfo>>() } fun loadWeatherData() { val apiKey = ConfigPropertiesUtils.getValue("api") if (apiKey == null) { println("Error: API key is null.") return } val listOfCities = dataSource.getCityList() val currentListOfCityWeatherInfo: MutableList<CityWeatherInfo> = ArrayList<CityWeatherInfo>(0).toMutableList() listOfCities.forEach { city -> WeatherAPI.getWeatherByCity( cacheDir, city ) { weatherResponse -> val cityWeatherInfo = CityWeatherInfo( city.id, weatherResponse.location.name, weatherResponse.current.temp_c ) currentListOfCityWeatherInfo.add(cityWeatherInfo) citiesWeatherInfoLiveData.postValue( currentListOfCityWeatherInfo ) } } } fun observeLiveData() : LiveData<List<CityWeatherInfo>> { return citiesWeatherInfoLiveData } } class CitiesListViewModelFactory(private val context: Context) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(CitiesListViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return CitiesListViewModel( dataSource = CityDataSource.getDataSource(context.resources), cacheDir = context.cacheDir ) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
0
d347343c3745ea6f4ad5c923dc54a8efd25dab63
2,318
task1-android-app
MIT License
core/vmrequest/src/main/kotlin/com/vmloft/develop/library/request/RResponse.kt
lzan13
78,939,095
false
null
package com.vmloft.develop.library.request /** * Create by lzan13 on 2020/02/13 18:56 * 描述:统一请求结果数据 bean */ data class RResponse<out T>(val code: Int, val msg: String, val data: T)
1
null
14
34
c6eca3fb479d82ca14ca3bdcc3fb5f5494a4db0c
185
VMLibrary
MIT License
service/src/main/java/com/tink/service/authentication/UserEventBus.kt
tink-ab
245,144,086
false
{"Gradle Kotlin DSL": 7, "Gradle": 4, "Java Properties": 2, "Markdown": 2, "Shell": 9, "Text": 2, "Ignore List": 5, "Batchfile": 1, "YAML": 1, "INI": 4, "Proguard": 3, "Kotlin": 252, "XML": 4, "CODEOWNERS": 1, "OASv2-json": 2, "Java": 1}
package com.tink.service.authentication import com.tink.model.user.User import com.tink.service.di.ServiceScope import io.reactivex.disposables.Disposable import io.reactivex.subjects.BehaviorSubject import javax.inject.Inject @ServiceScope class UserEventBus @Inject constructor() { private val publisherSubject = BehaviorSubject.create<User>() fun subscribe(onUserReceived: (User) -> Unit): Disposable = publisherSubject.subscribe(onUserReceived) fun postUser(user: User) = publisherSubject.onNext(user) }
1
null
6
1
e2202bb6892e5310feaf5fa51a35714302ddb7b0
532
tink-core-android
MIT License
parent/src/main/java/sk/backbone/parent/application/dependency_injection/ParentServerRepositoryModule.kt
backbonesk
273,036,191
false
null
package sk.backbone.parent.application.dependency_injection import android.content.Context import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.logging.HttpLoggingInterceptor import sk.backbone.parent.repositories.server.client.HttpClient import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object ParentServerRepositoryModule { @ParentDefaultHttpClient @Singleton @Provides fun provideParentDefaultHttpClient(@ApplicationContext context: Context): HttpClient { return HttpClient(context) } @ParentDefaultHttpClientLogging @Provides @Singleton fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY return logging } }
0
Kotlin
1
2
784297b125f7870b97dc31f14a8c74e994f009d4
958
parent
MIT License
core/android/src/main/kotlin/com/walletconnect/android/internal/utils/Expiration.kt
WalletConnect
435,951,419
false
{"Kotlin": 2502705, "Java": 4366, "Shell": 1892}
@file:JvmName("Expiration") package com.walletconnect.android.internal.utils val PROPOSAL_EXPIRY: Long get() = currentTimeInSeconds + fiveMinutesInSeconds val ACTIVE_SESSION: Long get() = currentTimeInSeconds + weekInSeconds
78
Kotlin
71
199
e373c535d7cefb2f932368c79622ac05763b411a
226
WalletConnectKotlinV2
Apache License 2.0
analytics/src/main/java/io/appmetrica/analytics/impl/component/processor/event/ExternalAttributionHandler.kt
appmetrica
650,662,094
false
null
package io.appmetrica.analytics.impl.component.processor.event import io.appmetrica.analytics.coreutils.internal.time.TimeProvider import io.appmetrica.analytics.impl.CounterReport import io.appmetrica.analytics.impl.attribution.ExternalAttributionHelper import io.appmetrica.analytics.impl.attribution.ExternalAttributionTypeConverter import io.appmetrica.analytics.impl.component.ComponentUnit import io.appmetrica.analytics.impl.protobuf.backend.ExternalAttribution.ClientExternalAttribution class ExternalAttributionHandler( component: ComponentUnit, timeProvider: TimeProvider ) : ReportComponentHandler(component) { private val externalAttributionHelper = ExternalAttributionHelper(component, timeProvider) override fun process(reportData: CounterReport): Boolean { if (!externalAttributionHelper.isInAttributionCollectingWindow()) { component.publicLogger.i("Ignoring attribution since out of collecting interval") return true } val attribution = ClientExternalAttribution.parseFrom(reportData.valueBytes) val attributionType = attribution.attributionType val attributionJson = String(attribution.value) if (!externalAttributionHelper.isNewAttribution(attributionType, attributionJson)) { component.publicLogger.i( "Ignoring attribution " + "of type `${ExternalAttributionTypeConverter.toString(attributionType)}` " + "with value `$attributionJson` " + "since it is not new" ) return true } externalAttributionHelper.saveAttribution(attributionType, attributionJson) component.publicLogger.i( "Handling attribution " + "of type `${ExternalAttributionTypeConverter.toString(attributionType)}`" ) return false } }
3
null
5
54
81572296e16423617822fbc19c2465d6b7b4713e
1,899
appmetrica-sdk-android
MIT License
android/app/src/main/java/com/fabirt/debty/ui/people/detail/PersonDetailViewModel.kt
fabirt
349,736,814
false
{"Kotlin": 164948}
package com.fabirt.debty.ui.people.detail import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabirt.debty.domain.model.Movement import com.fabirt.debty.domain.model.MovementType import com.fabirt.debty.domain.model.Person import com.fabirt.debty.domain.repository.movement.MovementRepository import com.fabirt.debty.domain.repository.person.PersonRepository import com.fabirt.debty.ui.common.SwipeToDeleteDelegate import com.fabirt.debty.util.Event import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class PersonDetailViewModel @Inject constructor( private val personRepository: PersonRepository, private val movementRepository: MovementRepository ) : ViewModel(), SwipeToDeleteDelegate<Movement> { private val _lastItemRemoved = MutableLiveData<Event<Movement>>() val lastItemRemoved: LiveData<Event<Movement>> get() = _lastItemRemoved fun requestPerson(personId: Int) = personRepository.requestPerson(personId) fun requestMovements(personId: Int): Flow<List<Movement>> = movementRepository.requestPersonMovementsSortedByDate(personId) fun requestBalance(personId: Int) = movementRepository.requestPersonBalance(personId) suspend fun deletePerson(personId: Int) { personRepository.deleteAllPersonRelatedData(personId) } suspend fun deleteHistory(personId: Int): Int { return personRepository.deleteAllPersonRelatedData(personId, false) } override fun onSwiped(item: Movement) { viewModelScope.launch { movementRepository.deleteMovement(item) _lastItemRemoved.value = Event(item) } } fun undoItemRemoval(item: Movement) { viewModelScope.launch { movementRepository.createMovement(item) } } fun settleAccount(personId: Int, amount: Double, description: String) { val movementType = if (amount > 0) MovementType.OwedMeSettled else MovementType.IOwedSettled val movement = Movement( 0, personId, amount * -1, System.currentTimeMillis(), description, movementType ) viewModelScope.launch { movementRepository.createMovement(movement) } } fun payLoan(m: Movement) { val movement = m.copy( id = 0, amount = m.amount * -1, date = System.currentTimeMillis(), type = when (m.type) { MovementType.ILent -> MovementType.PaidMe MovementType.LentMe -> MovementType.IPaid else -> m.type } ) viewModelScope.launch { movementRepository.createMovement(movement) } } fun updatePerson(person: Person) { viewModelScope.launch { personRepository.updatePerson(person) } } }
0
Kotlin
8
46
fd9e7b97728f57c93104caa1c4c6ae70ff770ec7
3,071
debty-v2
MIT License
source_code/app/src/main/java/com/example/speakingtopics/network/apiservice/ApiService.kt
radocodes
565,788,532
false
{"Kotlin": 26458}
package com.example.speakingtopics.network.apiservice import com.example.speakingtopics.network.models.topics.TopicResponseModel interface ApiService { suspend fun getDefaultTopics(): List<TopicResponseModel> }
0
Kotlin
0
0
3d262bac0d3dece0e1993171021a5e217bd89714
216
Speaking-Topics
MIT License
src/me/anno/gpu/texture/TextureReader.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10736182, "C": 236426, "Java": 6754, "Lua": 4404, "C++": 3070, "GLSL": 2698}
package me.anno.gpu.texture import me.anno.cache.AsyncCacheData import me.anno.config.DefaultConfig import me.anno.gpu.GFX import me.anno.image.Image import me.anno.image.ImageCache import me.anno.image.ImageReadable import me.anno.image.ImageAsFolder import me.anno.image.ImageTransform import me.anno.image.raw.GPUImage import me.anno.io.MediaMetadata.Companion.getMeta import me.anno.io.files.FileReference import me.anno.io.files.InvalidRef import me.anno.io.files.Signature import me.anno.utils.InternalAPI import me.anno.utils.OS import me.anno.utils.Sleep import me.anno.utils.async.Callback import me.anno.video.VideoCache import org.apache.logging.log4j.LogManager @InternalAPI class TextureReader(val file: FileReference) : AsyncCacheData<ITexture2D>() { companion object { @JvmStatic val imageTimeout get() = DefaultConfig["ui.image.frameTimeout", 5000L] @JvmStatic private val LOGGER = LogManager.getLogger(TextureReader::class) // injected by ImagePlugin @JvmField var findExifRotation: ((FileReference, Callback<ImageTransform?>) -> Unit)? = null @JvmStatic fun getRotation(src: FileReference, callback: Callback<ImageTransform?>) { if (src == InvalidRef || src.isDirectory) return callback.ok(null) // which files can contain exif metadata? // according to https://exiftool.org/TagNames/EXIF.html, // JPG, TIFF, PNG, JP2, PGF, MIFF, HDP, PSP and XC, AVI and MOV val findRotation = findExifRotation ?: return callback.ok(null) findRotation(src, callback) } } private fun callback(texture: ITexture2D?, error: Exception?) { if (hasValue) { texture?.destroy() LOGGER.warn("Destroying $texture for $file before it was used") } else { value = texture error?.printStackTrace() } } init { if (file is ImageReadable) { val texture = Texture2D("i2t/ir/${file.name}", 1024, 1024, 1) texture.create(file.readGPUImage(), true, ::callback) } else { val cpuImage = ImageCache.getImageWithoutGenerator(file) if (cpuImage != null) { val texture = Texture2D("i2t/ci/${file.name}", cpuImage.width, cpuImage.height, 1) cpuImage.createTexture(texture, sync = true, checkRedundancy = true, ::callback) } else loadTexture() } } private fun loadTexture() { when (if (OS.isWeb) null else Signature.findNameSync(file)) { "dds", "media" -> tryUsingVideoCache(file) else -> ImageAsFolder.readImage(file, true).waitForGFX(::loadImage) } } private fun loadImage(image: Image?) { when (image) { is GPUImage -> { val texture = Texture2D("copyOf/${image.texture.name}", image.width, image.height, 1) texture.rotation = (image.texture as? Texture2D)?.rotation texture.create(image, true, ::callback) } null -> { LOGGER.warn("Null from ImageReader for $file") value = null } else -> { getRotation(file) { rot, _ -> val texture = Texture2D("i2t/?/$file", image.width, image.height, 1) texture.rotation = rot texture.create(image, true, ::callback) } } } } private fun tryUsingVideoCache(file: FileReference) { // calculate required scale? no, without animation, we don't need to scale it down ;) val meta = getMeta(file, false) if (meta == null || !meta.hasVideo || meta.videoFrameCount < 1) { LOGGER.warn("Cannot load $file using VideoCache") value = null } else { Sleep.waitUntilDefined(true, { val frame = VideoCache.getVideoFrame(file, 1, 0, 0, 1.0, imageTimeout, true) if (frame != null && (frame.isCreated || frame.isDestroyed)) frame else null }, { frame -> GFX.addGPUTask("ImageData.useFFMPEG", frame.width, frame.height) { value = frame.toTexture() } }) } } }
0
Kotlin
3
24
63377c2e684adf187a31af0f4e5dd0bfde1d050e
4,349
RemsEngine
Apache License 2.0
compiler/testData/codegen/box/when/kt2457.kt
JakeWharton
99,388,807
false
null
fun foo(i: Int) : Int = when (i) { 1 -> 1 null -> 1 else -> 1 } fun box() : String = if (foo(1) == 1) "OK" else "fail"
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
152
kotlin
Apache License 2.0
domain/src/main/java/com/seo4d696b75/android/ekisagasu/domain/dataset/update/DataUpdateUseCase.kt
Seo-4d696b75
247,417,963
false
{"Kotlin": 421916}
package com.seo4d696b75.android.ekisagasu.domain.dataset.update import com.seo4d696b75.android.ekisagasu.domain.dataset.DataRepository import com.seo4d696b75.android.ekisagasu.domain.dataset.DataVersion import com.seo4d696b75.android.ekisagasu.domain.dataset.LatestDataVersion import com.seo4d696b75.android.ekisagasu.domain.dataset.RemoteDataRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.withContext import java.io.File import javax.inject.Inject class DataUpdateUseCase @Inject constructor( private val repository: DataRepository, private val remoteRepository: RemoteDataRepository, ) { private val _progress = MutableStateFlow<DataUpdateProgress>(DataUpdateProgress.Download(0)) val progress = _progress.asStateFlow() suspend operator fun invoke( info: LatestDataVersion, dir: File, ): Result<DataVersion> = withContext(Dispatchers.IO) { if (!dir.exists() || !dir.isDirectory) { require(dir.mkdir()) } _progress.value = DataUpdateProgress.Download(0) runCatching { var percent = 0 remoteRepository.download(info.version, dir) { val p = (it * 100 / info.length).toInt() if (p in 1..100 && p > percent) { _progress.value = DataUpdateProgress.Download(p) percent = p } } _progress.value = DataUpdateProgress.Save repository.updateData(info, dir) }.also { dir.deleteRecursively() } } }
4
Kotlin
0
0
ca323eb5aa46187d16d335a10fd64d51bfd6c651
1,672
checkhelper
MIT License
app/src/main/java/com/mindorks/framework/mvvm/ui/account/login/register/RegisterActivity.kt
halimbimantara
510,920,973
false
{"Kotlin": 361926, "Java": 109358}
/* * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://mindorks.com/license/apache-v2 * * 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.mindorks.framework.mvvm.ui.account.login.register import android.app.DatePickerDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.View import android.widget.AdapterView import android.widget.DatePicker import android.widget.TextView import com.mindorks.framework.mvvm.R import com.mindorks.framework.mvvm.core.data.model.others.AppDataConstants.Register.user import com.mindorks.framework.mvvm.core.data.remote.NetworkErrorHandlingTag import com.mindorks.framework.mvvm.core.ui.common.extensions.etToString import com.mindorks.framework.mvvm.core.utils.AppConstants import com.mindorks.framework.mvvm.core.utils.AppConstants.USER_GENDER_FEMALE import com.mindorks.framework.mvvm.core.utils.AppConstants.USER_GENDER_MALE import com.mindorks.framework.mvvm.core.utils.DateUtils import com.mindorks.framework.mvvm.core.utils.rx.observe import com.mindorks.framework.mvvm.databinding.ActivityRegisterBinding import com.mindorks.framework.mvvm.di.component.ActivityComponent import com.mindorks.framework.mvvm.ui.base.BaseActivity import com.mindorks.framework.mvvm.ui.home.HomeActivityMain import com.mindorks.framework.mvvm.utils.ext.gone import com.mindorks.framework.mvvm.utils.ext.visible import timber.log.Timber import java.text.SimpleDateFormat import java.util.* class RegisterActivity : BaseActivity<ActivityRegisterBinding?, RegisterViewModel?>() { private var tglLahir: String = "" private var gender: String = ""// private lateinit var mBinding: ActivityRegisterBinding val listJenkel = arrayOf("--Pilih jenis kelamin--", "Laki - Laki", "Perempuan") var calendar = Calendar.getInstance() fun openMainActivity() { val intent: Intent = HomeActivityMain.newIntent(this@RegisterActivity) startActivity(intent) finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = viewDataBinding!! intUi() actionUi() } private fun intUi() { val items = listOf(*listJenkel) val adapter = CompletionAdapter( this, R.layout.item_drop_downl, items as MutableList<String> ) mBinding.EtJenkel.setAdapter(adapter) } private fun actionUi() { val startdateListener = DatePickerDialog.OnDateSetListener { _: DatePicker?, year: Int, month: Int, dayOfMonth: Int -> calendar[Calendar.YEAR] = year calendar[Calendar.MONTH] = month calendar[Calendar.DAY_OF_MONTH] = dayOfMonth updateLabel(mBinding.EtTtl) } mBinding.EtTtl.setOnClickListener { val mdialog = DatePickerDialog( this@RegisterActivity, startdateListener, calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH] ) mdialog.show() } mBinding.EtJenkel.onItemClickListener = AdapterView.OnItemClickListener { adapterView: AdapterView<*>?, view: View?, i: Int, l: Long -> gender = if (listJenkel[i].contains("Laki")) { USER_GENDER_MALE } else if (listJenkel[i].contains("Perempuan")) { USER_GENDER_FEMALE } else { listJenkel[i] } } mBinding.BtnApply.setOnClickListener { formValidation() } } private fun updateLabel(textView: TextView) { val myFormat = AppConstants.DATE_FORMAT_MDY_KOMA //In which you need put here val sdf = SimpleDateFormat(myFormat, Locale.ENGLISH) textView.text = sdf.format(calendar.time) tglLahir = DateUtils.formatDateto( sdf.format(calendar.time), AppConstants.DATE_FORMAT_DEFAULT ) } private fun formValidation() { val firstName = mBinding.EtNamaDepan.etToString() val lastName = mBinding.EtNamaBelakang.etToString() val email = mBinding.EtEmail.etToString() val pwd = mBinding.EtPassword.etToString() val uname = mBinding.EtUsername.etToString() val ttl = mBinding.EtTtl.etToString() if (firstName.isEmpty()) { mBinding.EtNamaDepan.error = getString(R.string.info_field_canempty) } else if (lastName.isEmpty()) { mBinding.EtNamaBelakang.error = getString(R.string.info_field_canempty) } else if (email.isEmpty()) { mBinding.EtEmail.error = getString(R.string.info_field_canempty) } else if (pwd.isEmpty()) { mBinding.EtPassword.error = getString(R.string.info_field_canempty) } else if (uname.isEmpty()) { mBinding.EtUsername.error = getString(R.string.info_field_canempty) } else if (ttl.isEmpty()) { mBinding.EtTtl.error = getString(R.string.info_field_canempty) } else if (gender.contains("Pilih")) { mBinding.EtJenkel.error = getString(R.string.info_field_canempty) } else { showLoadingProgress(true) mViewModel!!.postRegister(firstName, lastName, gender, user, email, uname, pwd) } } private fun showLoadingProgress(show: Boolean) { if (show) { mBinding.BtnApply.gone() mBinding.CLoading.visible() } else { mBinding.BtnApply.visible() mBinding.CLoading.gone() } } override fun performDependencyInjection(buildComponent: ActivityComponent) { buildComponent.inject(this) } companion object { fun newIntent(context: Context?): Intent { return Intent(context, RegisterActivity::class.java) } } override val bindingVariable: Int get() = 0 override val layoutId: Int get() = R.layout.activity_register override fun observeChange() { observe(mViewModel!!.successRegister, ::isSuccess) observe(mViewModel!!.errorData, ::handlingError) } private fun handlingError(errorResponse: NetworkErrorHandlingTag) { when (errorResponse.tipeError) { AppConstants.ERROR_TYPE_NETWORK -> { Timber.i("Network Error") showMessage("${errorResponse.messages}") } AppConstants.ERROR_TYPE_TOKEN_FAILED -> { Timber.i("Regenerate token") showMessage("Regenerate token ${errorResponse.messages}") } AppConstants.ERROR_TYPE_OTHER -> { Timber.i("Failed ${errorResponse.messages}") showMessage("Failed ${errorResponse.messages}") } } showLoadingProgress(false) } private fun isSuccess(successRegister: Boolean) { if (successRegister) { showMessage(getString(R.string.alert_success_register)) showLoadingProgress(false) Handler(Looper.getMainLooper()).postDelayed({ finish() }, 3000) } } }
0
Kotlin
0
0
6e0d1073428e064a5abf4aaebedc44fea5abe847
7,821
blitar-membina
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/resource/PopUserOTPResourceController.kt
ministryofjustice
665,659,688
false
{"Kotlin": 1609755, "Dockerfile": 1994}
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.resource import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.Parameter import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import org.hibernate.query.sqm.tree.SqmNode.log import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.config.ErrorResponse import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.config.NoDataWithCodeFoundException import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.data.PoPUserResponse import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.data.popuserapi.OneLoginData import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.jpa.entity.PoPUserOTPEntity import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.service.PoPUserOTPService import uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.service.PrisonerService @RestController @Validated @RequestMapping("/resettlement-passport/popUser", produces = [MediaType.APPLICATION_JSON_VALUE]) @PreAuthorize("hasRole('RESETTLEMENT_PASSPORT_EDIT') or hasAuthority('SCOPE_scope')") class PoPUserOTPResourceController(private val popUserOTPService: PoPUserOTPService, private val prisonerService: PrisonerService) { @GetMapping("/otp", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Get all OTP", description = "Get All Person on Probation Users OTP") @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Successful Operation", ), ApiResponse( description = "Not found", responseCode = "404", content = [Content(mediaType = MediaType.APPLICATION_JSON_VALUE)], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [ Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = Schema(implementation = ErrorResponse::class), ), ], ), ApiResponse( responseCode = "400", description = "Incorrect information provided to perform assessment match", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun getPoPUsersOTP() = popUserOTPService.getAllOTPs() @GetMapping("/{nomsId}/otp", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Get OTP for NomsId", description = "Get Person on Probation User OTP") @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Successful Operation", ), ApiResponse( description = "Not found", responseCode = "404", content = [Content(mediaType = MediaType.APPLICATION_JSON_VALUE)], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [ Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = Schema(implementation = ErrorResponse::class), ), ], ), ApiResponse( responseCode = "400", description = "Incorrect information provided to perform assessment match", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun getPoPUserOTPByNomisId( @Schema(example = "AXXXS", required = true) @PathVariable("nomsId") nomsId: String, ): PoPUserOTPEntity? { val prisonerEntity = prisonerService.getPrisonerEntity(nomsId) return popUserOTPService.getOTPByPrisoner(prisonerEntity) } @PostMapping("/{nomsId}/otp", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Generate OTP for PoP User", description = "Generate OTP for Person On Probation User") @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Successful Operation", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [ Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = Schema(implementation = ErrorResponse::class), ), ], ), ApiResponse( responseCode = "400", description = "Incorrect information provided", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun createOTPByNomsId( @Schema(example = "AXXXS", required = true) @PathVariable("nomsId") nomsId: String, ): PoPUserOTPEntity { val prisonerEntity = prisonerService.getPrisonerEntity(nomsId) return popUserOTPService.createPoPUserOTP(prisonerEntity) } @DeleteMapping("/{nomsId}/otp", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Delete PoP User OTP", description = "Delete Person On Probation User OTP") @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Successful Operation", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [ Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = Schema(implementation = ErrorResponse::class), ), ], ), ApiResponse( responseCode = "400", description = "Incorrect information provided", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun deletePoPUserOTPByNomsId( @PathVariable("nomsId") @Parameter(required = true) nomsId: String, ) { val prisonerEntity = prisonerService.getPrisonerEntity(nomsId) val popUserOTPEntity = popUserOTPService.getOTPByPrisoner(prisonerEntity) ?: throw NoDataWithCodeFoundException( "PoPUser Id", nomsId, ) popUserOTPService.deletePoPUserOTP(popUserOTPEntity) } @PostMapping("/onelogin/verify", produces = [MediaType.APPLICATION_JSON_VALUE]) @Operation(summary = "Verify OTP for PoP User", description = "Verify OTP for Person On Probation User") @ApiResponses( value = [ ApiResponse( responseCode = "200", description = "Successful Operation", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Forbidden, requires an appropriate role", content = [ Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = Schema(implementation = ErrorResponse::class), ), ], ), ApiResponse( responseCode = "400", description = "Incorrect information provided", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun verifyOTPByOneLoginURN( @RequestBody oneLoginUserData: OneLoginData, ): PoPUserResponse? { log.debug("In verifyOTPByOneLoginURN") return popUserOTPService.getPoPUserVerified(oneLoginUserData) } }
1
Kotlin
2
1
cb002e1d1cbdb5889469d78ec48ebe4174916771
9,172
hmpps-resettlement-passport-api
MIT License
app/src/main/java/knf/kuma/database/dao/QueueDAO.kt
jordyamc
119,774,950
false
null
package knf.kuma.database.dao import androidx.lifecycle.LiveData import androidx.room.* import knf.kuma.database.BaseConverter import knf.kuma.pojos.QueueObject @Dao @TypeConverters(BaseConverter::class) interface QueueDAO { @get:Query("SELECT MIN(aid) AS id,`key`,aid,name,number,eid,isFile,uri,time,link FROM queueobject ORDER BY name") val allAlone: LiveData<MutableList<QueueObject>> @get:Query("SELECT * FROM queueobject ORDER BY name") val all: LiveData<MutableList<QueueObject>> @get:Query("SELECT * FROM queueobject ORDER BY time ASC") val allAsort: LiveData<MutableList<QueueObject>> @get:Query("SELECT count(*) FROM queueobject") val countLive: LiveData<Int> @Query("SELECT count(*) FROM queueobject WHERE eid = :eid") fun isInQueue(eid: String): Boolean @Query("SELECT count(*) FROM queueobject WHERE eid = :eid") fun isInQueueLive(eid: String): LiveData<Boolean> @Query("SELECT count(*) FROM queueobject WHERE aid LIKE :aid") fun countAlone(aid: String): Int @Query("SELECT * FROM queueobject WHERE aid = :aid ORDER BY eid+0 ASC") fun getByAid(aid: String): LiveData<MutableList<QueueObject>> @Query("SELECT * FROM queueobject WHERE aid = :aid ORDER BY eid+0 ASC") fun getAllByAid(aid: String): MutableList<QueueObject> @Insert(onConflict = OnConflictStrategy.REPLACE) fun add(queueObject: QueueObject) @Update fun update(vararg objects: QueueObject) @Delete fun remove(queueObject: QueueObject) @Delete fun remove(list: MutableList<QueueObject>) @Query("DELETE FROM queueobject WHERE aid LIKE :aid") fun removeByID(aid: String) @Query("DELETE FROM queueobject WHERE eid LIKE :eid") fun removeByEID(eid: String) }
24
null
39
159
320c4edb7ca7b4e0be6d0f1ad2b61e876f47461d
1,763
UKIKU
MIT License
app/src/main/java/com/vivekupasani/single/viewModels/ProfileViewModel.kt
vivekupasani
856,708,527
false
{"Kotlin": 99984}
package com.vivekupasani.single.viewModels import android.app.Application import android.widget.ProgressBar import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.vivekupasani.single.models.Users class ProfileViewModel(application: Application) : AndroidViewModel(application) { private val auth: FirebaseAuth = FirebaseAuth.getInstance() private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() private val _user = MutableLiveData<Users>() val user: LiveData<Users> get() = _user private val _error = MutableLiveData<String>() val error: LiveData<String> = _error fun fetchUserData() { firestore.collection("Users") .document(auth.currentUser!!.uid) .get() .addOnSuccessListener { if (it.exists()) { val user = it.toObject(Users::class.java) _user.value = user!! } else { _error.value = "User data not found" } } .addOnFailureListener { _error.value = it.message } } }
0
Kotlin
0
0
d239c7716a536e04ee914c91136877257c4f5ebb
1,304
Single
MIT License
chapter4-pwm/src/main/java/com/plattysoft/pwmsamples/LedBrightnessActivity.kt
PacktPublishing
131,269,346
false
null
package com.plattysoft.pwmsamples import android.app.Activity import android.os.Bundle import android.os.Handler import com.google.android.things.pio.PeripheralManager import com.google.android.things.pio.Pwm import java.util.* import kotlin.concurrent.timerTask /** * Created by <NAME> on 13/05/18. */ class LedBrightnessActivity: Activity() { private val initialTime = System.currentTimeMillis() private lateinit var pwm: Pwm private val handler = Handler() private val ledRunnable = object : Runnable { override fun run() { val elapsedSeconds = (System.currentTimeMillis() - initialTime) / 1000.0 val dutyCycle = Math.cos(elapsedSeconds) * 50.0 + 50 pwm.setPwmDutyCycle(dutyCycle) handler.post(this) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) pwm = PeripheralManager.getInstance().openPwm(BoardDefaults.servoPwm) pwm.setPwmFrequencyHz(50.0) pwm.setEnabled(true) handler.post(ledRunnable) } override fun onDestroy() { super.onDestroy() handler.removeCallbacks(ledRunnable) pwm.close() } }
0
null
6
13
62344e949cf1103889086a844de24fa2830db7f6
1,213
Android-Things-Quick-Start-Guide
MIT License
app/src/main/java/com/alossa/alossacapstone/ui/profile/InputWishlistActivity.kt
hikizan
434,510,763
false
null
package com.alossa.alossacapstone.ui.profile import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.lifecycle.ViewModelProvider import com.alossa.alossacapstone.databinding.ActivityInputWishlistBinding import com.alossa.alossacapstone.utils.SharedPref import com.alossa.alossacapstone.utils.ViewModelFactory class InputWishlistActivity : AppCompatActivity() { private lateinit var _binding: ActivityInputWishlistBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityInputWishlistBinding.inflate(layoutInflater) setContentView(_binding.root) supportActionBar?.title = "Tambah Wishlist" supportActionBar?.elevation = 0f supportActionBar?.setDisplayHomeAsUpEnabled(true) val factory = ViewModelFactory.getInstance() val viewModel = ViewModelProvider(this, factory)[ProfilViewModel::class.java] val sharedPref = SharedPref(this) _binding.apply { btnSubmitWishlist.setOnClickListener { val namaWishList = edtWishlistName.text val targetDana = edtWishlistTarget.text val durasi = edtWishlistDuration.text viewModel.addWishList(sharedPref.getId(), namaWishList.toString(), 2, targetDana.toString().toInt(), durasi.toString().toInt(), 1) .observe(this@InputWishlistActivity, { response-> Toast.makeText( this@InputWishlistActivity, response.msg, Toast.LENGTH_LONG ).show() if (response.status.equals("success")) { //val intent = Intent(this@InputWishlistActivity, WishlistActivity::class.java) //startActivity(intent) finish() } }) } } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
0
Kotlin
0
0
ddb8bdb0c907abccc190d88bd30c8299b3b1b4df
2,186
Alossa-Capstone
Apache License 2.0
app/src/main/java/com/ladsers/ztemp/domain/states/DeviceStatusState.kt
Ladsers
713,928,864
false
{"Kotlin": 33046}
package com.ladsers.ztemp.domain.states import androidx.compose.ui.graphics.vector.ImageVector import com.ladsers.ztemp.data.models.DeviceStatus interface DeviceStatusState { object InProcessing : DeviceStatusState object NotSignedIn : DeviceStatusState object NoDeviceSelected : DeviceStatusState object SignInError : DeviceStatusState data class Success(val deviceStatus: DeviceStatus) : DeviceStatusState data class Error(val icon: ImageVector, val message: String, val retryAction: () -> Unit) : DeviceStatusState }
0
Kotlin
0
0
ce66d52e62a6c2c19fb6513820dad956ffdcaa0c
553
zTemp
Apache License 2.0
app/src/main/java/com/cyberwalker/fashionstore/splash/SplashViewModel.kt
cyph3rcod3r
535,256,550
false
null
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cyberwalker.fashionstore.splash import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor(savedStateHandle: SavedStateHandle) : ViewModel() { var uiState by mutableStateOf(SplashUiState()) private set } data class SplashUiState( val loadComplete: Boolean = false )
0
null
8
87
90a375503c0e4aa08dac97154f5257101e3a780b
1,303
FashionStore
Apache License 2.0
app/src/main/java/com/camven/test/MainActivity.kt
Camwly
598,459,544
false
null
package com.camven.test import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.camven.test.databinding.ActivityMainBinding import com.camven.test.view.requestlayout.TestRequestLayoutActivity class MainActivity : AppCompatActivity() { private var binding: ActivityMainBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding?.root) binding?.tvRequestLayout?.setOnClickListener { val intent = Intent(this, TestRequestLayoutActivity::class.java) startActivity(intent) } } }
0
Kotlin
0
0
f681a0f3ba998d4714b1ee967f4dcf2a45776bcb
756
test
Apache License 2.0
common/src/main/kotlin/net/spaceeye/vmod/toolgun/serverSettings/ServerSettingsTypes.kt
SuperSpaceEye
751,999,893
false
{"Kotlin": 721124, "Java": 16898}
package net.spaceeye.vmod.toolgun.serverSettings import net.spaceeye.vmod.toolgun.modes.GUIBuilder import net.spaceeye.vmod.toolgun.serverSettings.modes.DimensionalGravitySettings import net.spaceeye.vmod.toolgun.serverSettings.modes.ServerLimitsSettings import net.spaceeye.vmod.utils.Registry import net.spaceeye.vmod.utils.RegistryObject interface ServerSettingsGUIBuilder: GUIBuilder, RegistryObject object ServerSettingsTypes: Registry<ServerSettingsGUIBuilder>() { init { register(::ServerLimitsSettings) register(::DimensionalGravitySettings) } }
2
Kotlin
8
5
dfdf5b8807350284d1b1169e0b408b47ebe08d73
580
VMod
MIT License
app/src/main/java/blue/aodev/animeultimetv/presentation/screen/episodes/EpisodesFragment.kt
esnaultdev
94,973,529
false
null
package blue.aodev.animeultimetv.presentation.screen.episodes import android.os.Bundle import android.support.v17.leanback.app.VerticalGridFragment import android.support.v17.leanback.widget.ArrayObjectAdapter import android.support.v17.leanback.widget.FocusHighlight import android.support.v17.leanback.widget.OnItemViewClickedListener import android.support.v17.leanback.widget.Presenter import android.support.v17.leanback.widget.Row import android.support.v17.leanback.widget.RowPresenter import android.support.v17.leanback.widget.VerticalGridPresenter import blue.aodev.animeultimetv.domain.AnimeRepository import blue.aodev.animeultimetv.domain.model.Anime import blue.aodev.animeultimetv.domain.model.AnimeSummary import blue.aodev.animeultimetv.domain.model.Episode import blue.aodev.animeultimetv.utils.extensions.fromBgToUi import blue.aodev.animeultimetv.presentation.application.MyApplication import blue.aodev.animeultimetv.presentation.common.EpisodeCardPresenter import blue.aodev.animeultimetv.presentation.screen.playback.PlaybackActivity import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject class EpisodesFragment : VerticalGridFragment() { companion object { private val COLUMNS = 4 private val ZOOM_FACTOR = FocusHighlight.ZOOM_FACTOR_MEDIUM } @Inject lateinit var animeRepository: AnimeRepository private lateinit var episodesAdapter: ArrayObjectAdapter private var anime: Anime? = null val animeSummary: AnimeSummary by lazy { (activity as EpisodesActivity).animeSummary } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MyApplication.graph.inject(this) title = animeSummary.title setupRowAdapter() animeRepository.getAnime(animeSummary.id) .fromBgToUi() .subscribeBy( onNext = { this.anime = it updateEpisodes(it.episodes) } ) } private fun setupRowAdapter() { val gridPresenter = VerticalGridPresenter(ZOOM_FACTOR, false) gridPresenter.numberOfColumns = COLUMNS setGridPresenter(gridPresenter) val cardPresenterSelector = EpisodeCardPresenter(activity) episodesAdapter = ArrayObjectAdapter(cardPresenterSelector) adapter = episodesAdapter onItemViewClickedListener = ItemViewClickedListener() } private fun updateEpisodes(episodes: List<Episode>) { episodesAdapter.clear() episodesAdapter.addAll(0, episodes) } private inner class ItemViewClickedListener : OnItemViewClickedListener { override fun onItemClicked(itemViewHolder: Presenter.ViewHolder, item: Any, rowViewHolder: RowPresenter.ViewHolder?, row: Row?) { if (item is Episode) { anime?.let { anime -> val episodeIndex = anime.episodes.indexOf(item) val intent = PlaybackActivity.getIntent(activity, anime, episodeIndex) activity.startActivityForResult(intent, 0) } } } } }
1
Kotlin
1
1
481bb13907ec07226180290c5dbfc4e96284d950
3,244
AnimeUltimeTv
MIT License
streaming/testUtil/com/android/tools/idea/streaming/emulator/UiSettingsRule.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.streaming.emulator import com.android.adblib.DeviceSelector import com.android.adblib.testing.FakeAdbDeviceServices import com.android.adblib.testing.FakeAdbSession import com.android.ide.common.resources.configuration.LocaleQualifier import com.android.testutils.waitForCondition import com.android.tools.idea.adblib.AdbLibService import com.android.tools.idea.adblib.testing.TestAdbLibService import com.android.tools.idea.res.AppLanguageInfo import com.android.tools.idea.res.AppLanguageService import com.android.tools.idea.testing.ProjectServiceRule import com.android.tools.idea.testing.disposable import com.intellij.testFramework.ProjectRule import org.junit.rules.ExternalResource import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import kotlin.time.Duration.Companion.seconds const val DEFAULT_FONT_SIZE = 100 const val CUSTOM_FONT_SIZE = 130 const val DEFAULT_DENSITY = 480 const val CUSTOM_DENSITY = 560 const val APPLICATION_ID1 = "com.example.test.process1" const val APPLICATION_ID2 = "com.example.test.process2" /** * Supplies fakes for UI settings tests */ class UiSettingsRule : ExternalResource() { private val appLanguageServices = AppLanguageService { listOf( AppLanguageInfo(APPLICATION_ID1, setOf(LocaleQualifier("da"), LocaleQualifier("ru"))), AppLanguageInfo(APPLICATION_ID2, setOf(LocaleQualifier("es")))) } private val projectRule = ProjectRule() private val emulatorRule = FakeEmulatorRule() private val adbServiceRule = ProjectServiceRule(projectRule, AdbLibService::class.java, TestAdbLibService(FakeAdbSession())) private val appServiceRule = ProjectServiceRule(projectRule, AppLanguageService::class.java, appLanguageServices) val project get() = projectRule.project val testRootDisposable get() = projectRule.disposable val adb: FakeAdbDeviceServices get() = AdbLibService.getSession(project).deviceServices as FakeAdbDeviceServices val issuedChangeCommands: List<String> get() = adb.shellV2Requests.map { it.command } val emulator: FakeEmulator by lazy { createAndStartEmulator() } val emulatorDeviceSelector: DeviceSelector by lazy { DeviceSelector.fromSerialNumber(emulator.serialNumber) } val emulatorConfiguration: EmulatorConfiguration by lazy { EmulatorConfiguration.readAvdDefinition(emulator.avdId, emulator.avdFolder)!! } override fun before() { configureAdbShellCommands() } private fun configureAdbShellCommands() = configureUiSettings() fun configureUiSettings( darkMode: Boolean = false, gestureOverlayInstalled: Boolean = true, gestureNavigation: Boolean = false, applicationId: String = APPLICATION_ID1, appLocales: String = "", talkBackInstalled: Boolean = false, talkBackOn: Boolean = false, selectToSpeakOn: Boolean = false, fontSize: Int = DEFAULT_FONT_SIZE, physicalDensity: Int = DEFAULT_DENSITY, overrideDensity: Int = DEFAULT_DENSITY, deviceSelector: DeviceSelector = emulatorDeviceSelector ) { val overrideLine = if (physicalDensity != overrideDensity) "\n Override density: $overrideDensity" else "" val command = POPULATE_COMMAND val response = """ -- Dark Mode -- Night mode: ${if (darkMode) "yes" else "no"} -- Gestures -- ${if (gestureOverlayInstalled) "[${if (gestureNavigation) "x" else " "}] com.android.internal.systemui.navbar.gestural" else ""} -- List Packages -- package:com.google.some.package1 ${if (talkBackInstalled) "package:com.google.android.marvin.talkback" else "package:com.google.some.package2"} package:com.google.some.package3 -- Accessibility Services -- ${formatAccessibilityServices(talkBackOn, selectToSpeakOn)} -- Accessibility Button Targets -- ${formatAccessibilityServices(talkBackOn = false, selectToSpeakOn)} -- Font Size -- ${(fontSize.toFloat() / 100f)} -- Density -- Physical density: $physicalDensity$overrideLine -- Foreground Application -- Proc # 0: fg T/A/TOP LCMNFU t: 0 17132:com.example.test.process1/u0a405 (top-activity) Proc # 0: fg T/A/TOP LCMNFU t: 0 17132:com.example.test.process1/u0a405 (top-activity) """.trimIndent().replace("\n\n", "\n") // trim spaces and remove all empty lines adb.configureShellCommand(deviceSelector, command, response) adb.configureShellCommand(deviceSelector, POPULATE_LANGUAGE_COMMAND.format(applicationId), """ -- App Language -- Locales for $applicationId for user 0 are [$appLocales]" """.trimIndent()) adb.configureShellCommand(deviceSelector, "settings get secure $ENABLED_ACCESSIBILITY_SERVICES", formatAccessibilityServices(talkBackOn, selectToSpeakOn)) adb.configureShellCommand(deviceSelector, "settings get secure $ACCESSIBILITY_BUTTON_TARGETS", formatAccessibilityServices(talkBackOn = false, selectToSpeakOn)) } fun createAndStartEmulator(api: Int = 33): FakeEmulator { val avdFolder = FakeEmulator.createPhoneAvd(emulatorRule.avdRoot, api = api) val emulator = emulatorRule.newEmulator(avdFolder) emulator.start() val emulatorController = getControllerOf(emulator) waitForCondition(5.seconds) { emulatorController.connectionState == EmulatorController.ConnectionState.CONNECTED } return emulator } fun createAndStartWatchEmulator(api: Int = 33): FakeEmulator { val avdFolder = FakeEmulator.createWatchAvd(emulatorRule.avdRoot, api = api) val emulator = emulatorRule.newEmulator(avdFolder) emulator.start() val emulatorController = getControllerOf(emulator) waitForCondition(5.seconds) { emulatorController.connectionState == EmulatorController.ConnectionState.CONNECTED } return emulator } fun getControllerOf(emulator: FakeEmulator): EmulatorController { val catalog = RunningEmulatorCatalog.getInstance() val emulators = catalog.updateNow().get() val emulatorController = emulators.single { emulator.serialNumber == it.emulatorId.serialNumber } return emulatorController } private fun formatAccessibilityServices(talkBackOn: Boolean, selectToSpeakOn: Boolean): String = when { talkBackOn && selectToSpeakOn -> "$TALK_BACK_SERVICE_NAME:$SELECT_TO_SPEAK_SERVICE_NAME" talkBackOn && !selectToSpeakOn -> TALK_BACK_SERVICE_NAME !talkBackOn && selectToSpeakOn -> SELECT_TO_SPEAK_SERVICE_NAME else -> "null" } override fun apply(base: Statement, description: Description): Statement = apply(base, description, projectRule, emulatorRule, adbServiceRule, appServiceRule) private fun apply(base: Statement, description: Description, vararg rules: TestRule): Statement { var statement = super.apply(base, description) rules.reversed().forEach { statement = it.apply(statement, description) } return statement } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
7,569
android
Apache License 2.0
src/main/kotlin/com/vauthenticator/server/password/domain/PasswordEncoder.kt
VAuthenticator
191,632,792
false
{"Kotlin": 594019, "TypeScript": 47216, "HCL": 13254, "Python": 11052, "HTML": 6658, "Shell": 1961, "JavaScript": 1917, "Dockerfile": 1302}
package com.vauthenticator.server.password.domain interface VAuthenticatorPasswordEncoder { fun encode(password: String): String fun matches(password: String, encodedPassword: String): Boolean }
41
Kotlin
1
18
6c7f6cd4820318921a3a08844d063e55f92fca97
206
vauthenticator
Apache License 2.0
app/src/main/java/com/example/submisionawal/ui/detail/DetailViewModel.kt
Pavelmez
802,370,030
false
{"Kotlin": 47962}
package com.example.submisionawal.ui.detail import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.submisionawal.data.response.DetailUserResponse import com.example.submisionawal.data.retrofit.ApiConfig import retrofit2.Call import retrofit2.Callback import retrofit2.Response class DetailViewModel : ViewModel() { private val _detailUser = MutableLiveData<DetailUserResponse>() val detailUser: LiveData<DetailUserResponse> = _detailUser private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> = _isLoading private val apiService = ApiConfig.getApiService() companion object { private const val TAG = "DetailViewModel" } fun getDetailUser(username: String) { _isLoading.postValue(true) apiService.getDetailUser(username).enqueue(object : Callback<DetailUserResponse> { override fun onResponse( call: Call<DetailUserResponse>, response: Response<DetailUserResponse> ) { _isLoading.postValue(false) if (response.isSuccessful) { _detailUser.postValue(response.body()) } else { Log.e(TAG, "onFailure: ${response.message()}") } } override fun onFailure(call: Call<DetailUserResponse>, t: Throwable) { _isLoading.postValue(false) Log.e(TAG, "onFailure: ${t.message}") } }) } }
0
Kotlin
0
0
78a1135b8f698952e12151a37ae8d1787d3aec0a
1,601
Basic-Github-Users
MIT License
firefly-net/src/test/kotlin/com/fireflysource/net/http/client/impl/content/provider/TestFileContentProvider.kt
hypercube1024
3,458,429
false
{"PowerShell": 2, "Maven POM": 8, "Ignore List": 3, "Text": 3, "YAML": 2, "Markdown": 1, "Java": 498, "Kotlin": 183, "INI": 3, "Shell": 2, "XML": 6, "CMake": 1, "C++": 3, "C": 1, "HTML": 2}
package com.fireflysource.net.http.client.impl.content.provider import com.fireflysource.common.io.BufferUtils import com.fireflysource.common.io.openFileChannelAsync import com.fireflysource.common.io.useAwait import com.fireflysource.common.io.writeAwait import com.fireflysource.net.http.client.HttpClientContentProviderFactory.fileBody import kotlinx.coroutines.future.await import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption.READ import java.nio.file.StandardOpenOption.WRITE import java.util.* class TestFileContentProvider { private val tmpFile = Paths.get(System.getProperty("user.home"), "tmpFile${UUID.randomUUID()}.txt") @BeforeEach fun init() { Files.createFile(tmpFile) println("create file: $tmpFile") } @AfterEach fun destroy() { Files.delete(tmpFile) println("delete file: $tmpFile") } @Test @DisplayName("should read file successfully") fun test(): Unit = runBlocking { val capacity = 24 val fileChannel = openFileChannelAsync(tmpFile, WRITE).await() fileChannel.useAwait { val writeBuffer = BufferUtils.allocate(capacity) val writePos = BufferUtils.flipToFill(writeBuffer) writeBuffer.putInt(1).putInt(2).putInt(3) .putInt(4).putInt(5).putInt(6) BufferUtils.flipToFlush(writeBuffer, writePos) val writeLen = fileChannel.writeAwait(writeBuffer, 0L) assertEquals(capacity, writeLen) } val provider = fileBody(tmpFile, READ) as FileContentProvider val readBuffer = BufferUtils.allocate(capacity) val readPos = BufferUtils.flipToFill(readBuffer) val readLen = provider.read(readBuffer).await() BufferUtils.flipToFlush(readBuffer, readPos) assertEquals(capacity, readLen) (1..6).forEach { i -> assertEquals(i, readBuffer.int) } provider.closeAsync().await() Unit } @Test @DisplayName("should seek position and read file successfully") fun testSeekPosition(): Unit = runBlocking { val capacity = 24 val fileChannel = openFileChannelAsync(tmpFile, WRITE).await() fileChannel.useAwait { val writeBuffer = BufferUtils.allocate(capacity) val writePos = BufferUtils.flipToFill(writeBuffer) writeBuffer.putInt(1).putInt(2).putInt(3) .putInt(4).putInt(5).putInt(6) BufferUtils.flipToFlush(writeBuffer, writePos) val writeLen = fileChannel.writeAwait(writeBuffer, 0L) assertEquals(capacity, writeLen) } val pos: Long = 2 * 4 val length = capacity - pos val provider = fileBody(tmpFile, setOf(READ), pos, length) as FileContentProvider val readBuffer = BufferUtils.allocate(capacity) val readPos = BufferUtils.flipToFill(readBuffer) val readLen = provider.read(readBuffer).await() BufferUtils.flipToFlush(readBuffer, readPos) assertEquals(length, readLen.toLong()) (3..6).forEach { i -> assertEquals(i, readBuffer.int) } provider.closeAsync().await() Unit } }
1
Java
112
295
e4774ba7726a08afbe97a7ee8d7343bc9df671de
3,495
firefly
Apache License 2.0
push-sdk/meteor/src/main/java/com/wuhaowen/meteor/thread/Task.kt
wuhaowen
164,527,240
false
{"Java": 98735, "Kotlin": 39339, "Go": 8726}
package com.wuhaowen.meteor.thread enum class TaskPriority { LOW, MEDIUM, HIGH } interface Task : Comparable<Task>{ var priority: TaskPriority override fun compareTo(other: Task): Int = this.priority.ordinal - other.priority.ordinal }
1
null
1
1
ac535779cf979efdc2ce3269fd556e3ec29dfc71
258
chatterbox
MIT License
plugins/api/src/main/kotlin/org/rsmod/plugins/api/cache/map/xtea/XteaFileLoader.kt
rsmod
293,875,986
false
null
package org.rsmod.plugins.api.cache.map.xtea import com.fasterxml.jackson.databind.ObjectMapper import com.github.michaelbull.logging.InlineLogger import org.openrs2.crypto.XteaKey import org.rsmod.game.config.GameConfig import org.rsmod.json.Json import java.nio.file.Files import javax.inject.Inject private val logger = InlineLogger() private const val FILE_NAME = "xteas.json" class XteaFileLoader @Inject constructor( @Json private val mapper: ObjectMapper, private val config: GameConfig, private val repository: XteaRepository ) { fun load() { val file = config.cachePath.resolve(FILE_NAME) Files.newBufferedReader(file).use { val fileXtea = mapper.readValue(it, Array<FileXtea>::class.java) fileXtea.forEach { xtea -> repository[xtea.mapSquare] = XteaKey.fromIntArray(xtea.key) } logger.info { "Loaded ${fileXtea.size} map XTEA keys." } } } }
0
Kotlin
49
55
5293efb07c833715f9bd9df4cad6ff9aa68143da
964
rsmod
ISC License
src/me/anno/utils/test/structures/FloatArray2D.kt
AntonioNoack
266,471,164
false
null
package me.anno.utils.test.structures import me.anno.ecs.components.mesh.Mesh import me.anno.io.Saveable import me.anno.io.text.TextReader import me.anno.io.text.TextWriter import org.apache.logging.log4j.LogManager fun main() { val logger = LogManager.getLogger("FloatArray2D") val writer = TextWriter() writer.writeFloatArray2D("x", Array(5) { FloatArray(5) { if (it < 3) it.toFloat() else 0f } }) logger.info(writer.data.toString()) val reader = TextReader(writer.data.toString()) reader.readProperty(object : Saveable() { override fun readFloatArray2D(name: String, values: Array<FloatArray>) { logger.info( "$name: ${ values.joinToString(",", "[", "]") { fa -> fa.joinToString(",", "[", "]") { it.toInt().toString() } } }" ) } override fun isDefaultValue(): Boolean = false override val approxSize: Int = -1 override val className: String = "" }) val mesh = Mesh() mesh.positions = FloatArray(18) { it.toFloat() % 5f } mesh.indices = IntArray(10) { it } logger.info(TextWriter.toText(mesh)) }
0
Kotlin
1
8
e5f0bb17202552fa26c87c230e31fa44cd3dd5c6
1,211
RemsStudio
Apache License 2.0
src/main/kotlin/dev/stromland/jsonschema/module/kotlin/KotlinJacksonModule.kt
stromland
244,131,317
false
null
package dev.stromland.jsonschema.module.kotlin import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.introspect.AnnotatedConstructor import com.fasterxml.jackson.databind.introspect.AnnotatedParameter import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.github.victools.jsonschema.generator.FieldScope import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder import com.github.victools.jsonschema.module.jackson.JacksonModule import dev.stromland.jsonschema.module.kotlin.resolvers.TypeMetadataRegister import kotlin.reflect.jvm.kotlinProperty data class KotlinJacksonModuleConfig( val disableRequired: Boolean = false, val disableDefaultValue: Boolean = false, val disableNullable: Boolean = false ) /** * Module for jsonschema-generator. Takes advantage of Kotlin data classes. * Given a data class this module can add the following information to json schema: * - Default values. * - Nullable type. * - Required properties. Required when a field is not nullable or doesn't have a default value. * * @param typeMetadataRegister register for resolving types. */ class KotlinJacksonModule( val config: KotlinJacksonModuleConfig = KotlinJacksonModuleConfig(), val typeMetadataRegister: TypeMetadataRegister = TypeMetadataRegister() ) : JacksonModule() { private var mapper = jacksonObjectMapper() override fun applyToConfigBuilder(builder: SchemaGeneratorConfigBuilder) { super.applyToConfigBuilder(builder) mapper = builder.objectMapper .registerKotlinModule() .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) builder.forFields().also { if (!config.disableRequired) it.withRequiredCheck(this::resolveRequiredCheck) if (!config.disableDefaultValue) it.withDefaultResolver(this::resolveDefault) if (!config.disableNullable) it.withNullableCheck(this::resolveNullable) } } private fun resolveRequiredCheck(field: FieldScope): Boolean { return field.isRequired() } private fun resolveDefault(field: FieldScope): Any? { val kProperty = field.rawMember.kotlinProperty ?: return null return typeMetadataRegister.getDefaultValue(field.member.declaringType.erasedType, kProperty) } private fun resolveNullable(field: FieldScope): Boolean { val type = field.rawMember.kotlinProperty return type?.returnType?.isMarkedNullable ?: false } /** * EXTENSION FUNCTIONS */ private fun FieldScope.getAnnotatedParameter(): AnnotatedParameter? { val constructor = this.getAnnotatedConstructor() val index = constructor?.annotated?.parameters?.indexOfFirst { it.name == this.name } ?: return null if (index == -1) { return null } return constructor.getParameter(index) } private fun FieldScope.getAnnotatedConstructor(): AnnotatedConstructor? { val bean = getBeanDescriptionForClass(this.member.declaringType) return bean.constructors.takeIf { it.size > 0 }?.first() } private fun FieldScope.isRequired(): Boolean { val annotatedParameter = this.getAnnotatedParameter() ?: return false return mapper.serializationConfig.annotationIntrospector.hasRequiredMarker(annotatedParameter) } }
0
Kotlin
0
0
31d1fd5eb1172bb9392f2354b5ba2693baa93ccf
3,539
jsonschema-module-jackson-kotlin
Apache License 2.0
src/feature/details/src/commonMain/kotlin/com/gabrielbmoro/moviedb/details/ui/widgets/GenresCard.kt
gabrielbmoro
574,746,759
false
null
package com.gabrielbmoro.moviedb.details.ui.widgets import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @OptIn(ExperimentalLayoutApi::class) @Composable fun GenresCard( genres: List<String>, modifier: Modifier = Modifier ) { FlowRow( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp), maxItemsInEachRow = 4 ) { var i = 0 while (i < genres.size) { val genre = genres[i] Card( shape = CircleShape, modifier = Modifier.padding(vertical = 4.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondary) ) { Text( text = genre, style = MaterialTheme.typography.labelLarge.copy( color = MaterialTheme.colorScheme.secondaryContainer ), modifier = Modifier.padding( horizontal = 8.dp, vertical = 4.dp ) ) } i++ } } }
9
null
8
62
0ae8c7ae825162eac685513c293aeb0556eb43ea
1,689
MovieDB-App
MIT License
src/main/kotlin/examples/forces/GravitationalAttraction.kt
CuriousNikhil
415,380,983
false
null
package examples.forces import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.input.pointer.pointerMoveFilter import k5 import math.Vector2D import math.constrain import math.divide import math.k5Random import math.magSq import math.plusAssign import math.set import math.setMag import math.sub import math.timesAssign import math.toOffSet import kotlin.math.sqrt import kotlin.random.Random data class Moon(val x: Float, val y: Float, val m: Float) { val position = Vector2D(x, y) val velocity = Vector2D.randomVector() val acceleration = Vector2D(0f, 0f) val mass = m val r = sqrt(mass) * 2 init { velocity *= 10f } fun applyForce(force: Vector2D) { val f = force.divide(mass) acceleration += f } fun update() { velocity += acceleration position += velocity acceleration *= 0f } fun render(drawScope: DrawScope) { drawScope.drawCircle(Color.White, r, position.toOffSet()) } } data class Attractor(val x: Float, val y: Float, val m: Float) { val position = Vector2D(x, y) val mass = m val radius = sqrt(mass) * 2 fun attract(ball: Moon) { val attractorPosition = position.copy() val force = attractorPosition.sub(ball.position) val distanceSq = constrain(force.magSq(), 100f, 1000f) val G = 5 // Universal Gravitational Constant val gPull = G * (mass * ball.mass) / distanceSq force.setMag(gPull) ball.applyForce(force) } fun render(drawScope: DrawScope) { drawScope.drawCircle(Color.Magenta, radius, position.toOffSet()) } } @OptIn(ExperimentalComposeUiApi::class) fun gravitationalPull() = k5 { val moons = List(15) { Moon( k5Random(50, dimensFloat.width.toInt()), k5Random(50, dimensFloat.height.toInt()), Random.nextInt(30, 100).toFloat() ) } val attractor = Attractor(dimensFloat.width / 2, dimensFloat.height / 2, 600f) show( modifier = Modifier.pointerMoveFilter( onMove = { attractor.position.set(Vector2D(it.x, it.y)) false } ) ) { drawScope -> attractor.render(drawScope) for (moon in moons) { moon.update() moon.render(drawScope) attractor.attract(moon) } } }
1
Kotlin
6
99
106deec4165a44c3590c6c9ea335b97d29e54cf5
2,557
k5-compose
Apache License 2.0
src/main/kotlin/su/sonoma/lostriver/Config.kt
saddydead1
837,735,532
false
{"Kotlin": 210174, "Java": 475}
package su.sonoma.fishingmod import net.minecraft.resources.ResourceLocation import net.minecraft.world.item.Item import net.minecraftforge.common.ForgeConfigSpec import net.minecraftforge.eventbus.api.SubscribeEvent import net.minecraftforge.fml.common.Mod.EventBusSubscriber import net.minecraftforge.fml.event.config.ModConfigEvent import net.minecraftforge.registries.ForgeRegistries import java.util.stream.Collectors // An example config class. This is not required, but it's a good idea to have one to keep your config organized. // Demonstrates how to use Forge's config APIs @EventBusSubscriber(modid = Fishingmod.MODID, bus = EventBusSubscriber.Bus.MOD) object Config { private val BUILDER = ForgeConfigSpec.Builder() private val LOG_DIRT_BLOCK: ForgeConfigSpec.BooleanValue = BUILDER .comment("Whether to log the dirt block on common setup") .define("logDirtBlock", true) private val MAGIC_NUMBER: ForgeConfigSpec.IntValue = BUILDER .comment("A magic number") .defineInRange("magicNumber", 42, 0, Int.MAX_VALUE) val MAGIC_NUMBER_INTRODUCTION: ForgeConfigSpec.ConfigValue<String> = BUILDER .comment("What you want the introduction message to be for the magic number") .define("magicNumberIntroduction", "The magic number is... ") // a list of strings that are treated as resource locations for items private val ITEM_STRINGS: ForgeConfigSpec.ConfigValue<List<String>> = BUILDER .comment("A list of items to log on common setup.") .defineListAllowEmpty("items", listOf("minecraft:iron_ingot")) { obj: Any -> validateItemName(obj) } val SPEC: ForgeConfigSpec = BUILDER.build() var logDirtBlock: Boolean = false var magicNumber: Int = 0 var magicNumberIntroduction: String? = null lateinit var items: Set<Item> private fun validateItemName(obj: Any): Boolean { return obj is String && ForgeRegistries.ITEMS.containsKey(ResourceLocation(obj)) } @SubscribeEvent fun onLoad(event: ModConfigEvent?) { logDirtBlock = LOG_DIRT_BLOCK.get() magicNumber = MAGIC_NUMBER.get() magicNumberIntroduction = MAGIC_NUMBER_INTRODUCTION.get() // convert the list of strings into a set of items items = ITEM_STRINGS.get() .mapNotNull { itemName: String -> ForgeRegistries.ITEMS.getValue(ResourceLocation(itemName)) } .toSet() } }
0
Kotlin
0
2
f6579c09f6661bbc244f392871ecbe08f86531c2
2,428
lostriver
MIT License
shared/src/iosMain/kotlin/com/prof18/feedflow/utils/Crashlytics.kt
prof18
600,257,020
false
null
package com.prof18.feedflow.utils import co.touchlab.crashkios.crashlytics.CrashlyticsKotlin import co.touchlab.crashkios.crashlytics.enableCrashlytics import co.touchlab.crashkios.crashlytics.setCrashlyticsUnhandledExceptionHook fun setupCrashlytics() { enableCrashlytics() setCrashlyticsUnhandledExceptionHook() } fun sendCrash() { CrashlyticsKotlin.sendHandledException(Exception("Some exception")) }
0
Kotlin
4
97
e3d2ae617a067c0484d414c34fc4ae87630e3b7a
419
feed-flow
Apache License 2.0
data/src/main/java/ca/bc/gov/data/datasource/remote/model/base/specialauthority/SpecialAuthorityPayload.kt
bcgov
414,797,174
false
{"Kotlin": 1305241, "Java": 582146}
package ca.bc.gov.data.datasource.remote.model.base.specialauthority /** * @author: Created by <NAME> on 24,June,2022 */ data class SpecialAuthorityPayload( val referenceNumber: String? = null, val drugName: String? = null, val effectiveDate: String? = null, val expiryDate: String? = null, val prescriberFirstName: String? = null, val prescriberLastName: String? = null, val requestStatus: String? = null, val requestedDate: String? = null )
7
Kotlin
5
5
8866b6673f902057eb12542c3d86d90cfa60aa65
478
myhealthBC-android
Apache License 2.0
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/MaxNTimeBucket.kt
russelldavis
265,272,636
false
null
// 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.util.indexing.diagnostic import java.util.* /** * Bucket of times with size of at most [sizeLimit]. * The first added time is `firstTime`. * Maintains exact min, max, mean of all added times. * Maintains median of [sizeLimit] max times. */ class MaxNTimeBucket(private val sizeLimit: Int, firstTime: TimeNano) { private val _maxNTimes: PriorityQueue<TimeNano> = PriorityQueue(setOf(firstTime)) private var _count: Long = 1 private var _minTime: TimeNano = firstTime private var _maxTime: TimeNano = firstTime private var _sum: TimeNano = firstTime @Synchronized fun addTime(time: TimeNano) { _maxNTimes += time if (_maxTime < time) _maxTime = time if (_minTime > time) _minTime = time _sum += time _count++ while (_maxNTimes.size > sizeLimit) { _maxNTimes.poll() } } val count: Long @Synchronized get() = _count val totalTime: TimeNano @Synchronized get() = _sum val minTime: TimeNano @Synchronized get() = _minTime val maxTime: TimeNano @Synchronized get() = _maxTime val meanTime: Double @Synchronized get() = _sum.toDouble() / _count val maxNTimes: List<TimeNano> @Synchronized get() = _maxNTimes.toList() }
1
null
1
1
fa602b2874ea4eb59442f9937b952dcb55910b6e
1,346
intellij-community
Apache License 2.0
src/test/kotlin/de/pflugradts/passbird/application/eventhandling/ApplicationEventHandlerTest.kt
christianpflugradt
522,173,174
false
{"Kotlin": 579999}
package de.pflugradts.passbird.application.eventhandling import de.pflugradts.passbird.INTEGRATION import de.pflugradts.passbird.application.UserInterfaceAdapterPort import de.pflugradts.passbird.application.fakeUserInterfaceAdapterPort import de.pflugradts.passbird.domain.model.ddd.DomainEvent import de.pflugradts.passbird.domain.model.egg.createEggForTesting import de.pflugradts.passbird.domain.model.event.EggCreated import de.pflugradts.passbird.domain.model.event.EggMoved import de.pflugradts.passbird.domain.model.event.EggNotFound import de.pflugradts.passbird.domain.model.event.EggRenamed import de.pflugradts.passbird.domain.model.event.EggUpdated import de.pflugradts.passbird.domain.model.shell.EncryptedShell import de.pflugradts.passbird.domain.model.shell.Shell.Companion.shellOf import de.pflugradts.passbird.domain.model.transfer.Output import de.pflugradts.passbird.domain.service.eventhandling.EventHandler import de.pflugradts.passbird.domain.service.password.encryption.CryptoProvider import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import org.junit.jupiter.api.Tag import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import strikt.api.expectThat import strikt.assertions.contains import java.util.stream.Stream @Tag(INTEGRATION) class ApplicationEventHandlerTest { private val cryptoProvider = mockk<CryptoProvider>() private val userInterfaceAdapterPort = mockk<UserInterfaceAdapterPort>() private val applicationEventHandler = ApplicationEventHandler(cryptoProvider, userInterfaceAdapterPort) private var passbirdEventRegistry = PassbirdEventRegistry(mutableSetOf<EventHandler>(applicationEventHandler)) @ParameterizedTest @MethodSource("providePasswordEvents") fun `should process egg events`(domainEvent: DomainEvent) { // given val expectedEggIdShell = shellOf("expected eggId") every { cryptoProvider.decrypt(any(EncryptedShell::class)) } answers { expectedEggIdShell } fakeUserInterfaceAdapterPort(instance = userInterfaceAdapterPort) val outputSlot = slot<Output>() // when passbirdEventRegistry.register(domainEvent) passbirdEventRegistry.processEvents() // then verify { userInterfaceAdapterPort.send(capture(outputSlot)) } expectThat(outputSlot.captured.shell.asString()) contains expectedEggIdShell.asString() } companion object { @JvmStatic private fun providePasswordEvents() = Stream.of( Arguments.of(EggCreated(createEggForTesting())), Arguments.of(EggUpdated(createEggForTesting())), Arguments.of(EggRenamed(createEggForTesting())), Arguments.of(EggMoved(createEggForTesting())), Arguments.of(EggNotFound(shellOf("expected eggId"))), ) } }
1
Kotlin
0
0
8364de9e421c45dd9ae2a8e3cfc70d17efbf714a
2,945
Passbird
Apache License 2.0
app/src/main/java/org/covidwatch/android/presentation/settings/SettingsFragment.kt
generalmotors
279,946,799
true
{"Kotlin": 257493, "Java": 5776}
package org.covidwatch.android.presentation import android.Manifest import android.annotation.SuppressLint import android.bluetooth.BluetoothAdapter import android.content.Context.MODE_PRIVATE import android.content.Intent import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import org.covidwatch.android.R import org.covidwatch.android.databinding.FragmentSettingsBinding import org.covidwatch.android.presentation.settings.SettingsViewModel import org.covidwatch.android.presentation.util.formatContactNumber import org.covidwatch.android.presentation.util.validateContactNumber import org.covidwatch.android.service.ContactTracerService import org.covidwatch.android.util.ButtonUtils import org.koin.androidx.viewmodel.ext.android.viewModel import pub.devrel.easypermissions.AfterPermissionGranted import pub.devrel.easypermissions.AppSettingsDialog import pub.devrel.easypermissions.EasyPermissions private const val LOCATION_PERMISSION = 100 private const val REQUEST_ENABLE_BT = 101 class SettingsFragment : Fragment(), EasyPermissions.PermissionCallbacks { private var _binding: FragmentSettingsBinding? = null private val binding get() = _binding!! private val settingsViewModel: SettingsViewModel by viewModel() lateinit var prefs : SharedPreferences private val bluetoothAdapter: BluetoothAdapter? by lazy { BluetoothAdapter.getDefaultAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentSettingsBinding.inflate(inflater, container, false) return binding.root } @SuppressLint("ClickableViewAccessibility") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) prefs = context?.getSharedPreferences("org.covidwatch.android.PREFERENCE_FILE_KEY",MODE_PRIVATE)!! settingsViewModel.hasLocationPermissionLiveData.observe(viewLifecycleOwner, Observer { val checkedIconId = if (it) R.drawable.ic_check_true else R.drawable.ic_info_red val fillColor = if (it) R.color.maroon_shadow else R.color.accentYellow binding.locationButton.setCompoundDrawablesWithIntrinsicBounds(checkedIconId, 0, 0, 0) binding.locationButton.backgroundTintList = ColorStateList.valueOf(resources.getColor(fillColor)) binding.locationButton.isClickable = !it }) settingsViewModel.isBluetoothEnabledLiveData.observe(viewLifecycleOwner, Observer { val checkedIconId = if (it) R.drawable.ic_check_true else R.drawable.ic_info_red val fillColor = if (it) R.color.maroon_shadow else R.color.accentYellow binding.bluetoothButton.setCompoundDrawablesWithIntrinsicBounds(checkedIconId, 0, 0, 0) binding.bluetoothButton.backgroundTintList = ColorStateList.valueOf(resources.getColor(fillColor)) binding.bluetoothButton.isClickable = !it }) disableButton(binding.saveButton, prefs.getString("contact_number_full","").toString() != "") binding.contactPhoneNumber.text = Editable.Factory.getInstance().newEditable(getPhoneNumber()) binding.saveButton.setOnClickListener { val formattedPhone = formatContactNumber(binding.contactPhoneNumber.text.toString()) if (validateContactNumber(formattedPhone)){ prefs.edit()?.putString("contact_number_full", formattedPhone)?.apply() binding.contactPhoneNumber.setText(formattedPhone) Toast.makeText(context,"Saved!",Toast.LENGTH_LONG).show() } } binding.contactPhoneNumber.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(s: Editable?) { val currentNumber = prefs.getString("contact_number_full","") val currentField = binding.contactPhoneNumber.text.toString() if (validateContactNumber(formatContactNumber(currentField)) && currentField != currentNumber) { enableButton(binding.saveButton) }else if (currentField == currentNumber) { disableButton(binding.saveButton,true) }else { disableButton(binding.saveButton,false) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } }) binding.closeButton.setOnClickListener { findNavController().popBackStack() } binding.locationButton.setOnTouchListener(ButtonUtils.ButtonTouchListener()) binding.bluetoothButton.setOnTouchListener(ButtonUtils.ButtonTouchListener()) } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this) } override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) { if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { AppSettingsDialog.Builder(this).build().show() } settingsViewModel.onLocationPermissionResult() } override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) { settingsViewModel.onLocationPermissionResult() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_ENABLE_BT) { settingsViewModel.onBluetoothResult() } } @AfterPermissionGranted(LOCATION_PERMISSION) fun ensureLocationPermissionIsGranted() { val perms = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) if (EasyPermissions.hasPermissions(requireContext(), *perms)) { return } EasyPermissions.requestPermissions( this, getString(R.string.bluetooth_explanation_subtext), LOCATION_PERMISSION, *perms ) } fun ensureBluetoothIsOn() : Boolean { return if (bluetoothAdapter?.isEnabled == true) { true } else { turnOnBluetooth() } } private fun turnOnBluetooth() : Boolean { val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT) return true } private fun getPhoneNumber() : String { println("TRYING TO GET PHONE NUMBER THROUGH MAIN APP VARIABLE") println(prefs.toString()) return prefs?.getString("contact_number_full","No Contact Number Stored").toString() } private fun enableButton(button : Button) : Button { button.isClickable = true button.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.accentYellow)) button.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0) return button } private fun disableButton(button : Button, valid : Boolean?) : Button { button.isClickable = false button.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.maroon_shadow)) if (valid!!) { button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_true,0,0,0) }else if (!valid){ button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_info_red,0,0,0) } return button } private fun toggleButton(button : Button) : Button { button.isClickable = !button.isClickable if (button.isClickable) { enableButton(button) }else { disableButton(button,null) } return button } }
1
Kotlin
2
1
41c9eefcc48f584a5544f7c92b6fc95e89e11f9c
8,695
covidwatch-android-tcn
Apache License 2.0
src/eu/opendiabetes/gateway/language/info_sheets/english/FollowupParentUsers.kt
OPEN-diabetes
277,939,065
false
null
package eu.opendiabetes.gateway.language.info_sheets.english const val INFO_SHEET_FOLLOWUP_PARENT_NON_USERS = """ <h1>Introduction</h1> <p>The OPEN team invites you to take part in a global study that examines in what way the innovations being developed by the Do-It-Yourself Artificial Pancreas Systems (DIYAPS) community might benefit all people living with diabetes. The following information explains what to expect if you choose to take part in the research. <b>Please read it carefully. If you do not understand some of the information and/or would like to discuss anything related to the project, feel free to contact a member of our research team</b> (see below).</p> <h1>Name of Study</h1> <p>OPEN (Outcomes of Patients’ Evidence with Novel, Do-it-Yourself Artificial Pancreas Technology)</p> <h1>Name of Principal Investigator</h1> <p>Dr <NAME></p> <h1>What is this research about?</h1> <p>A growing number of people living with diabetes are choosing to build DIYAPS to help with the management of their condition. However, more research is needed to understand if and how people living with diabetes benefit from using these systems. The primary aim of this study is to document the difficulties and challenges that people face in building DIYAPS, as well as why some choose not to use DIYAPS.</p> <h1>Why is OPEN doing this research?</h1> <p>By carrying out this research study, OPEN aims to understand the barriers to uptake of DIYAPS solutions.</p> <h1>Why am I being invited to take part?</h1> <p>You have been invited to take part because you are the parent or caretaker of a child that has diabetes and you are a member of the DIYAPS community.</p> <h1>What will happen if we decide to take part in this research study?</h1> <p>If you agree to take part, you will be first given a unique <b>participant ID</b> which will guarantee your anonymity in the survey. The ID allows you to take a break and come back where you have left off at a later stage or login on another device and continue from there. Therefore, <b>please keep it safe by noting it down, e-mailing it to yourself or taking a picture of it as you may need it later</b>.</p></p> <p>You will then be asked to <b>complete some questionnaires</b>. Altogether, it should not take you more than 10–15 minutes. These questionnaires will focus on:</p> <ul> <li>you and your child's demographic information</li> <li>your experiences of being a member of an online DIYAPS community</li> <li>the challenges you may have experienced or anticipate in building a DIYAPS</li> </ul> <p>At the end of the survey, we will ask you if you would like to further assist our research by completing an additional questionnaire regarding your child’s most recent diabetes-related medical history. We will also ask if you would like to sign up for follow-up studies run by OPEN in the future. For this, you can <b>become a member of the OPEN project</b> on a data repository site called ‘<b>Open Humans</b>’. This will allow us to <b>anonymously communicate with you</b> to ask about your participation in future studies as data protection laws do not allow us to obtain or use personal e-mail accounts for communication. <b>Instructions</b> on how to connect your existing Open Humans account — or create a new one and connect this — <b>are provided on the</b> <a href="https://open-diabetes.eu/en/open-survey/survey-tutorials/" target="_blank">OPEN website</a>. Please note that these additional steps are completely optional.</p> <p>Choosing to sign up to Open Humans and joining the OPEN project on Open Humans is <b>optional</b> and you decide if you would like to participate in any further follow-up studies. Bear in mind that your participation in the OPEN project and future studies will greatly assist us to enhance the existing scientific evidence on DIYAPS.</p> <p>If you are happy to sign up to the Open Humans platform, instructions on how to connect your existing Open Humans account — <b>or</b> create a new one and connect this — are provided on the <a href="https://open-diabetes.eu/en/open-survey/survey-tutorials/" target="_blank">OPEN website</a>.</p> <h1>How will the data be used?</h1> <p>The pseudonymized responses to the survey will be analyzed by our team of researchers. Once the OPEN project is completed, your anonymized data will be available to researchers upon request. To protect your privacy, any information that might lead to your identity will be removed from your data set before being accessed by any researchers.</p> <p>The organizations in the OPEN consortium involved in accessing your data will include:</p> <ul> <li>University College Dublin, Ireland</li> <li>Charité – Universitätsmedizin Berlin, Germany</li> <li>Dedoc Labs GmbH, Germany</li> <li>Steno Diabetes Center Copenhagen, Denmark</li> <li>Copenhagen University, Denmark</li> <li>The Australian Centre for Behavioural Research in Diabetes (ACBRD), Australia</li> </ul> <h1>How is your privacy protected?</h1> <p>The design of this study is in line with all EU (GDPR), Irish (Data Protection Act, 2018) and UCD (UCD ethics Committee) ethical and data protection regulations. Every precaution will be taken to respect your privacy, in line with the General Data Protection Regulations (GDPR).</p> <p>As stated above, any information that you share that may potentially inadvertently make you identifiable will be removed — this process is called pseudonymization.</p> <p>Please note that only adults (aged 18+) who are able to provide consent are allowed to participate.</p> <h1>What are the benefits of taking part in this research study?</h1> <p>There are no direct, material benefits expected from taking part in this study. However, you will be helping to improve the overall scientific knowledge about DIYAPS systems and its use. As a consequence, your participation and experience may help the diabetes community.</p> <h1>What are the risks of taking part in this research study?</h1> <p>There are no anticipated risks expected from taking part in this study. However, if you do experience any aspect of the study as distressing, you are free to stop participating at any time, without personal consequence, and we recommend contacting your GP/primary care physician or local diabetes organizations who may be able to provide you with psychological and practical support. However, if they are not in a position to provide support, you may find information on the following webpages helpful:</p> <ul> <li><a href="https://acbrd.org.au/diabetes-and-emotional-health-factsheets/" target="_blank">Diabetes and emotional health factsheets</a></li> <li><a href="https://www.jdrf.org/t1d-resources/living-with-t1d/mental-health/" target="_blank">Mental Health</a></li> </ul> <p>If you choose to provide detailed personal information in a free text field, there is a small chance that you may identify yourself or your child within the questionnaire to OPEN researchers. However, this information will be removed before the data set is shared with the rest of the OPEN research team.</p> <h1>Can I change my mind at any stage and withdraw from the study?</h1> <p>Yes! If you decide to participate and subsequently change your mind, you may withdraw from the study at any time. You may also choose to remove your data from future analyses of the OPEN project. To do so, please contact our research team through the details provided below. You can also have the option to leave the OPEN project on Open Humans at any time and remove any data that you have uploaded to the platform. Please note that in both instances we can only delete your data if you provide your Participant ID from the survey.</p> <h1>How will I find out what happens with this project?</h1> <p>The OPEN team would like you to engage with this project as much as possible. That is why we have developed a website for the OPEN project. On <a href="https://open-diabetes.eu">this website</a>, we provide regular updates on the findings of our project, and you may also sign up to our newsletter to receive regular e-mail updates. All the results of our research will be published in a way which will be accessible and free of charge to the public.</p> <h1>Contact Details</h1> <p>If any participant or participant’s caregiver would like to contact a member of the research team for any research-related reason, they can do so via the contact information below. If any questions are not answered in a satisfactory manner, then contact can be made with a Data Protection Officer at UCD, the details of which are also provided below. For general data protection inquiries, please contact the UCD Data Protection office. Finally, if none of the UCD contacts have given a satisfactory response, details on the Data Protection Commission are provided below.</p> <div id="contact-details"> <div class="contact-detail"> <span><b>Dr <NAME></b></span> <span>Project Coordinator</span> <span>School of Sociology</span> <span>Newman Building</span> <span>University College Dublin</span> <span>Belfield,</span> <span>Dublin 4</span> <span>Telephone: <a href="tel:+35317167019">+353 1 716 7019</a></span> <span>Email: <a href="mailto:<EMAIL>"><EMAIL></a></span> </div> <div class="contact-detail"> <span><b>Dr. med. <NAME></b></span> <span><b>Prof. Dr. med. <NAME></b></span> <span>Clinical Leads</span> <span>Department of Paediatric Endocrinology and Diabetes</span> <span>Charité – Universitätsmedizin Berlin</span> <span>Augustenburger Platz 1</span> <span>13353 Berlin</span> <span>Germany</span> <span>Telephone: <a href="tel:+4930450616454">+49 30 450 616454</a></span> <span>Email: <a href="mailto:<EMAIL>"><EMAIL></a></span> </div> <div class="contact-detail"> <span><b>UCD Data Protection General Enquiries</b></span> <span><NAME></span> <span>University College Dublin</span> <span>Belfield, Dublin 4. Ireland</span> <span>Telephone: <a href="tel:+3537168786">+353 716 8786</a></span> <span>Email: <a href="mailto:<EMAIL>"><EMAIL></a></span> </div> <div class="contact-detail"> <span><b>Data Protection Commission</b></span> <span>21 Fitzwilliam Square South,</span> <span>Dublin 2</span> <span>D02 RD28</span> <span>Telephone: <a href="tel:+353 1 578 684 800">+353 1 578 684 800</a></span> <span>Website: <a href="https://forms.dataprotection.ie/contact" target="_blank">https://forms.dataprotection.ie/contact</a></span> </div> </div> <p><b>Thank you very much for your time and willingness to help us to research this subject!</b></p> <p><b>The OPEN team</b></p> <h1>PARTICIPANT CONSENT FORM</h1> <p>I have read this consent form. I understand that I can refuse to participate in this project. I have taken time to think carefully about my decision to participate. I freely consent to share my data with this research project.</p> <p>By clicking "agree" below, you are e-signing this form and agree to the following:</p> <ul> <li>I understand the uncertainty and risk of research as stated in this consent form.</li> <li>I understand that data I choose to share may be used for any purpose, including research purposes.</li> <li>I understand that once I authorize data sharing, data privacy laws might not apply or no longer protect my information.</li> <li>I understand that I can withdraw data from the study at any time, but copies of that data that have already been made by other people may remain.</li> </ul> """
0
Kotlin
0
1
057ae04453639368cf9a038604b7a3865e2b3ddc
11,681
Gateway
MIT License
waltid-services/waltid-e2e-tests/src/test/kotlin/LspPotentialWallet.kt
walt-id
701,058,624
false
null
import id.walt.commons.interop.LspPotentialInterop import id.walt.credentials.vc.vcs.W3CVC import id.walt.crypto.keys.KeyGenerationRequest import id.walt.crypto.keys.KeySerialization import id.walt.crypto.keys.KeyType import id.walt.crypto.keys.jwk.JWKKey import id.walt.crypto.utils.JsonUtils.toJsonElement import id.walt.issuer.issuance.IssuanceExamples import id.walt.issuer.issuance.IssuanceRequest import id.walt.issuer.issuance.createCredentialOfferUri import id.walt.issuer.lspPotential.LspPotentialIssuanceInterop import id.walt.oid4vc.data.AuthenticationMethod import id.walt.oid4vc.data.CredentialFormat import id.walt.oid4vc.data.CredentialOffer import id.walt.oid4vc.data.OpenIDProviderMetadata import id.walt.oid4vc.data.dif.VCFormat import id.walt.oid4vc.requests.AuthorizationRequest import id.walt.verifier.lspPotential.LspPotentialVerificationInterop import id.walt.webwallet.db.models.WalletCredential import id.walt.webwallet.db.models.WalletDid import id.walt.webwallet.web.controllers.UsePresentationRequest import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.util.* import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.* import kotlinx.uuid.UUID import kotlin.test.assertContains import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertNotNull class LspPotentialWallet(val client: HttpClient, val walletId: String) { private var issuedMdocId: String = "" private var issuedSDJwtVCId: String = "" private lateinit var generatedKeyId: String private lateinit var generatedDid: String init { // === create EC256 key and DID:JWK (did is not necessarily required, but currently needed for wallet initialization) === val keysApi = KeysApi(client) runBlocking { keysApi.generate(UUID(walletId), KeyGenerationRequest(keyType = KeyType.secp256r1)) { generatedKeyId = it } DidsApi(client).create(UUID(walletId), DidsApi.DidCreateRequest("jwk", keyId = generatedKeyId)) { generatedDid = it } } } suspend fun testMDocIssuance() = E2ETestWebService.test("test mdoc issuance") { // === get credential offer from test issuer API === val issuanceReq = Json.decodeFromString<IssuanceRequest>(IssuanceExamples.mDLCredentialIssuanceData).copy( authenticationMethod = AuthenticationMethod.PRE_AUTHORIZED ) val offerResp = client.post("/openid4vc/sdjwt/issue") { contentType(ContentType.Application.Json) setBody(Json.encodeToJsonElement(issuanceReq).toString()) } assert(offerResp.status == HttpStatusCode.OK) val offerUri = offerResp.bodyAsText() // === resolve credential offer === val resolvedOffer = client.post("/wallet-api/wallet/$walletId/exchange/resolveCredentialOffer") { setBody(offerUri) }.expectSuccess().body<CredentialOffer>() assertEquals(1, resolvedOffer.credentialConfigurationIds.size) assertEquals("org.iso.18013.5.1.mDL", resolvedOffer.credentialConfigurationIds.first()) // === resolve issuer metadata === val issuerMetadata = client.get("${resolvedOffer.credentialIssuer}/.well-known/openid-credential-issuer").expectSuccess().let { it.body<OpenIDProviderMetadata>() } assertEquals(issuerMetadata.issuer, resolvedOffer.credentialIssuer) assertContains(issuerMetadata.credentialConfigurationsSupported!!.keys, resolvedOffer.credentialConfigurationIds.first()) // === use credential offer request === val issuedCred = client.post("/wallet-api/wallet/$walletId/exchange/useOfferRequest?did=$generatedDid") { setBody(offerUri) }.expectSuccess().body<List<WalletCredential>>().first() assertEquals(CredentialFormat.mso_mdoc, issuedCred.format) // === get issued credential from wallet-api val fetchedCredential = client.get("/wallet-api/wallet/$walletId/credentials/${issuedCred.id}") .expectSuccess().body<WalletCredential>() assertEquals(issuedCred.format, fetchedCredential.format) runBlocking { issuedMdocId = fetchedCredential.id } } suspend fun testMdocPresentation() = E2ETestWebService.test("test mdoc presentation") { val createReqResponse = client.post("/openid4vc/verify") { header("authorizeBaseUrl", "mdoc-openid4vp://") header("responseMode", "direct_post_jwt") contentType(ContentType.Application.Json) setBody( buildJsonObject { put("request_credentials", JsonArray(listOf(JsonPrimitive("org.iso.18013.5.1.mDL")))) put("trusted_root_cas", JsonArray(listOf(JsonPrimitive(LspPotentialInterop.POTENTIAL_ROOT_CA_CERT)))) }) } assertEquals(200, createReqResponse.status.value) val presReqUrl = createReqResponse.bodyAsText() // === resolve presentation request === val parsedRequest = client.post("/wallet-api/wallet/$walletId/exchange/resolvePresentationRequest") { setBody(presReqUrl) }.expectSuccess().let { response -> response.body<String>().let { AuthorizationRequest.fromHttpParameters(parseQueryString(Url(it).encodedQuery).toMap()) } } assertNotNull(parsedRequest.presentationDefinition) // === find matching credential === val matchingCreds = client.post("/wallet-api/wallet/$walletId/exchange/matchCredentialsForPresentationDefinition") { setBody(parsedRequest.presentationDefinition!!) }.expectSuccess().let { response -> response.body<List<WalletCredential>>()} assertNotEquals(0, matchingCreds.size) client.post("/wallet-api/wallet/$walletId/exchange/usePresentationRequest") { setBody(UsePresentationRequest(generatedDid, presReqUrl, listOf(issuedMdocId))) }.expectSuccess() } suspend fun testSDJwtVCIssuance() = E2ETestWebService.test("test sd-jwt-vc issuance") { // === get credential offer from test issuer API === val issuanceReq = IssuanceRequest( Json.parseToJsonElement(KeySerialization.serializeKey(LspPotentialIssuanceInterop.POTENTIAL_ISSUER_JWK_KEY)).jsonObject, "", "identity_credential_vc+sd-jwt", credentialData = W3CVC(buildJsonObject { put("family_name", "Doe") put("given_name", "John") }), null, x5Chain = listOf(LspPotentialInterop.POTENTIAL_ISSUER_CERT), trustedRootCAs = listOf(LspPotentialInterop.POTENTIAL_ROOT_CA_CERT) ) val offerResp = client.post("/openid4vc/sdjwt/issue") { contentType(ContentType.Application.Json) setBody(Json.encodeToJsonElement(issuanceReq).toString()) } assert(offerResp.status == HttpStatusCode.OK) val offerUri = offerResp.bodyAsText() // === resolve credential offer === val resolvedOffer = client.post("/wallet-api/wallet/$walletId/exchange/resolveCredentialOffer") { setBody(offerUri) }.expectSuccess().let { it.body<CredentialOffer>() } assertEquals(1, resolvedOffer.credentialConfigurationIds.size) assertEquals("identity_credential_vc+sd-jwt", resolvedOffer.credentialConfigurationIds.first()) // === resolve issuer metadata === val issuerMetadata = client.get("${resolvedOffer.credentialIssuer}/.well-known/openid-credential-issuer").expectSuccess().let { it.body<OpenIDProviderMetadata>() } assertEquals(issuerMetadata.issuer, resolvedOffer.credentialIssuer) assertContains(issuerMetadata.credentialConfigurationsSupported!!.keys, resolvedOffer.credentialConfigurationIds.first()) // === use credential offer request === val issuedCred = client.post("/wallet-api/wallet/$walletId/exchange/useOfferRequest?did=$generatedDid") { setBody(offerUri) }.expectSuccess().body<List<WalletCredential>>().first() assertEquals(CredentialFormat.sd_jwt_vc, issuedCred.format) // === get issued credential from wallet-api val fetchedCredential = client.get("/wallet-api/wallet/$walletId/credentials/${issuedCred.id}") .expectSuccess().body<WalletCredential>() assertEquals(issuedCred.format, fetchedCredential.format) runBlocking { issuedSDJwtVCId = fetchedCredential.id } } suspend fun testSDJwtPresentation() = E2ETestWebService.test("test sd-jwt-vc presentation") { val createReqResponse = client.post("/openid4vc/verify") { header("authorizeBaseUrl", "openid4vp://") header("openId4VPProfile","HAIP") header("responseMode", "direct_post") contentType(ContentType.Application.Json) setBody( buildJsonObject { put("request_credentials", JsonArray(listOf(JsonPrimitive("identity_credential_vc+sd-jwt")))) }) } assertEquals(200, createReqResponse.status.value) val presReqUrl = createReqResponse.bodyAsText() // === resolve presentation request === val parsedRequest = client.post("/wallet-api/wallet/$walletId/exchange/resolvePresentationRequest") { setBody(presReqUrl) }.expectSuccess().let { response -> response.body<String>().let { AuthorizationRequest.fromHttpParameters(parseQueryString(Url(it).encodedQuery).toMap()) } } assertNotNull(parsedRequest.presentationDefinition) // === find matching credential === val matchingCreds = client.post("/wallet-api/wallet/$walletId/exchange/matchCredentialsForPresentationDefinition") { setBody(parsedRequest.presentationDefinition!!) }.expectSuccess().let { response -> response.body<List<WalletCredential>>()} assertNotEquals(0, matchingCreds.size) client.post("/wallet-api/wallet/$walletId/exchange/usePresentationRequest") { setBody(UsePresentationRequest(generatedDid, presReqUrl, listOf(issuedSDJwtVCId))) }.expectSuccess() } }
43
null
42
116
0bcb9e1efe911b4445535ca1531a56b7a52c472c
9,663
waltid-identity
Apache License 2.0
app/src/main/java/com/yechaoa/wanandroid_jetpack/ui/main/navi/NaviRepository.kt
yechaoa
335,943,073
false
null
package com.yechaoa.wanandroid_jetpack.ui.main.navi import com.yechaoa.wanandroid_jetpack.base.BaseRepository /** * Created by yechaoa on 2021/2/8. * Describe : */ class NaviRepository : BaseRepository() { suspend fun getNavi() = apiService().getNavi().data() }
0
Kotlin
9
81
f46b9f25ec4c7ae0ef6d9bbacfeccf3dbbf7d522
272
wanandroid_jetpack
Apache License 2.0