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
integration-tests/devtools/src/test/resources/__snapshots__/RESTClientCodestartTest/testContent/src_main_kotlin_ilove_quark_us_MyRemoteService.kt
loicmathieu
187,598,844
false
null
package ilove.quark.us import org.eclipse.microprofile.rest.client.inject.RegisterRestClient import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.QueryParam /** * To use it via injection. * * {@code * @Inject * @RestClient * lateinit var myRemoteService: MyRemoteService * * fun doSomething() { * val restClientExtensions = myRemoteService.getExtensionsById("io.quarkus:quarkus-rest-client") * } * } */ @RegisterRestClient(baseUri = "https://stage.code.quarkus.io/api") interface MyRemoteService { @GET @Path("/extensions") fun getExtensionsById(@QueryParam("id") id: String): Set<Extension> data class Extension(val id: String, val name: String, val shortName: String, val keywords: List<String>) }
15
null
1
3
f29b28887af4b50e7484dd1faf252b15f1a9f61a
773
quarkus
Apache License 2.0
buildSrc/src/main/kotlin/com/luggsoft/codegen/generators/TupleCodeGenerator.kt
dan-lugg
403,679,356
false
{"Kotlin": 79335}
package com.luggsoft.codegen.generators import com.luggsoft.codegen.util.toTypes internal class TupleCodeGenerator( override val path: String, override val permutations: Int, ) : CodeGeneratorBase() { override fun generateCode(appendable: Appendable) { appendable.appendLine("@file:Suppress(\"PackageDirectoryMismatch\")") appendable.appendLine() appendable.appendLine("package com.luggsoft.common") appendable.appendLine() (1..this.permutations).forEach { x -> appendable.appendLine("/**") appendable.appendLine(" * Represents a tuple of $x value(s).") appendable.appendLine(" *") appendable.appendLine(" * [https://en.wikipedia.org/wiki/Tuple]") appendable.appendLine(" */") appendable.appendLine("data class Tuple$x<${(1..x).toTypes()}>(") (1..x).forEach { y -> appendable.appendLine(" val p$y: T$y,") } appendable.appendLine(")") appendable.appendLine("{") if (x < this.permutations) { appendable.appendLine(" /**") appendable.appendLine(" * Returns a new [Tuple$x] with [value] as the last value.") appendable.appendLine(" *") appendable.appendLine(" * @param value The value to include in the new [Tuple$x]") appendable.appendLine(" */") appendable.appendLine(" operator fun <T> plus(value: T) = Tuple${x + 1}(${(1..x).joinToString { i -> "this.p$i" }}, value)") appendable.appendLine() } appendable.appendLine(" /**") appendable.appendLine(" * Returns the tuple value(s) as a list.") appendable.appendLine(" *") appendable.appendLine(" * @see [List]") appendable.appendLine(" */") appendable.appendLine(" fun toList() = listOf(${(1..x).joinToString { i -> "this.p$i" }})") appendable.appendLine("}") appendable.appendLine() appendable.appendLine("/**") appendable.appendLine(" * Invokes [this] with positional arguments from [Tuple$x].") appendable.appendLine(" */") appendable.appendLine("fun <${(1..x).toTypes()}, R> ((${(1..x).toTypes()}) -> R).invokeWithTuple(tuple$x: Tuple$x<${(1..x).toTypes()}>) = this.invoke(${(1..x).joinToString { i -> "tuple$x.p$i" }})") appendable.appendLine() } } }
0
Kotlin
0
0
302dab250706204e91a998c31b70fe411eb28296
2,560
kt-common
MIT License
domain/src/main/java/com/mynimef/domain/AppRepository.kt
MYnimef
637,497,996
false
{"Kotlin": 266286}
package com.mynimef.domain import com.mynimef.domain.models.AccountModel import com.mynimef.domain.models.EAppState import com.mynimef.domain.models.ERole class AppRepository( private val storageRoot: IAppStorageRoot, private val networkRoot: IAppNetworkRoot ) { fun getAppState() = storageRoot.getAppState() fun getActualAccountId() = storageRoot.getActualAccountId() val storage: IAppStorage = storageRoot val network: IAppNetwork = networkRoot suspend fun signIn(account: AccountModel) { storageRoot.insertAccount(account) setState(when (account.role) { ERole.CLIENT -> EAppState.CLIENT ERole.TRAINER -> EAppState.TRAINER }) } suspend fun signOutClient(accountId: Long) { storageRoot.deleteAllCards() storageRoot.deleteAccount(accountId) storageRoot.deleteClient(accountId) networkRoot.removeAccessToken() setState(EAppState.AUTH) } suspend fun signOutTrainer(accountId: Long) { storageRoot.deleteAllCards() storageRoot.deleteAccount(accountId) networkRoot.removeAccessToken() setState(EAppState.AUTH) } private suspend fun setState(state: EAppState) { storageRoot.setAppState(state) } }
0
Kotlin
1
0
7980d53f3605bbca6d89af6113297a89f5bf057e
1,288
FoodMood-Android
MIT License
app/src/main/java/xyz/teamgravity/dictionary/data/remote/dto/DefinitionDto.kt
raheemadamboev
466,416,651
false
{"Kotlin": 24032}
package xyz.teamgravity.dictionary.data.remote.dto import com.google.gson.annotations.SerializedName import xyz.teamgravity.dictionary.domain.model.DefinitionModel data class DefinitionDto( @SerializedName("antonyms") val antonyms: List<String>, @SerializedName("definition") val definition: String, @SerializedName("example") val example: String?, @SerializedName("synonyms") val synonyms: List<String> ) { fun toDefinitionModel(): DefinitionModel { return DefinitionModel( antonyms = antonyms, definition = definition, example = example, synonyms = synonyms ) } }
0
Kotlin
0
0
c405fd8d19f45a32be785e8d9a26ef6e08569ea9
656
dictionary
Apache License 2.0
app/src/main/java/com/harunkor/motionmonitorapp/domain/usecase/move/AddMove.kt
harunkor
507,013,101
false
null
package com.harunkor.motionmonitorapp.domain.usecase.move import com.harunkor.motionmonitorapp.domain.model.MoveEntity import com.harunkor.motionmonitorapp.domain.repository.MoveRepository class AddMove(private val moveRepository: MoveRepository) { operator fun invoke(moveEntity: MoveEntity) = moveRepository.addMove(moveEntity) }
0
Kotlin
0
1
1fc0c8ff860a8f6ce40febe0235ddf4fb33c8877
337
MotionMonitorIceHockeyApp
The Unlicense
buildSrc/src/main/kotlin/korlibs/korge/gradle/util/MD5.kt
korlibs
80,095,683
false
{"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33}
package korlibs.korge.gradle.util import java.security.* fun ByteArray.md5String(): String { return MessageDigest.getInstance("MD5").digest(this).hex }
464
Kotlin
123
2,497
1a565007ab748e00a4d602fcd78f7d4032afaf0b
155
korge
Apache License 2.0
app/src/main/java/com/adityagupta/gdsc_nie/presentation/main/home/events/details/EventDetailsViewModel.kt
yat2k
415,939,124
true
{"Kotlin": 30019}
package com.adityagupta.gdsc_nie.presentation.main.home.events.details import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import com.adityagupta.gdsc_nie.domain.repository.EventDetailsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import javax.inject.Inject @HiltViewModel class EventDetailsViewModel @Inject constructor( private val repository: EventDetailsRepository ) : ViewModel() { val responseLiveData = liveData(Dispatchers.IO) { emit(repository.getResponseFromRealtimeDatabaseUsingCoroutines()) } }
0
Kotlin
0
0
a0f35eafbbcce7e945d25d5afb7d775dec0495cd
602
GDSC-NIE-Android
MIT License
app/src/main/kotlin/sakura/felica/felicahistory/EdyHistory.kt
ayatk
114,255,745
false
null
package sakura.felica.felicahistory /** * Edy履歴コード * 参考:http://jennychan.web.fc2.com/format/edy.html */ class EdyHistory { private var remain: Int = 0 private fun init(res: ByteArray, off: Int) { this.remain = toInt(res, off, 12, 13, 14, 15) //12-15: Edy残高 } private fun toInt(res: ByteArray, off: Int, vararg idx: Int): Int { var num = 0 for (anIdx in idx) { num = num shl 8 num += res[off + anIdx].toInt() and 0x0ff } return num } override fun toString(): String = "残高:" + remain + "円" companion object { fun parse(res: ByteArray, off: Int): EdyHistory { val self = EdyHistory() self.init(res, off) return self } } }
0
Kotlin
1
8
2ef3ec8e3ac8f95bef4db0f108f06fb0286fa006
703
FeliCaReader
MIT License
app/src/main/java/com/davipviana/chat/adapter/MessageAdapter.kt
davipviana
158,010,139
false
null
package com.davipviana.chat.adapter import android.content.Context import android.graphics.Color import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.davipviana.chat.R import com.davipviana.chat.model.Message import com.squareup.picasso.Picasso class MessageAdapter( private val context: Context, val messages: ArrayList<Message>, private val clientId: Int ) : RecyclerView.Adapter<MessageAdapter.MessageViewHolder>() { override fun getItemCount(): Int { return messages.size } override fun onBindViewHolder(holder: MessageViewHolder, position: Int) { val message = messages[position] holder.bindMessageInfo(message) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder { val itemView = LayoutInflater.from(context).inflate(R.layout.message_item, parent, false) return MessageViewHolder(itemView) } fun add(message: Message) { messages.add(message) notifyDataSetChanged() } inner class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val messageTextView: TextView = itemView.findViewById(R.id.message_item_text) private val messageUserAvatar: ImageView = itemView.findViewById(R.id.message_item_user_avatar) fun bindMessageInfo(message: Message) { this.messageTextView.text = message.text if(clientId != message.clientId) { itemView.setBackgroundColor(Color.CYAN) } Picasso .get() .load("https://api.adorable.io/avatars/285/" + message.clientId + ".png") .into(messageUserAvatar) } } }
0
Kotlin
0
0
4f22454fea3973ff56f0ebe1c672513df14bdcfd
1,873
chat-app
Apache License 2.0
src/main/kotlin/classiccsproblemskotlin/chapter2/Node.kt
nielsutrecht
327,268,239
false
{"Java": 172624, "Kotlin": 32198}
package classiccsproblemskotlin.chapter2 data class Node<T> ( val state: T, var parent: Node<T>?, var cost: Double = 0.0, val heuristic: Double = 0.0) : Comparable<Node<T>> { override fun compareTo(other: Node<T>): Int = (cost + heuristic).compareTo(other.cost + other.heuristic) fun toPath() : List<T> { val path = mutableListOf(state) var node = this while(node.parent != null) { node = node.parent!! path.add(0, node.state) } return path } }
1
null
1
1
30119ab5ecdb64d90e99e68a05fec9530a0dedc0
565
classiccsproblemskotlin
Apache License 2.0
api/src/commonMain/kotlin/lexi/LogStatus.kt
aSoft-Ltd
592,348,487
false
{"Kotlin": 43591}
package lexi enum class LogStatus { Started, Progressing, Passed, Failed }
0
Kotlin
0
0
6b78ddd6d3c5d860aa26016bf0d801e0b8c653be
79
lexi
MIT License
jupyter-lib/shared-compiler/src/main/kotlin/org/jetbrains/kotlinx/jupyter/messaging/comms/CommManagerInternal.kt
Kotlin
63,066,291
false
{"Kotlin": 924138, "JavaScript": 40044, "CSS": 16243, "Python": 14915, "Jupyter Notebook": 1290, "Shell": 74}
package org.jetbrains.kotlinx.jupyter.messaging.comms import org.jetbrains.kotlinx.jupyter.api.libraries.Comm import org.jetbrains.kotlinx.jupyter.api.libraries.CommManager import org.jetbrains.kotlinx.jupyter.messaging.CommClose import org.jetbrains.kotlinx.jupyter.messaging.CommMsg import org.jetbrains.kotlinx.jupyter.messaging.CommOpen import org.jetbrains.kotlinx.jupyter.messaging.Message interface CommManagerInternal : CommManager { fun processCommOpen(message: Message, content: CommOpen): Comm? fun processCommMessage(message: Message, content: CommMsg) fun processCommClose(message: Message, content: CommClose) }
71
Kotlin
108
1,034
9ba6d0009410c307f5b150483a9fb7a560cd577c
640
kotlin-jupyter
Apache License 2.0
composeApp/src/commonMain/kotlin/daily/GetDailyPokemon.kt
numq
785,492,262
false
{"Kotlin": 119523, "Swift": 594, "HTML": 304}
package daily import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.todayIn import pokemon.Pokemon import pokemon.PokemonRepository import usecase.UseCase import kotlin.random.Random class GetDailyPokemon( private val repository: PokemonRepository, ) : UseCase<Unit, Pokemon> { override suspend fun execute(input: Unit): Result<Pokemon> { return repository.getPokemons().map { pokemons -> val seed = Clock.System .todayIn(TimeZone.currentSystemDefault()) .atStartOfDayIn(TimeZone.currentSystemDefault()) .toEpochMilliseconds() pokemons.random(Random(seed)) } } }
0
Kotlin
0
1
ed71deadb6b169effa8a59e61938eec122494973
736
reduce-and-conquer
MIT License
pillarbox-core-business/src/main/java/ch/srgssr/pillarbox/core/business/tracker/commandersact/CommandersActTracker.kt
SRGSSR
519,157,987
false
null
/* * Copyright (c) SRG SSR. All rights reserved. * License information is available from the LICENSE file. */ package ch.srgssr.pillarbox.core.business.tracker.commandersact import androidx.media3.exoplayer.ExoPlayer import ch.srgssr.pillarbox.analytics.commandersact.CommandersAct import ch.srgssr.pillarbox.player.tracker.MediaItemTracker import kotlin.time.Duration.Companion.milliseconds /** * Commanders act tracker * * https://confluence.srg.beecollaboration.com/display/INTFORSCHUNG/standard+streaming+events%3A+sequence+of+events+for+media+player+actions * * @property commandersAct CommandersAct to send stream events */ class CommandersActTracker(private val commandersAct: CommandersAct) : MediaItemTracker { /** * Data for CommandersAct * * @property assets labels to send to CommandersAct * @property sourceId TBD */ data class Data(val assets: Map<String, String>, val sourceId: String? = null) private var analyticsStreaming: CommandersActStreaming? = null private var currentData: Data? = null override fun start(player: ExoPlayer, initialData: Any?) { requireNotNull(initialData) require(initialData is Data) commandersAct.enableRunningInBackground() currentData = initialData analyticsStreaming = CommandersActStreaming(commandersAct = commandersAct, player = player, currentData = initialData) analyticsStreaming?.let { player.addAnalyticsListener(it) } } override fun update(data: Any) { require(data is Data) if (currentData != data) { analyticsStreaming?.let { it.currentData = data } } } override fun stop(player: ExoPlayer, reason: MediaItemTracker.StopReason, positionMs: Long) { analyticsStreaming?.let { player.removeAnalyticsListener(it) it.notifyStop(position = positionMs.milliseconds, reason == MediaItemTracker.StopReason.EoF) } analyticsStreaming = null currentData = null } /** * Factory */ class Factory(private val commandersAct: CommandersAct) : MediaItemTracker.Factory { override fun create(): MediaItemTracker { return CommandersActTracker(commandersAct) } } }
24
null
1
9
7209750736a47157f22dd939a17750d649172f0a
2,293
pillarbox-android
MIT License
formats/json-tests/commonTest/src/kotlinx/serialization/json/JsonModesTest.kt
Kotlin
97,827,246
false
null
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json import kotlinx.serialization.* import kotlinx.serialization.test.* import kotlin.test.* class JsonModesTest : JsonTestBase() { @Test fun testNan() = parametrizedTest(lenient) { assertStringFormAndRestored("{\"double\":NaN,\"float\":NaN}", Box(Double.NaN, Float.NaN), Box.serializer()) } @Test fun testInfinity() = parametrizedTest(lenient) { assertStringFormAndRestored( "{\"double\":Infinity,\"float\":-Infinity}", Box(Double.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), Box.serializer() ) } @Test fun nonStrictJsonCanSkipValues() = parametrizedTest { jsonTestingMode -> val data = JsonOptionalTests.Data() assertEquals( lenient.decodeFromString(JsonOptionalTests.Data.serializer(), "{strangeField: 100500, a:0}", jsonTestingMode), data ) assertEquals( lenient.decodeFromString(JsonOptionalTests.Data.serializer(), "{a:0, strangeField: 100500}", jsonTestingMode), data ) } @Test fun nonStrictJsonCanSkipComplexValues() = parametrizedTest { jsonTestingMode -> val data = JsonOptionalTests.Data() assertEquals( lenient.decodeFromString( JsonOptionalTests.Data.serializer(), "{a: 0, strangeField: {a: b, c: {d: e}, f: [g,h,j] }}", jsonTestingMode ), data ) assertEquals( lenient.decodeFromString( JsonOptionalTests.Data.serializer(), "{strangeField: {a: b, c: {d: e}, f: [g,h,j] }, a: 0}", jsonTestingMode ), data ) } @Test fun ignoreKeysCanIgnoreWeirdStringValues() { val data = JsonOptionalTests.Data() fun doTest(input: String) { assertEquals(data, lenient.decodeFromString(input)) } doTest("{a: 0, strangeField: [\"imma string with } bracket\", \"sss\"]}") doTest("{a: 0, strangeField: [\"imma string with ] bracket\", \"sss\"]}") doTest("{a: 0, strangeField: \"imma string with } bracket\"}") doTest("{a: 0, strangeField: \"imma string with ] bracket\"}") doTest("{a: 0, strangeField: {key: \"imma string with ] bracket\"}}") doTest("{a: 0, strangeField: {key: \"imma string with } bracket\"}}") doTest("""{"a": 0, "strangeField": {"key": "imma string with } bracket"}}""") doTest("""{"a": 0, "strangeField": {"key": "imma string with ] bracket"}}""") doTest("""{"a": 0, "strangeField": ["imma string with ] bracket"]}""") doTest("""{"a": 0, "strangeField": ["imma string with } bracket"]}""") } @Serializable class Empty @Test fun lenientThrowOnMalformedString() { fun doTest(input: String) { assertFailsWith<SerializationException> { lenient.decodeFromString(Empty.serializer(), input) } } doTest("""{"a":[{"b":[{"c":{}d",""e"":"}]}""") doTest("""{"a":[}""") doTest("""{"a":""") lenient.decodeFromString(Empty.serializer(), """{"a":[]}""") // should not throw } @Test fun testSerializeQuotedJson() = parametrizedTest { jsonTestingMode -> assertEquals( """{"a":10,"e":false,"c":"Hello"}""", default.encodeToString( JsonTransientTest.Data.serializer(), JsonTransientTest.Data(10, 100), jsonTestingMode ) ) } @Test fun testStrictJsonCanNotSkipValues() = parametrizedTest { jsonTestingMode -> assertFailsWith(SerializationException::class) { default.decodeFromString(JsonOptionalTests.Data.serializer(), "{strangeField: 100500, a:0}", jsonTestingMode) } } @Serializable data class Box(val double: Double, val float: Float) }
407
null
621
5,396
d4d066d72a9f92f06c640be5a36a22f75d0d7659
4,029
kotlinx.serialization
Apache License 2.0
src/main/kotlin/com/example/mediasamplekotlin/repositories/UserRepository.kt
pi0ne
165,431,884
false
{"Kotlin": 13146, "HTML": 3745}
package com.example.mediasamplekotlin.repositories import com.example.mediasamplekotlin.entities.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface UserRepository : JpaRepository<User, Long> { fun findByEmail(email: String): User? }
0
Kotlin
0
0
f450e4e5870078c2cdc34e231cd7575e2164f7c2
324
media-sample-kotlin
MIT License
px-checkout/src/main/java/com/mercadopago/android/px/internal/repository/PayerPaymentMethodRepository.kt
mercadopago
49,529,486
false
null
package com.mercadopago.android.px.internal.repository import com.mercadopago.android.px.model.CustomSearchItem internal interface PayerPaymentMethodRepository : LocalRepository<List<@kotlin.jvm.JvmSuppressWildcards CustomSearchItem>> { operator fun get(key: PayerPaymentMethodKey): CustomSearchItem? operator fun get(customOptionId: String): CustomSearchItem? fun getIdsWithSplitAllowed(): Set<String> }
38
null
69
94
f5cfa00ea5963f9153a237c3f329af5d2d6cd87f
418
px-android
MIT License
designsystem/src/main/java/com/ccc/ncs/designsystem/theme/Theme.kt
moonggae
810,632,720
false
{"Kotlin": 391495, "HTML": 262870}
package com.ccc.ncs.designsystem.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val DarkColorScheme = darkColorScheme( primary = DarkPrimary, onPrimary = White, secondary = PurpleGrey80, tertiary = Pink80, surface = DarkBlue90, onSurface = LightBlue10, onSurfaceVariant = Grey50, surfaceContainer = DarkBlue80, surfaceContainerHigh = DarkBlue70, background = DarkBlue90, ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun NcsTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = when { darkTheme -> DarkColorScheme else -> LightColorScheme } // val view = LocalView.current // if (!view.isInEditMode) { // SideEffect { // val window = (view.context as Activity).window // window.statusBarColor = colorScheme.primary.toArgb() // WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme // } // } MaterialTheme( colorScheme = colorScheme, content = content ) }
1
Kotlin
0
0
fcb8793e3d07314c071ac5d215ca5a2adbea552d
1,687
NoCopyrightSounds-Android
X11 License
app/src/main/java/com/dede/android_eggs/util/TextViewExt.kt
hushenghao
306,645,388
false
null
package com.dede.android_eggs.util import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.widget.TextView private val defaultCompoundDrawable = ColorDrawable(0) fun TextView.updateCompoundDrawablesRelative( start: Drawable? = defaultCompoundDrawable, top: Drawable? = defaultCompoundDrawable, end: Drawable? = defaultCompoundDrawable, bottom: Drawable? = defaultCompoundDrawable, ) { val drawables = compoundDrawablesRelative if (start != defaultCompoundDrawable) drawables[0] = start if (top != defaultCompoundDrawable) drawables[1] = top if (end != defaultCompoundDrawable) drawables[2] = end if (bottom != defaultCompoundDrawable) drawables[3] = bottom setCompoundDrawablesRelative(drawables[0], drawables[1], drawables[2], drawables[3]) }
3
null
6
626
e1874513fbf03f7b1fbb2c89ce093dc97728e162
834
AndroidEasterEggs
Apache License 2.0
ktorfit-lib-common/src/commonMain/kotlin/de/jensklingenberg/ktorfit/converter/request/CoreResponseConverter.kt
Foso
203,655,484
false
null
package de.jensklingenberg.ktorfit.converter.request import de.jensklingenberg.ktorfit.internal.TypeData public interface CoreResponseConverter { /** * Check if this converter supports the return type * @param typeData is the typeData of the outer type of * the return type. e.g. for Flow<String> it will be kotlinx.coroutines.flow.Flow */ public fun supportedType(typeData: TypeData, isSuspend: Boolean): Boolean }
21
null
25
985
77bdb11430e2c787eb69e3c48780eea99e8a75b4
449
Ktorfit
Apache License 2.0
idea/tests/test/org/jetbrains/kotlin/idea/quickfix/quickfixTestUtils.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.utils import java.io.File fun findInspectionFile(startDir: File): File? { var currentDir: File? = startDir while (currentDir != null) { val inspectionFile = File(currentDir, ".inspection") if (inspectionFile.exists()) { return inspectionFile } currentDir = currentDir.parentFile } return null }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
610
intellij-kotlin
Apache License 2.0
app/src/main/java/com/flixclusive/data/repository/WatchlistRepositoryImpl.kt
rhenwinch
659,237,375
false
null
package com.flixclusive.data.repository import com.flixclusive.data.database.watchlist.WatchlistDao import com.flixclusive.di.IoDispatcher import com.flixclusive.domain.model.entities.WatchlistItem import com.flixclusive.domain.repository.WatchlistRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext import javax.inject.Inject class WatchlistRepositoryImpl @Inject constructor( private val watchlistDao: WatchlistDao, @IoDispatcher private val ioDispatcher: CoroutineDispatcher ) : WatchlistRepository { override suspend fun insert(item: WatchlistItem) = withContext(ioDispatcher) { watchlistDao.insert(item) } override suspend fun remove(item: WatchlistItem) = withContext(ioDispatcher) { watchlistDao.delete(item) } override suspend fun removeById(itemId: Int) = withContext(ioDispatcher) { watchlistDao.deleteById(itemId = itemId) } override suspend fun getWatchlistItemById(filmId: Int): WatchlistItem? = withContext(ioDispatcher) { watchlistDao.getWatchlistItemById(filmId) } override suspend fun getAllItems(): List<WatchlistItem> = withContext(ioDispatcher) { watchlistDao.getAllItems() } override fun getAllItemsInFlow(): Flow<List<WatchlistItem>> { return watchlistDao.getAllItemsInFlow() } }
2
Kotlin
2
18
2eef4c82655294eb3b277c00b3d8f7bea3f6961e
1,391
Flixclusive
MIT License
app/src/main/java/ru/n08i40k/polytechnic/next/ui/auth/TrySignUp.kt
N08I40K
857,687,777
false
{"Kotlin": 240310}
package ru.n08i40k.polytechnic.next.ui.auth import android.content.Context import com.android.volley.ClientError import com.android.volley.NoConnectionError import com.android.volley.TimeoutError import com.google.firebase.logger.Logger import kotlinx.coroutines.runBlocking import ru.n08i40k.polytechnic.next.model.UserRole import ru.n08i40k.polytechnic.next.network.request.auth.AuthSignUp import ru.n08i40k.polytechnic.next.network.unwrapException import ru.n08i40k.polytechnic.next.settings.settingsDataStore import java.util.concurrent.TimeoutException internal enum class SignUpError { ALREADY_EXISTS, GROUP_DOES_NOT_EXISTS, TIMED_OUT, NO_CONNECTION, APPLICATION_TOO_OLD, UNKNOWN } internal fun trySignUp( context: Context, username: String, password: String, group: String, role: UserRole, onError: (SignUpError) -> Unit, onSuccess: () -> Unit, ) { AuthSignUp( AuthSignUp.RequestDto( username, password, group, role ), context, { runBlocking { context.settingsDataStore.updateData { currentSettings -> currentSettings .toBuilder() .setUserId(it.id) .setAccessToken(it.accessToken) .setGroup(group) .build() } } onSuccess() }, { val error = when (val exception = unwrapException(it)) { is TimeoutException -> SignUpError.TIMED_OUT is NoConnectionError -> SignUpError.NO_CONNECTION is TimeoutError -> SignUpError.UNKNOWN is ClientError -> { when (exception.networkResponse.statusCode) { 400 -> SignUpError.APPLICATION_TOO_OLD 404 -> SignUpError.GROUP_DOES_NOT_EXISTS 409 -> SignUpError.ALREADY_EXISTS else -> SignUpError.UNKNOWN } } else -> SignUpError.UNKNOWN } if (error == SignUpError.UNKNOWN) { Logger.getLogger("tryRegister") .error("Unknown exception while trying to register!", it) } onError(error) }).send() }
0
Kotlin
0
1
c4444ff2ca63b3f53f4c5b962a373ddd4031a1d9
2,403
polytecnic-android
MIT License
UnrealMedia/app/src/main/java/com/qfleng/um/view/UriImageView.kt
Duke1
424,109,115
false
{"Text": 2, "Ignore List": 4, "Git Attributes": 1, "Markdown": 1, "Shell": 3, "C": 155, "Makefile": 1, "Gradle Kotlin DSL": 4, "Java Properties": 2, "Batchfile": 1, "CMake": 1, "Proguard": 1, "Kotlin": 59, "XML": 45, "C++": 7, "Java": 1}
package com.qfleng.um.view import android.content.Context import android.util.AttributeSet import com.facebook.drawee.generic.RoundingParams import com.facebook.drawee.view.SimpleDraweeView /** * ps:roundingBorderPadding解决白边问题 */ class UriImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : SimpleDraweeView(context, attrs, defStyleAttr) { fun setCornersRadius(radius: Float) { var roundingParams: RoundingParams? = hierarchy.roundingParams if (null == roundingParams) { roundingParams = RoundingParams.fromCornersRadius(radius) } else roundingParams.setCornersRadius(radius) hierarchy.roundingParams = roundingParams } fun setBorderWidth(width: Float) { val roundingParams = hierarchy.roundingParams ?: return roundingParams.borderWidth = width hierarchy.roundingParams = roundingParams } fun setBorderPadding(padding: Float) { val roundingParams = hierarchy.roundingParams ?: return roundingParams.padding = padding hierarchy.roundingParams = roundingParams } fun setBorderColor(color: Int) { val roundingParams = hierarchy.roundingParams ?: return roundingParams.borderColor = color hierarchy.roundingParams = roundingParams } }
0
C
0
1
a3154274937acf58e2bf42207414ff5e2984f553
1,363
UnrealMedia
MIT License
musicservice/src/main/java/com/gsfoxpro/musicservice/service/MusicService.kt
LetItPlay
113,900,291
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 119, "Java": 3, "Kotlin": 151}
package com.gsfoxpro.musicservice.service import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioAttributes import android.media.AudioFocusRequest import android.media.AudioManager import android.net.Uri import android.os.* import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaButtonReceiver import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import com.google.android.exoplayer2.* import com.google.android.exoplayer2.Player.STATE_ENDED import com.google.android.exoplayer2.Player.STATE_IDLE import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.gsfoxpro.musicservice.ExoPlayerListener import com.gsfoxpro.musicservice.MusicRepo import com.gsfoxpro.musicservice.model.AudioTrack import com.gsfoxpro.musicservice.ui.MusicPlayerNotification class MusicService : Service() { var mediaSession: MediaSessionCompat? = null private set var musicRepo: MusicRepo? = null set(value) { field = value notifyRepoChangedListeners(value) initTrack(value?.currentAudioTrack) } private val binder = LocalBinder() private lateinit var exoPlayer: SimpleExoPlayer private lateinit var audioManager: AudioManager private lateinit var audioFocusRequest: AudioFocusRequest private var audioFocusRequested = false private var lastInitializedTrack: AudioTrack? = null private val metadataBuilder = MediaMetadataCompat.Builder() private var becomingNoisyReceiverRegistered = false private val updateIntervalMs = 1000L private val progressHandler = Handler() private var needUpdateProgress = false private val repoListeners: MutableSet<RepoChangesListener> = mutableSetOf() private var initialPlaybackSpeed: Float = 1f private val stateBuilder: PlaybackStateCompat.Builder = PlaybackStateCompat.Builder() .setActions( PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_STOP or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) private val playbackSpeed get() = mediaSession?.controller?.playbackState?.playbackSpeed ?: initialPlaybackSpeed private val mediaSessionCallback = object : MediaSessionCompat.Callback() { override fun onCommand(command: String, extras: Bundle?, cb: ResultReceiver?) { when (command) { CHANGE_PLAYBACK_SPEED -> { val arg = extras?.getFloat(ARG_SPEED) ?: return val currentState = mediaSession?.controller?.playbackState ?: return exoPlayer.playbackParameters = PlaybackParameters(arg, 1.0f) val newState = stateBuilder.setState(currentState.state, currentState.position, arg).build() mediaSession?.setPlaybackState(newState) } UPDATE_INFO -> { mediaSession?.setMetadata(metadataBuilder.build()) sendPlaylistInfoEvent() } } } override fun onPlay() { play(musicRepo?.currentAudioTrack) } override fun onPause() { exoPlayer.playWhenReady = false stopUpdateProgress() unregisterBecomingNoisyReceiver() abandonAudioFocus() mediaSession?.apply { setPlaybackState(stateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, exoPlayer.currentPosition, playbackSpeed).build()) MusicPlayerNotification.show(this@MusicService, this) } } override fun onStop() { exoPlayer.stop() lastInitializedTrack = null stopUpdateProgress() unregisterBecomingNoisyReceiver() abandonAudioFocus() mediaSession?.apply { isActive = false setPlaybackState(stateBuilder.setState(PlaybackStateCompat.STATE_STOPPED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, playbackSpeed).build()) } MusicPlayerNotification.hide(this@MusicService) } override fun onSkipToNext() { play(musicRepo?.nextAudioTrack) } override fun onSkipToPrevious() { play(musicRepo?.prevAudioTrack) } override fun onSeekTo(positionMs: Long) { exoPlayer.seekTo(positionMs) } override fun onSkipToQueueItem(id: Long) { play(musicRepo?.getAudioTrackAtId(id.toInt())) } } private val playerListener = object : ExoPlayerListener() { override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { when (playbackState) { STATE_ENDED, STATE_IDLE -> { if (musicRepo?.autoPlay == true && playWhenReady) { mediaSessionCallback.onSkipToNext() } } } } } private val updateProgressTask = Runnable { if (needUpdateProgress) { val bundle = Bundle().apply { putLong(CURRENT_PROGRESS, exoPlayer.currentPosition) } mediaSession?.sendSessionEvent(PROGRESS_UPDATE_EVENT, bundle) startUpdateProgress(true) } } private val becomingNoisyReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) { mediaSessionCallback.onPause() } } } private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange -> when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { mediaSessionCallback.onPlay() exoPlayer.volume = VOLUME_NORMAL } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { registerBecomingNoisyReceiver() exoPlayer.volume = VOLUME_DUCK } else -> mediaSessionCallback.onPause() } } override fun onCreate() { super.onCreate() audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val audioAttributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build() audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setOnAudioFocusChangeListener(audioFocusChangeListener) .setAcceptsDelayedFocusGain(false) .setWillPauseWhenDucked(true) .setAudioAttributes(audioAttributes) .build() } val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON, null, applicationContext, MediaButtonReceiver::class.java) mediaSession = MediaSessionCompat(this, "MusicService").apply { setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS) setCallback(mediaSessionCallback) setMediaButtonReceiver(PendingIntent.getBroadcast(applicationContext, 0, mediaButtonIntent, 0)) } exoPlayer = ExoPlayerFactory.newSimpleInstance(DefaultRenderersFactory(this), DefaultTrackSelector(), DefaultLoadControl()) exoPlayer.addListener(playerListener) } override fun onDestroy() { super.onDestroy() release() } override fun onTaskRemoved(rootIntent: Intent?) { super.onTaskRemoved(rootIntent) release() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null && intent.hasExtra(ARG_SPEED)) { initialPlaybackSpeed = intent.getFloatExtra(ARG_SPEED, 1.0F) exoPlayer.playbackParameters = PlaybackParameters(initialPlaybackSpeed, 1.0f) } MediaButtonReceiver.handleIntent(mediaSession, intent) return super.onStartCommand(intent, flags, startId) } private fun release() { exoPlayer.release() mediaSession?.release() MusicPlayerNotification.hide(this@MusicService) } fun addTrackToStart(track: AudioTrack) { musicRepo?.addTrackToStart(track) repoListeners.forEach { it.onRepoChanged(musicRepo) } } fun addTrackToEnd(track: AudioTrack) { musicRepo?.addTrackToEnd(track) repoListeners.forEach { it.onRepoChanged(musicRepo) } } fun removeTrack(id:Int){ musicRepo?.removeTrack(id) repoListeners.forEach { it.onRepoChanged(musicRepo) } } private fun initTrack(audioTrack: AudioTrack?) { if (audioTrack != null) { val mediaSource = ExtractorMediaSource.Factory(DefaultDataSourceFactory(applicationContext, "user-agent")) .setExtractorsFactory(DefaultExtractorsFactory()) .createMediaSource(Uri.parse(audioTrack.url)) exoPlayer.prepare(mediaSource) } mediaSession?.setMetadata(buildMetadata(metadataBuilder, audioTrack)) lastInitializedTrack = audioTrack sendPlaylistInfoEvent() } private fun buildMetadata(builder: MediaMetadataCompat.Builder, audioTrack: AudioTrack?): MediaMetadataCompat { return builder.putString(MediaMetadataCompat.METADATA_KEY_ART_URI, audioTrack?.imageUrl) .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, audioTrack?.id?.toString()) .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, audioTrack?.url) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, audioTrack?.subtitle) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, audioTrack?.title) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, audioTrack?.lengthInMs ?: 0) .build() } private fun play(audioTrack: AudioTrack?) { if (audioTrack == null) { return } var trackChanged = false if (lastInitializedTrack?.id != audioTrack.id) { initTrack(audioTrack) trackChanged = true } if (!requestAudioFocus()) { return } val currentPosition = if (trackChanged) 0L else exoPlayer.currentPosition mediaSession?.apply { isActive = true setPlaybackState(stateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, currentPosition, playbackSpeed).build()) MusicPlayerNotification.show(this@MusicService, this) } mediaSession?.sendSessionEvent("eee", null) registerBecomingNoisyReceiver() exoPlayer.playWhenReady = true startUpdateProgress() } @Suppress("DEPRECATION") private fun requestAudioFocus(): Boolean { if (!audioFocusRequested) { audioFocusRequested = true val audioFocusResult: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) audioManager.requestAudioFocus(audioFocusRequest) else audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) if (audioFocusResult != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { return false } } return true } @Suppress("DEPRECATION") private fun abandonAudioFocus() { if (!audioFocusRequested) { return } audioFocusRequested = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { audioManager.abandonAudioFocusRequest(audioFocusRequest) } else { audioManager.abandonAudioFocus(audioFocusChangeListener) } } private fun startUpdateProgress(fromRunnable: Boolean = false) { if (!fromRunnable && needUpdateProgress) { return } needUpdateProgress = true progressHandler.postDelayed(updateProgressTask, updateIntervalMs) } private fun stopUpdateProgress() { needUpdateProgress = false progressHandler.removeCallbacks(updateProgressTask) } private fun sendPlaylistInfoEvent() { val bundle = Bundle().apply { putBoolean(HAS_NEXT, musicRepo?.hasNext == true) putBoolean(HAS_PREV, musicRepo?.hasPrev == true) } mediaSession?.sendSessionEvent(PLAYLIST_INFO_EVENT, bundle) } private fun registerBecomingNoisyReceiver() { if (!becomingNoisyReceiverRegistered) { registerReceiver(becomingNoisyReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) } } private fun unregisterBecomingNoisyReceiver() { if (becomingNoisyReceiverRegistered) { unregisterReceiver(becomingNoisyReceiver) } } fun addRepoChangesListener(listener: RepoChangesListener) = repoListeners.add(listener) fun removeRepoChangesListener(listener: RepoChangesListener) = repoListeners.remove(listener) private fun notifyRepoChangedListeners(repo: MusicRepo?) { repoListeners.forEach { it.onRepoChanged(repo) } } override fun onBind(intent: Intent?) = binder inner class LocalBinder(val musicService: MusicService = this@MusicService) : Binder() interface RepoChangesListener { fun onRepoChanged(repo: MusicRepo?) } companion object { const val UPDATE_INFO = "UPDATE_INFO" const val CHANGE_PLAYBACK_SPEED = "CHANGE_PLAYBACK_SPEED" const val ARG_SPEED = "ARG_SPEED" const val PROGRESS_UPDATE_EVENT = "PROGRESS_UPDATE_EVENT" const val CURRENT_PROGRESS = "CURRENT_PROGRESS" const val PLAYLIST_INFO_EVENT = "PLAYLIST_INFO_EVENT" const val HAS_NEXT = "HAS_NEXT" const val HAS_PREV = "HAS_PREV" const val VOLUME_DUCK = 0.2f const val VOLUME_NORMAL = 1.0f } }
8
Kotlin
1
0
74380c7cf5fe6ce8f307cd82d7e90f2e9704eacd
14,880
AndroidClient
Apache License 2.0
app/src/main/java/com/werb/moretype/complete/Complete.kt
werbhelius
96,016,727
false
null
package com.werb.moretype.complete /** * Created by wanbo on 2017/7/15. */ data class Complete(val name: String, val desc: String, val icon: String, val time: String, val text: String, val image: String, val width: String, val height: String)
0
null
22
192
371878a4003a58e4e708b6141def4ac4e5bf5f00
385
MoreType
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/auth/registration/RegistrationResult.kt
matrix-org
287,466,066
false
null
/* * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.api.auth.registration import org.matrix.android.sdk.api.session.Session // Either a session or an object containing data about registration stages sealed class RegistrationResult { data class Success(val session: Session) : RegistrationResult() data class FlowResponse(val flowResult: FlowResult) : RegistrationResult() } data class FlowResult( val missingStages: List<Stage>, val completedStages: List<Stage> )
1
null
27
97
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
1,087
matrix-android-sdk2
Apache License 2.0
spigot/src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/loading/MythicConfigLoader.kt
MythicDrops
10,021,467
false
{"Kotlin": 1247884}
package com.tealcube.minecraft.bukkit.mythicdrops.loading import com.tealcube.minecraft.bukkit.mythicdrops.api.errors.LoadingErrorManager import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItemManager import com.tealcube.minecraft.bukkit.mythicdrops.api.items.ItemGroupManager import com.tealcube.minecraft.bukkit.mythicdrops.api.loading.ConfigLoader import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager import com.tealcube.minecraft.bukkit.mythicdrops.api.repair.RepairItemManager import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketExtenderTypeManager import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketGemManager import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.SocketTypeManager import com.tealcube.minecraft.bukkit.mythicdrops.api.socketing.combiners.SocketGemCombinerManager import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.TierManager import com.tealcube.minecraft.bukkit.mythicdrops.aura.AuraRunnableFactory import com.tealcube.minecraft.bukkit.mythicdrops.config.ConfigQualifiers import com.tealcube.minecraft.bukkit.mythicdrops.config.Resources import com.tealcube.minecraft.bukkit.mythicdrops.config.TierYamlConfigurations import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString import com.tealcube.minecraft.bukkit.mythicdrops.getOrCreateSection import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicCustomItem import com.tealcube.minecraft.bukkit.mythicdrops.items.MythicItemGroup import com.tealcube.minecraft.bukkit.mythicdrops.logging.MythicDropsLogger import com.tealcube.minecraft.bukkit.mythicdrops.names.NameMap import com.tealcube.minecraft.bukkit.mythicdrops.relations.MythicRelation import com.tealcube.minecraft.bukkit.mythicdrops.repair.MythicRepairItem import com.tealcube.minecraft.bukkit.mythicdrops.socketing.combiners.MythicSocketGemCombiner import com.tealcube.minecraft.bukkit.mythicdrops.tiers.MythicTier import io.pixeloutlaw.kindling.Log import io.pixeloutlaw.minecraft.spigot.config.VersionedFileAwareYamlConfiguration import org.bukkit.scheduler.BukkitTask import org.koin.core.annotation.Named import org.koin.core.annotation.Single @Single internal class MythicConfigLoader( private val auraRunnableFactory: AuraRunnableFactory, private val customItemManager: CustomItemManager, private val itemGroupManager: ItemGroupManager, private val loadingErrorManager: LoadingErrorManager, private val relationManager: RelationManager, private val repairItemManager: RepairItemManager, private val resources: Resources, private val settingsManager: SettingsManager, private val socketGemCombinerManager: SocketGemCombinerManager, private val socketGemManager: SocketGemManager, private val socketExtenderTypeManager: SocketExtenderTypeManager, private val socketTypeManager: SocketTypeManager, private val tierManager: TierManager, private val tierYamlConfigurations: TierYamlConfigurations, @Named(ConfigQualifiers.STARTUP) private val startupYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.ARMOR) private val armorYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.CONFIG) private val configYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.CUSTOM_ITEMS) private val customItemsYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.LANGUAGE) private val languageYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.CREATURE_SPAWNING) private val creatureSpawningYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.RELATION) private val relationYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.REPAIR_COSTS) private val repairCostsYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.REPAIRING) private val repairingYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.SOCKET_GEM_COMBINERS) private val socketGemCombinersYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.SOCKET_GEMS) private val socketGemsYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.SOCKET_TYPES) private val socketTypesYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.SOCKETING) private val socketingYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.IDENTIFYING) private val identifyingYamlConfiguration: VersionedFileAwareYamlConfiguration, @Named(ConfigQualifiers.ITEM_GROUPS) private val itemGroupsYamlConfiguration: VersionedFileAwareYamlConfiguration ) : ConfigLoader { companion object { private const val ALREADY_LOADED_TIER_MSG = "Not loading %s as there is already a tier with that display color and identifier color loaded: %s" } private var auraTask: BukkitTask? = null override fun reloadStartupSettings() { startupYamlConfiguration.load() settingsManager.loadStartupSettingsFromConfiguration(startupYamlConfiguration) Log.clearLoggers() val logLevel = if (settingsManager.startupSettings.isDebug) { Log.Level.DEBUG } else { Log.Level.INFO } Log.addLogger(MythicDropsLogger(logLevel)) } override fun reloadSettings() { reloadStartupSettings() Log.debug("Clearing loading errors...") loadingErrorManager.clear() Log.debug("Loading settings from armor.yml...") armorYamlConfiguration.load() settingsManager.loadArmorSettingsFromConfiguration(armorYamlConfiguration) Log.debug("Loading settings from config.yml...") configYamlConfiguration.load() settingsManager.loadConfigSettingsFromConfiguration(configYamlConfiguration) if (!settingsManager.configSettings.options.isDisableLegacyItemChecks) { val disableLegacyItemChecksWarning = """ Legacy item checks (checking the lore of items) are not disabled! This feature is deprecated and will be removed in MythicDrops 9.x. """.trimIndent() Log.warn(disableLegacyItemChecksWarning) } Log.debug("Loading settings from language.yml...") languageYamlConfiguration.load() settingsManager.loadLanguageSettingsFromConfiguration(languageYamlConfiguration) Log.debug("Loading settings from creatureSpawning.yml...") creatureSpawningYamlConfiguration.load() settingsManager.loadCreatureSpawningSettingsFromConfiguration(creatureSpawningYamlConfiguration) Log.debug("Loading settings from repairing.yml...") repairingYamlConfiguration.load() settingsManager.loadRepairingSettingsFromConfiguration(repairingYamlConfiguration) Log.debug("Loading settings from socketing.yml...") socketingYamlConfiguration.load() settingsManager.loadSocketingSettingsFromConfiguration(socketingYamlConfiguration) Log.debug("Loading settings from identifying.yml...") identifyingYamlConfiguration.load() settingsManager.loadIdentifyingSettingsFromConfiguration(identifyingYamlConfiguration) } override fun reloadTiers() { Log.debug("Loading tiers...") tierManager.clear() tierYamlConfigurations.load() tierYamlConfigurations.getTierYamlConfigurations().forEach { tierYaml -> tierYaml.load() Log.debug("Loading tier from ${tierYaml.fileName}...") val key = tierYaml.fileName.replace(".yml", "") if (tierManager.contains(key)) { val message = "Not loading $key as there is already a tier with that name loaded" Log.info(message) loadingErrorManager.add(message) return@forEach } val tier = MythicTier.fromConfigurationSection(tierYaml, key, itemGroupManager, loadingErrorManager) ?: return@forEach // check if tier already exists with same color combination val preExistingTierWithColors = tierManager.getWithColors(tier.displayColor, tier.identifierColor) val disableLegacyItemChecks = settingsManager.configSettings.options.isDisableLegacyItemChecks if (preExistingTierWithColors != null && !disableLegacyItemChecks) { val message = ALREADY_LOADED_TIER_MSG.format( key, preExistingTierWithColors.name ) Log.info(message) loadingErrorManager.add(message) return@forEach } tierManager.add(tier) } Log.info("Loaded tiers: ${tierManager.get().joinToString(prefix = "[", postfix = "]") { it.name }}") } override fun reloadCustomItems() { Log.debug("Loading custom items...") customItemManager.clear() customItemsYamlConfiguration.load() customItemsYamlConfiguration.getKeys(false).forEach { if (!customItemsYamlConfiguration.isConfigurationSection(it)) { return@forEach } val customItemCs = customItemsYamlConfiguration.getOrCreateSection(it) val customItem = MythicCustomItem.fromConfigurationSection(customItemCs, it) if (customItem.material.isAir) { val message = "Error when loading custom item ($it): material is equivalent to AIR: ${customItem.material}" Log.debug(message) loadingErrorManager.add(message) return@forEach } customItemManager.add(customItem) } Log.info("Loaded custom items: ${customItemManager.get().size}") } override fun saveCustomItems() { Log.debug("Saving custom items...") val version = customItemsYamlConfiguration.getNonNullString("version") customItemsYamlConfiguration.getKeys(false).forEach { customItemsYamlConfiguration[it] = null } customItemsYamlConfiguration["version"] = version customItemManager.get().forEach { customItem -> val name = customItem.name customItemsYamlConfiguration.set("$name.display-name", customItem.displayName) customItemsYamlConfiguration.set("$name.material", customItem.material.name) customItemsYamlConfiguration.set("$name.lore", customItem.lore) customItemsYamlConfiguration.set("$name.weight", customItem.weight) customItemsYamlConfiguration.set("$name.durability", customItem.durability) customItemsYamlConfiguration.set("$name.chance-to-drop-on-monster-death", customItem.chanceToDropOnDeath) customItemsYamlConfiguration.set("$name.broadcast-on-find", customItem.isBroadcastOnFind) customItemsYamlConfiguration.set("$name.custom-model-data", customItem.customModelData) customItem.enchantments.forEach { val enchKey = it.enchantment.key customItemsYamlConfiguration.set("$name.enchantments.$enchKey.minimum-level", it.minimumLevel) customItemsYamlConfiguration.set("$name.enchantments.$enchKey.maximum-level", it.maximumLevel) } customItem.attributes.forEach { customItemsYamlConfiguration.set("$name.attributes.${it.name}.attribute", it.attribute.name) customItemsYamlConfiguration.set("$name.attributes.${it.name}.minimum-amount", it.minimumAmount) customItemsYamlConfiguration.set("$name.attributes.${it.name}.maximum-amount", it.maximumAmount) customItemsYamlConfiguration.set("$name.attributes.${it.name}.operation", it.operation) customItemsYamlConfiguration.set("$name.attributes.${it.name}.slot", it.equipmentSlot) } val color = customItem.rgb customItemsYamlConfiguration.set("$name.rgb.red", color.red) customItemsYamlConfiguration.set("$name.rgb.green", color.green) customItemsYamlConfiguration.set("$name.rgb.blue", color.blue) } customItemsYamlConfiguration.save() Log.info("Saved custom items") } override fun reloadNames() { NameMap.clear() Log.debug("Loading prefixes...") val prefixes = resources.loadPrefixes() NameMap.putAll(prefixes) Log.info("Loaded prefixes: ${prefixes.values.flatten().size}") Log.debug("Loading suffixes...") val suffixes = resources.loadSuffixes() NameMap.putAll(suffixes) Log.info("Loaded suffixes: ${suffixes.values.flatten().size}") Log.debug("Loading lore...") val lore = resources.loadLore() NameMap.putAll(lore) Log.info("Loaded lore: ${lore.values.flatten().size}") Log.debug("Loading mob names...") val mobNames = resources.loadMobNames() NameMap.putAll(mobNames) Log.info("Loaded mob names: ${mobNames.values.flatten().size}") } override fun reloadRepairCosts() { Log.debug("Loading repair costs...") repairItemManager.clear() repairCostsYamlConfiguration.load() repairCostsYamlConfiguration .getKeys(false) .mapNotNull { key -> if (!repairCostsYamlConfiguration.isConfigurationSection(key)) { return@mapNotNull null } val repairItemConfigurationSection = repairCostsYamlConfiguration.getOrCreateSection(key) MythicRepairItem.fromConfigurationSection(repairItemConfigurationSection, key, loadingErrorManager) }.forEach { repairItemManager.add(it) } Log.info("Loaded repair items: ${repairItemManager.get().size}") } override fun reloadItemGroups() { Log.debug("Loading item groups...") itemGroupManager.clear() itemGroupsYamlConfiguration.load() itemGroupsYamlConfiguration.getKeys(false).forEach { key -> if (!itemGroupsYamlConfiguration.isConfigurationSection(key)) { return@forEach } val itemGroupCs = itemGroupsYamlConfiguration.getOrCreateSection(key) itemGroupManager.add(MythicItemGroup.fromConfigurationSection(itemGroupCs, key)) } Log.info("Loaded item groups: ${itemGroupManager.get().size}") } override fun reloadSocketGemCombiners() { Log.debug("Loading socket gem combiners...") socketGemCombinerManager.clear() socketGemCombinersYamlConfiguration.load() socketGemCombinersYamlConfiguration.getKeys(false).forEach { if (!socketGemCombinersYamlConfiguration.isConfigurationSection(it)) return@forEach try { socketGemCombinerManager.add( MythicSocketGemCombiner.fromConfigurationSection( socketGemCombinersYamlConfiguration.getOrCreateSection( it ), it ) ) } catch (iae: IllegalArgumentException) { Log.error("Unable to load socket gem combiner with id=$it", iae) loadingErrorManager.add("Unable to load socket gem combiner with id=$it") } } } override fun saveSocketGemCombiners() { Log.debug("Saving socket gem combiners...") socketGemCombinersYamlConfiguration .getKeys(false) .forEach { socketGemCombinersYamlConfiguration[it] = null } socketGemCombinerManager.get().forEach { val key = it.uuid.toString() socketGemCombinersYamlConfiguration["$key.world"] = it.location.world.name socketGemCombinersYamlConfiguration["$key.x"] = it.location.x socketGemCombinersYamlConfiguration["$key.y"] = it.location.y socketGemCombinersYamlConfiguration["$key.z"] = it.location.z } socketGemCombinersYamlConfiguration.save() Log.info("Saved socket gem combiners") } override fun reloadSocketGems() { Log.debug("Loading socket types and socket extender types...") socketTypeManager.clear() socketExtenderTypeManager.clear() socketTypesYamlConfiguration.load() socketTypeManager.addAll( socketTypeManager.loadFromConfiguration( socketTypesYamlConfiguration ) ) socketExtenderTypeManager.addAll( socketExtenderTypeManager.loadFromConfiguration( socketTypesYamlConfiguration ) ) Log.debug("Loading socket gems...") socketGemManager.clear() socketGemsYamlConfiguration.load() socketGemManager.addAll( socketGemManager.loadFromConfiguration(socketGemsYamlConfiguration) ) auraTask?.cancel().also { Log.info("Existing aura task cancelled") } auraTask = auraRunnableFactory.createAuraRunnableTask()?.also { Log.info("Auras enabled") } } override fun reloadRelations() { Log.debug("Loading relations...") relationManager.clear() relationYamlConfiguration.load() relationYamlConfiguration.getKeys(false).forEach { if (!relationYamlConfiguration.isConfigurationSection(it)) return@forEach relationManager.add( MythicRelation.fromConfigurationSection( relationYamlConfiguration.getOrCreateSection(it), it ) ) } Log.info("Loaded relations: ${relationManager.get().size}") } }
60
Kotlin
43
40
e08d2ad3befda5e18bd763b6f30f00fa4ff44c35
18,218
MythicDrops
MIT License
app/src/main/java/com/balsikandar/github/data/db/DbEntityMapper.kt
balsikandar
255,555,406
false
null
package com.balsikandar.github.data.db import com.balsikandar.github.data.TrendingRepo object DbEntityMapper { fun convert(trendingRepoAPI: TrendingRepoDB): TrendingRepo { return TrendingRepo( trendingRepoAPI.author, trendingRepoAPI.name, trendingRepoAPI.description, trendingRepoAPI.language, trendingRepoAPI.stars, trendingRepoAPI.forks, trendingRepoAPI.avatar, false ) } }
0
Kotlin
1
6
7a6f61a5390b68a023b8aafd19d1c25cd7eab1fe
498
MVIGithubSample
Apache License 2.0
glance/glance-appwidget/src/test/kotlin/androidx/glance/appwidget/translators/RadioButtonBackportTranslatorTest.kt
androidx
256,589,781
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.translators import android.content.Context import android.content.res.Configuration import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.compose.ui.graphics.Color import androidx.glance.GlanceModifier import androidx.glance.appwidget.ImageViewSubject.Companion.assertThat import androidx.glance.appwidget.RadioButton import androidx.glance.appwidget.RadioButtonDefaults import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.applyRemoteViews import androidx.glance.appwidget.configurationContext import androidx.glance.appwidget.findView import androidx.glance.appwidget.findViewByType import androidx.glance.appwidget.runAndTranslate import androidx.glance.color.ColorProvider import androidx.glance.semantics.contentDescription import androidx.glance.semantics.semantics import androidx.glance.unit.ColorProvider import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import kotlin.test.assertIs import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @Config(minSdk = 23, maxSdk = 30) @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) class RadioButtonBackportTranslatorTest { private lateinit var fakeCoroutineScope: TestScope private val context = ApplicationProvider.getApplicationContext<Context>() private val lightContext = configurationContext { uiMode = Configuration.UI_MODE_NIGHT_NO } private val darkContext = configurationContext { uiMode = Configuration.UI_MODE_NIGHT_YES } @Before fun setUp() { fakeCoroutineScope = TestScope() } @Test fun canTranslateRadioButton_fixed_unchecked() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = false, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(Color.Blue), uncheckedColor = ColorProvider(Color.Red), ) ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Red) } @Test fun canTranslateRadioButton_fixed_checked() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(Color.Blue), uncheckedColor = ColorProvider(Color.Red), ) ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Blue) } @Test fun canTranslateRadioButton_dayNight_unchecked_day() = fakeCoroutineScope.runTest { val rv = lightContext.runAndTranslate { RadioButton( checked = false, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(lightContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Green) } @Test fun canTranslateRadioButton_dayNight_unchecked_night() = fakeCoroutineScope.runTest { val rv = darkContext.runAndTranslate { RadioButton( checked = false, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(darkContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Yellow) } @Test fun canTranslateRadioButton_dayNight_checked_day() = fakeCoroutineScope.runTest { val rv = lightContext.runAndTranslate { RadioButton( checked = true, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(lightContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Blue) } @Test fun canTranslateRadioButton_dayNight_checked_night() = fakeCoroutineScope.runTest { val rv = darkContext.runAndTranslate { RadioButton( checked = true, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(darkContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Red) } @Test fun canTranslateRadioButton_resource_unchecked() = fakeCoroutineScope.runTest { val rv = lightContext.runAndTranslate { RadioButton( checked = false, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(lightContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Green) } @Test fun canTranslateRadioButton_resource_checked() = fakeCoroutineScope.runTest { val rv = lightContext.runAndTranslate { RadioButton( checked = true, onClick = null, text = "RadioButton", colors = RadioButtonDefaults.colors( checkedColor = ColorProvider(day = Color.Blue, night = Color.Red), uncheckedColor = ColorProvider(day = Color.Green, night = Color.Yellow), ) ) } val radioButtonRoot = assertIs<ViewGroup>(lightContext.applyRemoteViews(rv)) assertThat(radioButtonRoot.radioImageView).hasColorFilter(Color.Blue) } @Test fun canTranslateRadioButton_onClick_null() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = null, text = "RadioButton", ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.hasOnClickListeners()).isFalse() } @Test fun canTranslateRadioButton_onClick_withAction() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = actionRunCallback<ActionCallback>(), text = "RadioButton", ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.hasOnClickListeners()).isTrue() } @Test fun canTranslateRadioButton_text() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = actionRunCallback<ActionCallback>(), text = "RadioButton", ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) val text = radioButtonRoot.findViewByType<TextView>() assertThat(text).isNotNull() assertThat(text?.text).isEqualTo("RadioButton") } @Test fun canTranslateRadioButton_disabled() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = actionRunCallback<ActionCallback>(), enabled = false, text = "RadioButton", ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.hasOnClickListeners()).isFalse() } @Test fun canTranslateRadioButtonWithSemanticsModifier_contentDescription() = fakeCoroutineScope.runTest { val rv = context.runAndTranslate { RadioButton( checked = true, onClick = actionRunCallback<ActionCallback>(), text = "RadioButton", modifier = GlanceModifier.semantics { contentDescription = "Custom radio button description" }, ) } val radioButtonRoot = assertIs<ViewGroup>(context.applyRemoteViews(rv)) assertThat(radioButtonRoot.contentDescription) .isEqualTo("Custom radio button description") } private val ViewGroup.radioImageView: ImageView? get() = findView { shadowOf(it.drawable).createdFromResId == androidx.glance.appwidget.R.drawable.glance_btn_radio_material_anim } }
29
null
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
11,178
androidx
Apache License 2.0
app/src/main/java/kashyap/in/yajurvedaproject/base/BaseView.kt
KashyapBhat
249,988,816
false
null
package kashyap.`in`.yajurvedaproject.base /** * Created by <NAME> on 2019-12-18. */ interface BaseView { fun showLoading() fun hideLoading() fun showToast(title: String, actionText: String, runnable: Runnable?) }
1
null
1
1
0f4506f66de50a52969169cede63b3135fd6ef9f
228
QuarantineMe
Apache License 2.0
media/src/test/java/fr/nihilus/music/media/provider/MediaDaoTest.kt
ismailghedamsi
322,889,723
true
{"Kotlin": 987508, "Prolog": 57}
/* * Copyright 2019 Thibault Seisel * * 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 fr.nihilus.music.media.provider import fr.nihilus.music.core.os.PermissionDeniedException import fr.nihilus.music.core.test.coroutines.test import fr.nihilus.music.media.provider.MediaProvider.MediaType import io.kotlintest.inspectors.forNone import io.kotlintest.inspectors.forOne import io.kotlintest.matchers.collections.shouldContainExactly import io.kotlintest.matchers.collections.shouldHaveSize import io.kotlintest.matchers.types.shouldBeInstanceOf import io.kotlintest.shouldBe import io.kotlintest.shouldThrow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runBlockingTest import org.junit.Test internal class MediaDaoTest { @Test fun givenDeniedPermission_whenSubscribingTracks_thenTerminateWithPermissionDeniedException() { shouldTerminateIfPermissionIsDenied(MediaDao::tracks) } @Test fun givenDeniedPermission_whenSubscribingAlbums_thenTerminateWithPermissionDeniedException() { shouldTerminateIfPermissionIsDenied(MediaDao::albums) } @Test fun givenDeniedPermission_whenSubscribingArtists_thenTerminateWithPermissionDeniedException() { shouldTerminateIfPermissionIsDenied(MediaDao::artists) } @Test fun givenTrackSubscription_whenReceivingUpdateAndPermissionIsRevoked_thenTerminateWithPermissionDeniedException() { shouldTerminateWhenPermissionIsRevoked(MediaType.TRACKS, MediaDao::tracks) } @Test fun givenAlbumSubscription_whenReceivingUpdateAndPermissionIsRevoked_thenTerminateWithPermissionDeniedException() { shouldTerminateWhenPermissionIsRevoked(MediaType.ALBUMS, MediaDao::albums) } @Test fun givenArtistSubscription_whenReceivingUpdateAndPermissionIsRevoked_thenTerminateWithPermissionDeniedException() { shouldTerminateWhenPermissionIsRevoked(MediaType.ARTISTS, MediaDao::artists) } @Test fun givenTrackSubscription_whenTerminatingWithError_thenUnregisterObserver() { shouldUnregisterObserverOnFlowFailure(MediaType.TRACKS, MediaDao::tracks) } @Test fun givenAlbumSubscription_whenTerminatingWithError_thenUnregisterObserver() { shouldUnregisterObserverOnFlowFailure(MediaType.ALBUMS, MediaDao::albums) } @Test fun givenArtistSubscription_whenTerminatingWithError_thenUnregisterObserver() { shouldUnregisterObserverOnFlowFailure(MediaType.ARTISTS, MediaDao::artists) } @Test fun whenSubscribingTracks_thenLoadCurrentTrackList() { val mediaDao = MediaDaoImpl(TestMediaProvider(tracks = SAMPLE_TRACKS)) shouldLoadMediaOnSubscription(mediaDao.tracks, SAMPLE_TRACKS) } @Test fun whenSubscribingAlbums_thenLoadCurrentAlbumList() { val mediaDao = MediaDaoImpl(TestMediaProvider(albums = SAMPLE_ALBUMS)) shouldLoadMediaOnSubscription(mediaDao.albums, SAMPLE_ALBUMS) } @Test fun whenSubscribingArtists_thenLoadCurrentArtistList() { val mediaDao = MediaDaoImpl(TestMediaProvider(artists = SAMPLE_ARTISTS)) shouldLoadMediaOnSubscription(mediaDao.artists, SAMPLE_ARTISTS) } @Test fun givenTrackSubscription_whenNotifiedForChange_thenReloadTrackList() { val provider = TestMediaProvider() val mediaDao = MediaDaoImpl(provider) shouldReloadMediaWhenNotified(provider, MediaType.TRACKS, mediaDao.tracks, SAMPLE_TRACKS) } @Test fun givenAlbumSubscription_whenNotifiedForChange_thenReloadAlbumList() { val provider = TestMediaProvider() val mediaDao = MediaDaoImpl(provider) shouldReloadMediaWhenNotified(provider, MediaType.ALBUMS, mediaDao.albums, SAMPLE_ALBUMS) } @Test fun givenArtistSubscription_whenNotifiedForChange_thenReloadArtistList() { val provider = TestMediaProvider() val mediaDao = MediaDaoImpl(provider) shouldReloadMediaWhenNotified(provider, MediaType.ARTISTS, mediaDao.artists, SAMPLE_ARTISTS) } @Test fun whenSubscribingTracks_thenRegisterAnObserver() { shouldRegisterAnObserverWhenSubscribed(MediaType.TRACKS, MediaDao::tracks) } @Test fun whenSubscribingAlbums_thenRegisterAnObserver() { shouldRegisterAnObserverWhenSubscribed(MediaType.ALBUMS, MediaDao::albums) } @Test fun whenSubscribingArtists_thenRegisterAnObserver() { shouldRegisterAnObserverWhenSubscribed(MediaType.ARTISTS, MediaDao::artists) } @Test fun givenAnActiveTrackSubscription_whenDisposingIt_thenUnregisterObserver() { shouldUnregisterObserverOnDisposal(MediaType.TRACKS, MediaDao::tracks) } @Test fun givenAnActiveAlbumSubscription_whenDisposingIt_thenUnregisterObserver() { shouldUnregisterObserverOnDisposal(MediaType.ALBUMS, MediaDao::albums) } @Test fun givenAnActiveArtistSubscription_whenDisposingIt_thenUnregisterObserver() { shouldUnregisterObserverOnDisposal(MediaType.ARTISTS, MediaDao::artists) } @Test fun givenDeniedPermission_whenDeletingTracks_thenFailWithPermissionDeniedException() = runBlockingTest { val provider = TestMediaProvider() provider.hasStoragePermission = false val mediaDao = MediaDaoImpl(provider) shouldThrow<PermissionDeniedException> { mediaDao.deleteTracks(longArrayOf(161L)) } } private fun shouldRegisterAnObserverWhenSubscribed( observerType: MediaType, flowProvider: MediaDao.() -> Flow<Any> ) = runBlockingTest { val provider = TestMediaProvider() val mediaDao = MediaDaoImpl(provider) mediaDao.flowProvider().test { provider.registeredObservers.forOne { it.type shouldBe observerType } } } private fun shouldUnregisterObserverOnDisposal( observerType: MediaType, flowProvider: MediaDao.() -> Flow<Any> ) = runBlockingTest { val provider = TestMediaProvider() val mediaDao = MediaDaoImpl(provider) mediaDao.flowProvider().take(1).collect() provider.registeredObservers.forNone { it.type shouldBe observerType } } private fun <M> shouldReloadMediaWhenNotified( provider: TestMediaProvider, type: MediaType, stream: Flow<List<M>>, expected: List<M> ) = runBlockingTest { stream.test { provider.notifyChange(type) expect(2) values[1] shouldContainExactly expected } } private fun <M> shouldLoadMediaOnSubscription( flow: Flow<List<M>>, expectedMedia: List<M> ) = runBlockingTest { val values = flow.take(1).toList() values shouldHaveSize 1 values[0] shouldContainExactly expectedMedia } private fun shouldUnregisterObserverOnFlowFailure( type: MediaType, flowProvider: MediaDao.() -> Flow<Any> ) = runBlockingTest { // Given an active subscription... val revokingPermissionProvider = TestMediaProvider() val mediaDao = MediaDaoImpl(revokingPermissionProvider) mediaDao.flowProvider().test { expect(1) // When receiving an update that triggers an error... revokingPermissionProvider.hasStoragePermission = false revokingPermissionProvider.notifyChange(type) } revokingPermissionProvider.registeredObservers.forNone { it.type shouldBe type } } private fun shouldTerminateIfPermissionIsDenied( flowProvider: MediaDao.() -> Flow<Any> ) = runBlockingTest { val deniedProvider = TestMediaProvider() deniedProvider.hasStoragePermission = false val mediaDao = MediaDaoImpl(deniedProvider) shouldThrow<PermissionDeniedException> { mediaDao.flowProvider().take(1).collect() } } private fun shouldTerminateWhenPermissionIsRevoked( type: MediaType, flowProvider: MediaDao.() -> Flow<Any> ) = runBlockingTest { // Given an active subscription... val revokingPermissionProvider = TestMediaProvider() val mediaDao = MediaDaoImpl(revokingPermissionProvider) mediaDao.flowProvider().test { expect(1) // When permission is revoked and an update notification is received... revokingPermissionProvider.hasStoragePermission = false revokingPermissionProvider.notifyChange(type) val failure = expectFailure() failure.shouldBeInstanceOf<PermissionDeniedException>() } } }
0
null
0
0
6ae2682be14bb1914ec1ffd3ba07db8b3f1f81c3
9,245
android-odeon
Apache License 2.0
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/targets/android/KotlinAndroidTargetPreset.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:Suppress("PackageDirectoryMismatch") // Old package for compatibility package org.jetbrains.kotlin.gradle.plugin.mpp import org.gradle.api.Project import org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPlugin import org.jetbrains.kotlin.gradle.plugin.KotlinTargetPreset class KotlinAndroidTargetPreset( private val project: Project ) : KotlinTargetPreset<KotlinAndroidTarget> { override fun getName(): String = PRESET_NAME override fun createTarget(name: String): KotlinAndroidTarget { val result = KotlinAndroidTarget(name, project).apply { disambiguationClassifier = name preset = this@KotlinAndroidTargetPreset } KotlinAndroidPlugin.applyToTarget(result) return result } companion object { const val PRESET_NAME = "android" } }
125
null
4903
39,894
0ad440f112f353cd2c72aa0a0619f3db2e50a483
1,041
kotlin
Apache License 2.0
domain/src/main/java/com/mkdev/domain/model/BalanceUIModel.kt
msddev
469,005,380
false
null
package com.mkdev.domain.model sealed class BalanceUIModel : UiAwareModel() { object Loading : BalanceUIModel() data class Success(val data: List<Balance>) : BalanceUIModel() data class SuccessWithMessage(val data: Transaction) : BalanceUIModel() data class Error(var error: String) : BalanceUIModel() }
0
Kotlin
0
0
ca6eacd6b5c6e4e612c766cf9b2df45f6b7ed9d0
321
Currency-Exchange
Apache License 2.0
src/main/kotlin/matt/nn/deephys/load/test/dtype/dtype.kt
mjgroth
518,764,053
false
{"Kotlin": 319138, "Python": 15494, "CSS": 778}
package matt.nn.deephys.load.test.dtype import kotlinx.serialization.Serializable import matt.collect.set.contents.Contents import matt.collect.set.contents.contentsOf import matt.lang.common.List2D import matt.math.arithmetic.sumOf import matt.math.numalg.matalg.multiarray.DoubleMultiArrayWrapper import matt.math.numalg.matalg.multiarray.FloatMultiArrayWrapper import matt.math.numalg.matalg.multiarray.MultiArrayWrapper import matt.math.statistics.mean import matt.nn.deephys.calc.TopNeurons import matt.nn.deephys.calc.act.ActivationRatio import matt.nn.deephys.calc.act.ActivationRatioFloat32 import matt.nn.deephys.calc.act.ActivationRatioFloat64 import matt.nn.deephys.calc.act.AlwaysOneActivation import matt.nn.deephys.calc.act.AlwaysOneActivationFloat32 import matt.nn.deephys.calc.act.AlwaysOneActivationFloat64 import matt.nn.deephys.calc.act.RawActivation import matt.nn.deephys.calc.act.RawActivationFloat32 import matt.nn.deephys.calc.act.RawActivationFloat64 import matt.nn.deephys.model.data.InterTestLayer import matt.nn.deephys.model.importformat.im.DeephyImage import matt.nn.deephys.model.importformat.im.ImageActivationCborBytes import matt.nn.deephys.model.importformat.im.ImageActivationCborBytesFloat32 import matt.nn.deephys.model.importformat.im.ImageActivationCborBytesFloat64 import matt.nn.deephys.model.importformat.testlike.TypedTestLike import matt.prim.double.DOUBLE_BYTE_LEN import matt.prim.float.FLOAT_BYTE_LEN import org.jetbrains.kotlinx.multik.api.toNDArray import org.jetbrains.kotlinx.multik.ndarray.data.D1 import org.jetbrains.kotlinx.multik.ndarray.data.D2 import org.jetbrains.kotlinx.multik.ndarray.data.MultiArray import org.jetbrains.kotlinx.multik.ndarray.data.NDArray import java.nio.ByteBuffer import kotlin.math.exp as kotlinExp @Serializable sealed interface DType<N : Number> { companion object { fun leastPrecise( type: DType<*>, vararg types: DType<*> ): DType<*> = if (types.isEmpty()) type else { val all = setOf(type, *types) if (Float32 in all) Float32 else Float64 } } val byteLen: Int fun bytesThing(bytes: ByteArray): ImageActivationCborBytes<N> fun bytesToArray( bytes: ByteArray, numIms: Int ): List<N> fun rawActivation(act: N): RawActivation<N, *> fun activationRatio(act: N): ActivationRatio<N, *> fun alwaysOneActivation(): AlwaysOneActivation<N, *> fun wrap(multiArray: MultiArray<N, D1>): MultiArrayWrapper<N> fun mean(list: List<N>): N fun div( num: N, denom: N ): N fun d1array(list: List<N>): NDArray<N, D1> fun d2array(list: List2D<N>): NDArray<N, D2> fun exp(v: N): N fun sum(list: List<N>): N val emptyImageContents: Contents<DeephyImage<N>> val label: String val one: N val zero: N } @Suppress("UNCHECKED_CAST") fun <N : Number> DType<N>.topNeurons( images: Contents<DeephyImage<*>>, layer: InterTestLayer, test: TypedTestLike<*>, denomTest: TypedTestLike<*>?, forcedNeuronIndices: List<Int>? = null ) = TopNeurons( images = images as Contents<DeephyImage<N>>, layer = layer, test = test as TypedTestLike<N>, denomTest = denomTest as TypedTestLike<N>?, forcedNeuronIndices = forcedNeuronIndices ) sealed class DtypeBase<N : Number>() : DType<N> { final override val emptyImageContents by lazy { contentsOf<DeephyImage<N>>() } } @Serializable object Float32 : DtypeBase<Float>() { override val label = "float32" override val byteLen = FLOAT_BYTE_LEN override fun bytesThing(bytes: ByteArray) = ImageActivationCborBytesFloat32(bytes) override fun bytesToArray( bytes: ByteArray, numIms: Int ): List<Float> = FloatArray(numIms).also { ByteBuffer.wrap(bytes).asFloatBuffer().get(it) }.asList() override fun rawActivation(act: Float) = RawActivationFloat32(act) override fun activationRatio(act: Float) = ActivationRatioFloat32(act) override fun alwaysOneActivation() = AlwaysOneActivationFloat32 override fun wrap(multiArray: MultiArray<Float, D1>) = FloatMultiArrayWrapper(multiArray) override fun mean(list: List<Float>) = list.mean() override fun div( num: Float, denom: Float ): Float = num / denom override fun d1array(list: List<Float>) = list.toNDArray() override fun d2array(list: List2D<Float>) = list.toNDArray() override fun exp(v: Float) = kotlinExp(v) override fun sum(list: List<Float>) = list.sumOf { it } override val one = 1f override val zero = 0f } @Serializable object Float64 : DtypeBase<Double>() { override val label = "float64" override val byteLen = DOUBLE_BYTE_LEN override fun bytesThing(bytes: ByteArray) = ImageActivationCborBytesFloat64(bytes) override fun bytesToArray( bytes: ByteArray, numIms: Int ): List<Double> = DoubleArray(numIms).also { ByteBuffer.wrap(bytes).asDoubleBuffer().get(it) }.asList() override fun rawActivation(act: Double) = RawActivationFloat64(act) override fun activationRatio(act: Double) = ActivationRatioFloat64(act) override fun alwaysOneActivation() = AlwaysOneActivationFloat64 override fun wrap(multiArray: MultiArray<Double, D1>) = DoubleMultiArrayWrapper(multiArray) override fun mean(list: List<Double>) = list.mean() override fun div( num: Double, denom: Double ): Double = num / denom override fun d1array(list: List<Double>) = list.toNDArray() override fun d2array(list: List2D<Double>) = list.toNDArray() override fun exp(v: Double) = kotlinExp(v) override fun sum(list: List<Double>) = list.sum() override val one = 1.0 override val zero = 0.0 } typealias FloatActivationData = List<List<Float>> typealias DoubleActivationData = List<List<Double>>
0
Kotlin
0
1
ca027c489f84ae1c61dd04b49b649119f5d41b76
5,966
deephys
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/general/ActivityRecvGiftData.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.activity.general import org.anime_game_servers.core.base.Version.GI_2_7_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.ProtoModel import org.anime_game_servers.multi_proto.gi.data.general.ProfilePicture @AddedIn(GI_2_7_0) @ProtoModel internal interface ActivityRecvGiftData { var giftNumMap: Map<Int, Int> var nickname: String var profilePicture: ProfilePicture var remarkName: String var uid: Int }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
546
anime-game-multi-proto
MIT License
src/main/kotlin/no/nav/arbeidsgiver/sykefravarsstatistikk/api/applikasjon/eksportering/EksporteringMetadataVirksomhetService.kt
navikt
201,881,144
false
{"Kotlin": 796531, "Shell": 1600, "Dockerfile": 213}
package no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.eksportAvSykefraværsstatistikk import arrow.core.Either import arrow.core.left import arrow.core.right import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.Bransjeprogram import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.Næringskode import no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.fellesdomene.ÅrstallOgKvartal import no.nav.arbeidsgiver.sykefravarsstatistikk.api.config.KafkaTopic import no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.database.VirksomhetMetadataRepository import no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.kafka.KafkaClient import no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.kafka.dto.MetadataVirksomhetKafkamelding import no.nav.arbeidsgiver.sykefravarsstatistikk.api.infrastruktur.kafka.dto.SektorKafkaDto import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class EksporteringMetadataVirksomhetService( private val virksomhetMetadataRepository: VirksomhetMetadataRepository, private val kafkaClient: KafkaClient, ) { private val log: Logger = LoggerFactory.getLogger(this::class.java) fun eksporterMetadataVirksomhet(årstallOgKvartal: ÅrstallOgKvartal): Either<FantIkkeData, Unit> { log.info( "Starter eksportering av metadata (virksomhet) for årstall '{}' og kvartal '{}' på topic '{}'.", årstallOgKvartal.årstall, årstallOgKvartal.kvartal, KafkaTopic.SYKEFRAVARSSTATISTIKK_METADATA_V1.navn ) val metadataVirksomhet = virksomhetMetadataRepository.hentVirksomhetMetadata(årstallOgKvartal) if (metadataVirksomhet.isEmpty()) { return FantIkkeData.left() } metadataVirksomhet.forEach { virksomhet -> try { val metadataVirksomhetKafkamelding = MetadataVirksomhetKafkamelding( virksomhet.orgnr, virksomhet.årstallOgKvartal, virksomhet.primærnæring, virksomhet.primærnæringskode, Bransjeprogram.finnBransje(Næringskode(virksomhet.primærnæringskode)), SektorKafkaDto.fraDomene(virksomhet.sektor) ) kafkaClient.sendMelding( metadataVirksomhetKafkamelding, KafkaTopic.SYKEFRAVARSSTATISTIKK_METADATA_V1, ) } catch (ex: Exception) { log.error( "Utsending av metadata for virksomhet med orgnr '{}' feilet: '{}'", virksomhet.orgnr, ex.message ) throw ex } } log.info( "Fullført eksportering av metadata (virksomhet) for årstall '{}' og kvartal '{}' på topic '{}'.", årstallOgKvartal.årstall, årstallOgKvartal.kvartal, KafkaTopic.SYKEFRAVARSSTATISTIKK_METADATA_V1.navn ) return Unit.right() } object FantIkkeData }
2
Kotlin
2
0
fd3e4795c206dd0565fb8fc968504f0df5acae09
3,145
sykefravarsstatistikk-api
MIT License
app/src/main/java/com/example/health/ApolloActivity.kt
sachinraj-264
280,628,001
false
{"Kotlin": 34455}
package com.example.health import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import android.widget.PopupMenu import android.widget.Toast import kotlinx.android.synthetic.main.activity_apollo.* import kotlinx.android.synthetic.main.activity_msr.* class ApolloActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_apollo) locationAp.setOnClickListener{ var loc = Intent(Intent.ACTION_VIEW, Uri.parse("geo:12.8960,77.5995")) startActivity(loc) } emailAp.setOnClickListener{ var mail = Intent(Intent.ACTION_SEND, Uri.parse("mailto:[email protected]")) startActivity(mail) } callAp.setOnClickListener{ var call = Intent(Intent.ACTION_DIAL, Uri.parse("tel:1860-500-1066")) startActivity(call) } ApMed.setOnClickListener { val popMenu = PopupMenu(this,ApMed) popMenu.menuInflater.inflate(R.menu.ap_pop1,popMenu.menu) popMenu.setOnMenuItemClickListener(object: PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem?):Boolean{ when(item!!.itemId){ R.id.generalMed -> Toast.makeText(this@ApolloActivity,"General Medicine", Toast.LENGTH_SHORT).show() R.id.elderlyCare -> Toast.makeText(this@ApolloActivity,"Elderly Care", Toast.LENGTH_SHORT).show() R.id.renalDiseases -> Toast.makeText(this@ApolloActivity,"Renal Diseases", Toast.LENGTH_SHORT).show() R.id.hematology -> Toast.makeText(this@ApolloActivity,"Hematology", Toast.LENGTH_SHORT).show() R.id.rheumatology -> Toast.makeText(this@ApolloActivity,"Rheumatology", Toast.LENGTH_SHORT).show() } return true } }) popMenu.show() } ApSurg.setOnClickListener { val popMenu = PopupMenu(this,ApSurg) popMenu.menuInflater.inflate(R.menu.ap_pop2,popMenu.menu) popMenu.setOnMenuItemClickListener(object: PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem?):Boolean{ when(item!!.itemId){ R.id.colorectalSurgery -> Toast.makeText(this@ApolloActivity,"Colorectal Surgery", Toast.LENGTH_SHORT).show() R.id.genSurgery -> Toast.makeText(this@ApolloActivity,"General and GI Surgery", Toast.LENGTH_SHORT).show() R.id.uroSurgery -> Toast.makeText(this@ApolloActivity,"Urology and Andrology", Toast.LENGTH_SHORT).show() R.id.vascular -> Toast.makeText(this@ApolloActivity,"Vascular and Endovascular Surgery", Toast.LENGTH_SHORT).show() } return true } }) popMenu.show() } ApWomen.setOnClickListener { val popMenu = PopupMenu(this,ApWomen) popMenu.menuInflater.inflate(R.menu.ap_pop3,popMenu.menu) popMenu.setOnMenuItemClickListener(object: PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem?):Boolean{ when(item!!.itemId){ R.id.gynecology -> Toast.makeText(this@ApolloActivity,"Obstetrics and Gynecology", Toast.LENGTH_SHORT).show() } return true } }) popMenu.show() } ApCos.setOnClickListener { val popMenu = PopupMenu(this,ApCos) popMenu.menuInflater.inflate(R.menu.ap_pop4,popMenu.menu) popMenu.setOnMenuItemClickListener(object: PopupMenu.OnMenuItemClickListener { override fun onMenuItemClick(item: MenuItem?):Boolean{ when(item!!.itemId){ R.id.derma -> Toast.makeText(this@ApolloActivity,"Dermatology", Toast.LENGTH_SHORT).show() R.id.plasSurgery -> Toast.makeText(this@ApolloActivity,"Plastic Surgery", Toast.LENGTH_SHORT).show() } return true } }) popMenu.show() } } }
0
Kotlin
0
0
d14b1ccd4a578b1a943e72b260fcdbbaae90b3d5
4,656
Arogya-Kavacha
MIT License
core/src/main/kotlin/dev/komu/kraken/model/item/food/Corpse.kt
komu
83,556,775
false
{"Kotlin": 225797}
package dev.komu.kraken.model.item.food import dev.komu.kraken.model.creature.Player import dev.komu.kraken.model.item.Food import dev.komu.kraken.model.item.Taste import dev.komu.kraken.utils.Expression import dev.komu.kraken.utils.rollDie class Corpse(name: String): Food(name) { var poisonDamage: Expression? = null var taste = Taste.CHICKEN override fun onEatenBy(eater: Player) { eater.decreaseHungriness(effectiveness) val poisonDamage = calculatePoisonDamage() if (poisonDamage > 0) { eater.message("This %s tastes terrible, it must have been poisonous!", title) eater.takeDamage(poisonDamage, eater, cause = "poisonous corpse") } else { eater.message("This %s tastes %s.", title, taste) } } private fun calculatePoisonDamage(): Int { val baseDamage = poisonDamage?.evaluate() ?: 0 return if (baseDamage > 0) rollDie(baseDamage * level) else 0 } }
0
Kotlin
0
0
680362d8e27c475b4ef1e2d13b67cb87f67249f6
1,008
kraken
Apache License 2.0
core/src/main/kotlin/dev/komu/kraken/model/item/food/Corpse.kt
komu
83,556,775
false
{"Kotlin": 225797}
package dev.komu.kraken.model.item.food import dev.komu.kraken.model.creature.Player import dev.komu.kraken.model.item.Food import dev.komu.kraken.model.item.Taste import dev.komu.kraken.utils.Expression import dev.komu.kraken.utils.rollDie class Corpse(name: String): Food(name) { var poisonDamage: Expression? = null var taste = Taste.CHICKEN override fun onEatenBy(eater: Player) { eater.decreaseHungriness(effectiveness) val poisonDamage = calculatePoisonDamage() if (poisonDamage > 0) { eater.message("This %s tastes terrible, it must have been poisonous!", title) eater.takeDamage(poisonDamage, eater, cause = "poisonous corpse") } else { eater.message("This %s tastes %s.", title, taste) } } private fun calculatePoisonDamage(): Int { val baseDamage = poisonDamage?.evaluate() ?: 0 return if (baseDamage > 0) rollDie(baseDamage * level) else 0 } }
0
Kotlin
0
0
680362d8e27c475b4ef1e2d13b67cb87f67249f6
1,008
kraken
Apache License 2.0
PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/ui/MainState.kt
android
41,576,069
false
null
/* * Copyright 2022 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.sample.subscriptionscodelab.ui import com.android.billingclient.api.ProductDetails import com.android.billingclient.api.Purchase data class MainState( val hasRenewableBasic: Boolean? = false, val hasPrepaidBasic: Boolean? = false, val hasRenewablePremium: Boolean? = false, val hasPrepaidPremium: Boolean? = false, val basicProductDetails: ProductDetails? = null, val premiumProductDetails: ProductDetails? = null, val purchases: List<Purchase>? = null, )
218
null
1336
2,379
047d2eb8eef8fe32ec07a115580faea8eb865e43
1,096
play-billing-samples
Apache License 2.0
src/main/kotlin/com/skillw/pouvoir/api/feature/database/ContainerHolder.kt
Glom-c
396,683,163
false
null
package com.skillw.pouvoir.api.feature.database import com.skillw.pouvoir.api.plugin.map.LowerKeyMap /** * @className ContainerHolder * * 容器持有者,负责管理一种特定类型的容器 * * 包括此类型容器的创建 销毁 * * @author Glom * @date 2023/1/20 17:26 Copyright 2023 user. All rights reserved. */ abstract class ContainerHolder<C : BaseContainer> : LowerKeyMap<C>() { var userContainerSyncTime: Long = 360000 /** * Create table * * @param tableName * @return */ protected abstract fun createContainer(tableName: String, userKey: Boolean = false): C fun container(tableName: String, userKey: Boolean = false): C { return computeIfAbsent(tableName) { this.createContainer(tableName, userKey).apply { onEnable() } } } protected abstract fun disconnect() fun disconnectAll() { values.forEach(BaseContainer::onDisable) disconnect() } }
3
null
8
9
35b93485f5f4c2d5c534a2765ff7cfb8f34dd737
889
Pouvoir
MIT License
lib/src/main/java/com/evdayapps/madassistant/clientlib/permission/PermissionManagerImpl.kt
Evdayapps
329,658,422
false
{"Kotlin": 110446}
package com.evdayapps.madassistant.clientlib.permission import android.util.Log import com.evdayapps.madassistant.clientlib.utils.Logger import com.evdayapps.madassistant.clientlib.utils.matches import com.evdayapps.madassistant.common.cipher.MADAssistantCipher import com.evdayapps.madassistant.common.models.exceptions.ExceptionModel import com.evdayapps.madassistant.common.models.networkcalls.NetworkCallLogModel import com.evdayapps.madassistant.common.models.permissions.MADAssistantPermissions import org.json.JSONException import org.json.JSONObject import java.io.InvalidObjectException import java.util.regex.Pattern class PermissionManagerImpl( private val cipher: MADAssistantCipher, private val logger: Logger? = null, ) : PermissionManager { private val TAG = "PermissionManagerImpl" private var permissions: MADAssistantPermissions? = null private var patternNetworkCallMethod: Pattern? = null private var patternNetworkCallUrl: Pattern? = null private var patternAnalyticsDestination: Pattern? = null private var patternAnalyticsName: Pattern? = null private var patternAnalyticsParams: Pattern? = null private var patternGenericLogsTag: Pattern? = null private var patternGenericLogsMessage: Pattern? = null private var patternExceptionsType: Pattern? = null private var patternExceptionsMessage: Pattern? = null /** * This function is used to set the authorization token for the system. * @param string The encrypted authorization token * @param deviceIdentifier is the identifier for the device. * @return an error message if an error is encountered, else null */ override fun setAuthToken(string: String?, deviceIdentifier: String): String? { // Check if the input string is null or blank. return when { string.isNullOrBlank() -> "AuthToken was null or blank" else -> try { // Decrypt the input string and parse it into a JSON object. val deciphered = cipher.decrypt(string) val json = JSONObject(deciphered!!) val permissions = MADAssistantPermissions(json) // Store the permissions object in a class property. this.permissions = permissions logger?.i(TAG, "permissions: $permissions") // Check device identifier if (!isWhitelistedDevice(deviceIdentifier)) { throw Exception("Invalid device identifier") } // Set the permission patterns based on the permissions object. setPermissionPatterns(permissions) // Return null if there are no errors. null } catch (ex: JSONException) { // Return an error message if the JSON parsing fails. "Authtoken decryption failed ${ex.message}" } catch (ex: InvalidObjectException) { // Return an error message if the auth token is invalid. "Invalid authToken" } catch (ex: Exception) { // Return an error message for any other exceptions. "Unknown exception processing authToken: ${ex.message}" } } } /** * Checks if the id of the current device is in the whitelist * @return true if device id is in the whitelist */ private fun isWhitelistedDevice(deviceId: String): Boolean { // Check if the device id is in the whitelist // Returns false if no permissions/deviceIds specified return permissions?.deviceId?.split(",")?.contains(deviceId) ?: false } private fun setPermissionPatterns(permissions: MADAssistantPermissions) { val flags = Pattern.MULTILINE and Pattern.CASE_INSENSITIVE listOf( permissions.networkCalls.filterMethod to ::patternNetworkCallMethod, permissions.networkCalls.filterUrl to ::patternNetworkCallUrl, permissions.analytics.filterDestination to ::patternAnalyticsDestination, permissions.analytics.filterEventName to ::patternAnalyticsName, permissions.analytics.filterParamData to ::patternAnalyticsParams, permissions.genericLogs.filterTag to ::patternGenericLogsTag, permissions.genericLogs.filterMessage to ::patternGenericLogsMessage, permissions.exceptions.filterType to ::patternExceptionsType, permissions.exceptions.filterMessage to ::patternExceptionsMessage ).forEach { (value, property) -> if (!value.isNullOrBlank()) { property.set(value.toPattern(flags)) } } } /** * The base logging check * This checks the following: * - Have we got a permission model from the repository? * - Is the current time within the timestamps? * @since 0.0.1 * * @return True if logging is enabled and timestamps check out, else false */ override fun isLoggingEnabled(): Boolean = permissions?.let { perms -> val start = perms.timestampStart ?: 0 val end = perms.timestampEnd ?: Long.MAX_VALUE System.currentTimeMillis() in start until end } ?: false /** * Should api call logs be encrypted? * @return true if read is false */ override fun shouldEncryptLogs(): Boolean = permissions?.encrypted == true /** * Test if [networkCallLogModel] should be logged * Checks the api permissions within permission model * * @param networkCallLogModel The api call to log * @return true or false */ override fun shouldLogNetworkCall(networkCallLogModel: NetworkCallLogModel): Boolean { if (!isLoggingEnabled() || (permissions?.networkCalls?.enabled != true)) { return false } val chkMethod = patternNetworkCallMethod?.matches(networkCallLogModel.request?.method) ?: true val chkUrl = patternNetworkCallUrl?.matches(networkCallLogModel.request?.url) ?: true return chkMethod && chkUrl } /** * Some api call headers need to be redacted to avoid leaks of confidential information */ override fun shouldRedactNetworkHeader(header: String): Boolean { return permissions?.networkCalls?.redactHeaders?.contains(header) ?: false } /** * Test if [throwable] should be logged to the repository */ override fun shouldLogException(throwable: Throwable): Boolean { if (!isLoggingEnabled() || (permissions?.exceptions?.enabled != true)) { return false } val chkType = patternExceptionsType?.matches(throwable.javaClass.simpleName) ?: true val chkMessage = patternExceptionsMessage?.matches(throwable.message) ?: true return chkType && chkMessage } override fun shouldLogException(exception: ExceptionModel): Boolean { if (!isLoggingEnabled() || (permissions?.exceptions?.enabled != true)) { return false } val chkType = patternExceptionsType?.matches(exception.stackTrace.firstOrNull()?.className) ?: true val chkMessage = patternExceptionsMessage?.matches(exception.message) ?: true return chkType && chkMessage } // region Analytics override fun shouldLogAnalytics( destination: String, eventName: String, data: Map<String, Any?> ): Boolean { if (!isLoggingEnabled() || permissions?.analytics?.enabled != true) { return false } val chkDest = patternAnalyticsDestination?.matches(destination) ?: true val checkName = patternAnalyticsName?.matches(eventName) ?: true val checkParams = patternAnalyticsParams?.matches(data.toString()) ?: true return chkDest && checkName && checkParams } // endregion Analytics /** * Determine if logging should occur for generic logs * * @param type int representing the log type (e.g. Log.VERBOSE) * @param tag String representing the log tag * @param message String representing the log message * * @return Boolean indicating if the log should occur */ override fun shouldLogGenericLog(type: Int, tag: String, message: String): Boolean { if (!isLoggingEnabled() || permissions?.genericLogs?.enabled != true) { return false } val subtypeEnabled = when (type) { Log.VERBOSE -> permissions?.genericLogs?.logVerbose == true Log.DEBUG -> permissions?.genericLogs?.logDebug == true Log.WARN -> permissions?.genericLogs?.logWarning == true Log.ERROR -> permissions?.genericLogs?.logError == true Log.INFO -> permissions?.genericLogs?.logInfo == true else -> false } if (!subtypeEnabled) { return false } val checkTag = patternGenericLogsTag?.matches(tag) ?: true val checkMessage = patternGenericLogsMessage?.matches(message) ?: true return checkTag && checkMessage } // endregion Generic Logs }
0
Kotlin
0
5
6862cfca259ef21726a8e622ddd8294d0be09089
9,172
madassistant-clientsdk
Apache License 2.0
kjob-core/src/test/kotlin/it/justwrote/kjob/internal/scheduler/JobCleanupSchedulerSpec.kt
justwrote
260,458,357
false
null
package it.justwrote.kjob.internal.scheduler import io.kotest.core.spec.style.ShouldSpec import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import it.justwrote.kjob.job.JobStatus.* import it.justwrote.kjob.repository.JobRepository import it.justwrote.kjob.repository.LockRepository import kotlinx.coroutines.flow.asFlow import java.util.* class JobCleanupSchedulerSpec : ShouldSpec() { init { val otherKjobId = UUID.randomUUID() val otherKjobId2 = UUID.randomUUID() val kjobId = UUID.randomUUID() val je1 = sj(id = "1", status = RUNNING, kjobId = kjobId) val je2 = sj(id = "2", status = RUNNING, kjobId = otherKjobId) val je3 = sj(id = "3", status = ERROR, kjobId = kjobId) val je4 = sj(id = "4", status = ERROR, kjobId = otherKjobId2) val je5 = sj(id = "5", status = ERROR) val all = listOf( je1, je2, je3, je4, je5 ) should("find next jobs for clean up") { val jobRepoMock = mockk<JobRepository>() val lockRepoMock = mockk<LockRepository>() val testee = JobCleanupScheduler( newScheduler(), 10000, jobRepoMock, lockRepoMock, 10 ) coEvery { lockRepoMock.exists(kjobId) } returns true coEvery { lockRepoMock.exists(otherKjobId) } returns false coEvery { lockRepoMock.exists(otherKjobId2) } returns true coEvery { jobRepoMock.findNext(emptySet(), setOf(SCHEDULED, RUNNING, ERROR), 10) } returns all.asFlow() coEvery { jobRepoMock.reset(je2.id, je2.kjobId) } returns true coEvery { jobRepoMock.reset(je5.id, je5.kjobId) } returns true testee.start() coVerify(timeout = 50) { jobRepoMock.findNext(emptySet(), setOf(SCHEDULED, RUNNING, ERROR), 10) } coVerify(timeout = 50) { lockRepoMock.exists(kjobId) } coVerify(timeout = 50) { lockRepoMock.exists(otherKjobId) } coVerify(timeout = 50) { jobRepoMock.reset(je2.id, je2.kjobId) } coVerify(timeout = 50) { jobRepoMock.reset(je5.id, je5.kjobId) } testee.shutdown() } } }
2
null
9
67
880b175516ce5f3e9edbb0b6fe7b50820c332026
2,328
kjob
Apache License 2.0
openai/clients-retrofit2/src/main/kotlin/io/bluetape4k/openai/clients/retrofit2/sync/CompletionSyncApi.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.openai.clients.retrofit2.sync import io.bluetape4k.openai.api.models.completion.CompletionRequest import io.bluetape4k.openai.api.models.completion.CompletionResult import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.POST import retrofit2.http.Streaming interface CompletionSyncApi { companion object { internal const val COMPLETIONS_PATH = "/v1/completions" } @POST(COMPLETIONS_PATH) fun createCompletion(@Body request: CompletionRequest): CompletionResult @Streaming @POST(COMPLETIONS_PATH) fun createCompletionStream(@Body request: CompletionRequest): Call<ResponseBody> }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
686
bluetape4k
MIT License
app/src/main/java/com/bernaferrari/changedetection/util/AppGlideModule.kt
bernaferrari
135,081,469
false
{"Kotlin": 423918, "Java": 60461}
package com.bernaferrari.changedetection.util import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule internal class AppGlideModule : AppGlideModule()
22
Kotlin
97
696
4cb31aab20c321421347b3aad4ad86f516f136f0
207
ChangeDetection
Apache License 2.0
back-end/src/main/kotlin/com/apexdevs/backend/web/controller/api/ApiAdminController.kt
sanctuuary
360,515,462
false
null
/* * This program has been developed by students from the bachelor Computer Science at Utrecht University within the Software Project course. * © Copyright Utrecht University (Department of Information and Computing Sciences) */ package com.apexdevs.backend.web.controller.api import com.apexdevs.backend.persistence.RunParametersOperation import com.apexdevs.backend.persistence.TopicOperation import com.apexdevs.backend.persistence.UserOperation import com.apexdevs.backend.persistence.database.entity.RunParameters import com.apexdevs.backend.persistence.database.entity.Topic import com.apexdevs.backend.persistence.database.entity.UserRequest import com.apexdevs.backend.persistence.exception.RunParametersNotFoundException import com.apexdevs.backend.persistence.exception.UserApproveRequestNotFoundException import com.apexdevs.backend.persistence.exception.UserNotFoundException import com.apexdevs.backend.web.controller.entity.runparameters.RunParametersDetails import com.apexdevs.backend.web.controller.entity.runparameters.RunParametersUploadRequest import com.apexdevs.backend.web.controller.entity.topic.TopicUploadRequest import com.apexdevs.backend.web.controller.entity.user.AdminApproveRequest import com.apexdevs.backend.web.controller.entity.user.AdminStatusRequest import com.apexdevs.backend.web.controller.entity.user.PendingUserRequestInfo import org.bson.types.ObjectId import org.springframework.http.HttpStatus import org.springframework.security.access.AccessDeniedException import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.security.core.userdetails.User import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import java.util.logging.Logger /** * Handles API calls for admins * all Ajax calls for the admin operations should be made through here */ @RestController @RequestMapping("/api/admin") class ApiAdminController(val userOperation: UserOperation, val topicOperation: TopicOperation, val runParametersOperation: RunParametersOperation) { /** * Collect all approval requests from unapproved users * @return: A list of requests, each containing (id, email, display name, motivation, creation date) */ @ResponseStatus(HttpStatus.OK) @GetMapping("/pending-requests") fun getAllUnapprovedUsers(@AuthenticationPrincipal admin: User): List<PendingUserRequestInfo> { try { // check if current user is admin if (!userOperation.userIsAdmin(admin.username)) throw AccessDeniedException("User is not admin") // returns list of all pending requests (which is an empty list in case there are none) return userOperation.getPendingRequests() } catch (exc: Exception) { when (exc) { is UserNotFoundException -> throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Admin user not found", exc) is AccessDeniedException -> throw ResponseStatusException(HttpStatus.FORBIDDEN, "User is not admin", exc) else -> throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "", exc) } } } /** * Approve or decline user registration completion by admin */ @ResponseStatus(HttpStatus.OK) @PostMapping("/approval") fun adminUserApproval(@AuthenticationPrincipal admin: User, @RequestBody adminApproveRequest: AdminApproveRequest) { try { // check if current user is admin if (!userOperation.userIsAdmin(admin.username)) throw AccessDeniedException("User is not admin") // call approve or deny depending on request, throw exception if request specifies otherwise when (adminApproveRequest.status) { UserRequest.Approved -> userOperation.approveUser(adminApproveRequest.email, adminApproveRequest.requestId) UserRequest.Denied -> userOperation.declineUser(adminApproveRequest.email, adminApproveRequest.requestId) else -> { throw IllegalArgumentException("Admin can only approve or deny users") } } log.info("Admin: ${admin.username} ${adminApproveRequest.status} user: ${adminApproveRequest.email}") } catch (exc: Exception) { when (exc) { is UserNotFoundException, is UserApproveRequestNotFoundException -> throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid AdminApproveRequest sent", exc) is AccessDeniedException -> throw ResponseStatusException(HttpStatus.FORBIDDEN, "User is not admin", exc) is IllegalArgumentException -> throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Admin can only approve or deny users", exc) else -> throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "", exc) } } } /** * Function for handling the topic uploads coming from the front-end */ @ResponseStatus(HttpStatus.CREATED) @PostMapping("/topic/upload") fun uploadTopic( @AuthenticationPrincipal admin: User, @RequestBody topicUploadRequest: TopicUploadRequest ) { try { if (!userOperation.userIsAdmin(admin.username)) throw AccessDeniedException("User: ${admin.username} not allowed to access this route") topicOperation.createTopic(Topic(topicUploadRequest.name)) log.info("Admin: ${admin.username} created new topic: ${topicUploadRequest.name}") } catch (exc: Exception) { when (exc) { is AccessDeniedException -> throw ResponseStatusException(HttpStatus.UNAUTHORIZED, exc.message, exc) else -> throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "", exc) } } } /** * Updates the requested run parameters by replacing them with the given run parameters * @param admin The (possibly admin) user who calls this endpoint * @param id The id of the run parameters to update * @param runParametersUploadRequest The data to update the run parameters with * @return The updated or created run parameters */ @ResponseStatus(HttpStatus.OK) @PutMapping("/runparameters/{id}") fun updateRunParameterLimits( @AuthenticationPrincipal admin: User, @PathVariable id: ObjectId, @RequestBody runParametersUploadRequest: RunParametersUploadRequest ): RunParametersDetails { try { // Check if the user is an administrator if (!userOperation.userIsAdmin(admin.username)) throw AccessDeniedException("User: ${admin.username} is not allowed to access this route") val user = userOperation.getByEmail(admin.username) val newRunParameters = RunParameters( id, runParametersUploadRequest.minLength, runParametersUploadRequest.maxLength, runParametersUploadRequest.maxDuration, runParametersUploadRequest.solutions ) return try { // Attempt to get the existing run parameters to check if they already exist runParametersOperation.getRunParameters(id) // Update the existing run parameters val updated = runParametersOperation.updateRunParameters(newRunParameters) log.info("Run parameters with id: ${newRunParameters.id} were updated by ${user.displayName}") runParametersOperation.getRunParametersDetails(updated) } catch (exception: RunParametersNotFoundException) { // Run parameters did not exist, add a new entry in the database val created = runParametersOperation.createRunParameters(newRunParameters) log.info("Run parameters with id: ${newRunParameters.id} were created by ${user.displayName}") runParametersOperation.getRunParametersDetails(created) } } catch (exc: Exception) { when (exc) { is AccessDeniedException -> throw ResponseStatusException(HttpStatus.UNAUTHORIZED, exc.message, exc) else -> throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "", exc) } } } /** * Change the admin status of a user. */ @ResponseStatus(HttpStatus.OK) @PostMapping("/adminstatus") fun setUserAdminStatus(@AuthenticationPrincipal admin: User, @RequestBody adminStatusRequest: AdminStatusRequest) { try { // Check if the user is an administrator if (!userOperation.userIsAdmin(admin.username)) throw AccessDeniedException("User: ${admin.username} is not allowed to access this route") userOperation.setUserAdminStatus(adminStatusRequest.userId, adminStatusRequest.adminStatus) } catch (exc: Exception) { when (exc) { is AccessDeniedException -> throw ResponseStatusException(HttpStatus.UNAUTHORIZED, exc.message, exc) is UserNotFoundException -> throw ResponseStatusException(HttpStatus.BAD_REQUEST, exc.message, exc) else -> throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "", exc) } } } companion object { val log: Logger = Logger.getLogger("ApiAdminController_Logger") } }
0
TypeScript
0
2
59611f01ff7bc89d7971b26f0354126e7bcde2d3
10,254
APE-Web
Apache License 2.0
src/test/kotlin/no/nav/fia/arbeidsgiver/sporreundersokelse/api/vert/SpørreundersøkelseVertTest.kt
navikt
644,356,194
false
{"Kotlin": 167056, "Dockerfile": 214}
package no.nav.fia.arbeidsgiver.sporreundersokelse.api.vert import HEADER_VERT_ID import io.kotest.assertions.shouldFail import io.kotest.inspectors.forAll import io.kotest.matchers.collections.shouldContainInOrder import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.ktor.client.request.header import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import kotlinx.coroutines.runBlocking import no.nav.fia.arbeidsgiver.helper.* import no.nav.fia.arbeidsgiver.helper.TestContainerHelper.Companion.fiaArbeidsgiverApi import no.nav.fia.arbeidsgiver.helper.TestContainerHelper.Companion.kafka import no.nav.fia.arbeidsgiver.konfigurasjon.KafkaTopics import no.nav.fia.arbeidsgiver.sporreundersokelse.api.deltaker.hentSpørsmålITema import no.nav.fia.arbeidsgiver.sporreundersokelse.api.dto.IdentifiserbartSpørsmål import no.nav.fia.arbeidsgiver.sporreundersokelse.api.vert.dto.TemaOversiktDto import no.nav.fia.arbeidsgiver.sporreundersokelse.api.vert.dto.TemaStatus import no.nav.fia.arbeidsgiver.sporreundersokelse.domene.StengTema import no.nav.fia.arbeidsgiver.sporreundersokelse.kafka.dto.SpørreundersøkelseDto import org.junit.After import org.junit.Before import java.util.* import kotlin.test.Test class SpørreundersøkelseVertTest { private val spørreundersøkelseHendelseKonsument = kafka.nyKonsument(topic = KafkaTopics.SPØRREUNDERSØKELSE_HENDELSE) @Before fun setUp() { spørreundersøkelseHendelseKonsument.subscribe(mutableListOf(KafkaTopics.SPØRREUNDERSØKELSE_HENDELSE.navnMedNamespace)) } @After fun tearDown() { spørreundersøkelseHendelseKonsument.unsubscribe() spørreundersøkelseHendelseKonsument.close() } val TEMA_ID_FOR_REDUSERE_SYKEFRAVÆR = 1 @Test fun `skal ikke kunne laste vertssider uten azure-token`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { fiaArbeidsgiverApi.performGet( url = "$VERT_BASEPATH/$spørreundersøkelseId/antall-deltakere", ) { header(HEADER_VERT_ID, spørreundersøkelseDto.vertId) }.status shouldBe HttpStatusCode.Unauthorized } } @Test fun `skal ikke kunne laste vertssider uten gyldig scopet azure-token`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { fiaArbeidsgiverApi.performGet( url = "$VERT_BASEPATH/$spørreundersøkelseId/antall-deltakere", ) { header(HEADER_VERT_ID, spørreundersøkelseDto.vertId) header( HttpHeaders.Authorization, TestContainerHelper.authServer.issueToken( issuerId = "azure", audience = "azure:fia-arbeidsgiver-frontend" ).serialize() ) }.status shouldBe HttpStatusCode.Unauthorized } } @Test fun `vertssider skal ikke kunne hentes uten gyldig vertsId`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { fiaArbeidsgiverApi.vertHenterAntallDeltakere( vertId = spørreundersøkelseDto.vertId, spørreundersøkelseId = spørreundersøkelseDto.spørreundersøkelseId ) shouldBe 0 shouldFail { fiaArbeidsgiverApi.vertHenterAntallDeltakere( vertId = UUID.randomUUID().toString(), spørreundersøkelseId = spørreundersøkelseDto.spørreundersøkelseId ) } } } @Test fun `vert skal kunne hente antall deltakere i en undersøkelse`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { fiaArbeidsgiverApi.vertHenterAntallDeltakere( vertId = spørreundersøkelseDto.vertId, spørreundersøkelseId = spørreundersøkelseDto.spørreundersøkelseId ) shouldBe 0 val antallDeltakere = 5 for (deltaker in 1..5) fiaArbeidsgiverApi.bliMed(spørreundersøkelseId = spørreundersøkelseId) fiaArbeidsgiverApi.vertHenterAntallDeltakere( vertId = spørreundersøkelseDto.vertId, spørreundersøkelseId = spørreundersøkelseDto.spørreundersøkelseId ) shouldBe antallDeltakere } } @Test fun `vert skal kunne få ut oversikt over alle temaer i en spørreundersøkelse`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { val temaOversikt = fiaArbeidsgiverApi.hentTemaoversikt(spørreundersøkelseDto) temaOversikt shouldHaveSize spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.size temaOversikt shouldContainInOrder spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.mapIndexed { index, it -> TemaOversiktDto( temaId = it.temaId, tittel = it.temanavn.name, del = index + 1, temanavn = it.temanavn, beskrivelse = it.beskrivelse, introtekst = it.introtekst, status = if (it.temaId == spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first().temaId) TemaStatus.ÅPNET else TemaStatus.IKKE_ÅPNET, førsteSpørsmålId = it.spørsmålOgSvaralternativer.first().id ) } } } @Test fun `vert skal kunne hente riktig temastatus når man har åpnet alle spørsmål i tema 1 men ikke noen i tema 2`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { val førsteTema = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first() førsteTema.spørsmålOgSvaralternativer.forEach { spørreundersøkelseDto.åpneSpørsmål( spørsmål = IdentifiserbartSpørsmål( temaId = førsteTema.temaId, spørsmålId = it.id ), ) } val temaOversikt = fiaArbeidsgiverApi.hentTemaoversikt(spørreundersøkelseDto) temaOversikt shouldHaveSize spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.size temaOversikt shouldContainInOrder spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.mapIndexed { index, it -> TemaOversiktDto( temaId = it.temaId, tittel = it.temanavn.name, del = index + 1, temanavn = it.temanavn, beskrivelse = it.beskrivelse, introtekst = it.introtekst, status = if (it.temaId == førsteTema.temaId) TemaStatus.ALLE_SPØRSMÅL_ÅPNET else TemaStatus.ÅPNET, førsteSpørsmålId = it.spørsmålOgSvaralternativer.first().id ) } } } @Test fun `vert skal kunne hente riktig temastatus når man har åpnet alle spørsmål alle temaer`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.forEach { tema -> tema.spørsmålOgSvaralternativer.forEach { spørreundersøkelseDto.åpneSpørsmål( spørsmål = IdentifiserbartSpørsmål( temaId = tema.temaId, spørsmålId = it.id ), ) } } val temaOversikt = fiaArbeidsgiverApi.hentTemaoversikt(spørreundersøkelseDto) temaOversikt shouldHaveSize spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.size temaOversikt shouldContainInOrder spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.mapIndexed { index, it -> TemaOversiktDto( temaId = it.temaId, tittel = it.temanavn.name, del = index + 1, temanavn = it.temanavn, beskrivelse = it.beskrivelse, introtekst = it.introtekst, status = TemaStatus.ALLE_SPØRSMÅL_ÅPNET, førsteSpørsmålId = it.spørsmålOgSvaralternativer.first().id ) } } } @Test fun `vert skal kunne få ut oversikt over ett tema i en spørreundersøkelse`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) val temaRedusereSykefravær = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first { it.temaId == TEMA_ID_FOR_REDUSERE_SYKEFRAVÆR } runBlocking { val temaOversikt = fiaArbeidsgiverApi.hentTemaoversiktForEttTema( spørreundersøkelse = spørreundersøkelseDto, temaId = TEMA_ID_FOR_REDUSERE_SYKEFRAVÆR ) temaOversikt shouldNotBe null temaOversikt.temanavn shouldBe temaRedusereSykefravær.temanavn temaOversikt.del shouldBe 2 temaOversikt.beskrivelse shouldBe temaRedusereSykefravær.beskrivelse temaOversikt.introtekst shouldBe temaRedusereSykefravær.introtekst temaOversikt.førsteSpørsmålId shouldBe temaRedusereSykefravær.spørsmålOgSvaralternativer.first().id } } @Test fun `vert skal kunne hente spørsmålsoversikt`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { val tema = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first() val spørsmål = tema.spørsmålOgSvaralternativer.first() val spørsmålsoversiktDto = spørreundersøkelseDto.åpneSpørsmål( spørsmål = IdentifiserbartSpørsmål( temaId = tema.temaId, spørsmålId = spørsmål.id ) ) spørsmålsoversiktDto.spørsmålTekst shouldBe spørsmål.spørsmål spørsmålsoversiktDto.svaralternativer shouldContainInOrder spørsmål.svaralternativer spørsmålsoversiktDto.nesteSpørsmål?.spørsmålId shouldBe tema.spørsmålOgSvaralternativer[1].id spørsmålsoversiktDto.nesteSpørsmål?.temaId shouldBe tema.temaId spørsmålsoversiktDto.temanummer shouldBe 1 spørsmålsoversiktDto.antallTema shouldBe spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.size spørsmålsoversiktDto.spørsmålnummer shouldBe 1 spørsmålsoversiktDto.antallSpørsmål shouldBe tema.spørsmålOgSvaralternativer.size } // på siste spørsmål runBlocking { val tema = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.last() val spørsmål = tema.spørsmålOgSvaralternativer.last() val spørsmålsoversiktDto = spørreundersøkelseDto.åpneSpørsmål( spørsmål = IdentifiserbartSpørsmål( temaId = tema.temaId, spørsmålId = spørsmål.id ) ) spørsmålsoversiktDto.spørsmålTekst shouldBe spørsmål.spørsmål spørsmålsoversiktDto.svaralternativer shouldContainInOrder spørsmål.svaralternativer spørsmålsoversiktDto.nesteSpørsmål shouldBe null } } @Test fun `vert skal kunne vite hvor mange som har svart på ett spørsmål`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { val førsteSpørsmål = IdentifiserbartSpørsmål( temaId = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first().temaId, spørsmålId = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first().spørsmålOgSvaralternativer.first().id ) spørreundersøkelseDto.åpneSpørsmål(spørsmål = førsteSpørsmål) fiaArbeidsgiverApi.hentAntallSvarForSpørsmål( spørsmål = førsteSpørsmål, spørreundersøkelse = spørreundersøkelseDto ) shouldBe 0 (1..5).forEach { antallSvar -> val bliMedDTO = fiaArbeidsgiverApi.bliMed(spørreundersøkelseId = spørreundersøkelseId) fiaArbeidsgiverApi.svarPåSpørsmål( spørsmål = førsteSpørsmål, svarIder = listOf(spørreundersøkelseDto.hentSpørsmålITema(førsteSpørsmål).svaralternativer.first().svarId), bliMedDTO = bliMedDTO, ) { kafka.sendAntallSvar( spørreundersøkelseId = spørreundersøkelseId.toString(), spørsmålId = førsteSpørsmål.spørsmålId, antallSvar = antallSvar ) } fiaArbeidsgiverApi.hentAntallSvarForSpørsmål( spørsmål = førsteSpørsmål, spørreundersøkelse = spørreundersøkelseDto ) shouldBe antallSvar } } } @Test fun `vert skal kunne lukke et tema, og det bør resultere i en kafkamelding`() { val spørreundersøkelseId = UUID.randomUUID() val spørreundersøkelseDto = kafka.sendSpørreundersøkelse(spørreundersøkelseId = spørreundersøkelseId) runBlocking { val temaId = spørreundersøkelseDto.temaMedSpørsmålOgSvaralternativer.first().temaId fiaArbeidsgiverApi.stengTema(spørreundersøkelse = spørreundersøkelseDto, temaId = temaId) val stengTema = StengTema(spørreundersøkelseId.toString(), temaId) kafka.ventOgKonsumerKafkaMeldinger(stengTema.tilNøkkel(), spørreundersøkelseHendelseKonsument) { meldinger -> meldinger.forAll { it.toInt() shouldBe temaId } } } } } suspend fun SpørreundersøkelseDto.åpneSpørsmål( spørsmål: IdentifiserbartSpørsmål, ) = fiaArbeidsgiverApi.hentSpørsmålSomVert( spørsmål = spørsmål, spørreundersøkelse = this )
0
Kotlin
0
0
c6f2e8e6f84ed0ca50f6ee0c156ca897c71ec668
15,244
fia-arbeidsgiver
MIT License
app/src/test/java/com/kgurgul/cpuinfo/features/processes/PsProviderTest.kt
kamgurgul
105,620,694
false
null
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.features.processes import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner /** * Tests for [PsProvider] * * @author kgurgul */ @RunWith(MockitoJUnitRunner::class) class PsProviderTest { @Test fun parsePs() { /* Given */ val psProvider = PsProvider() val generatedProcessItems = getProcessItemsList() /* When */ val parsedProcessItems = psProvider.parsePs(getDummyPsOutput()) /* Then */ assertEquals(generatedProcessItems.size, parsedProcessItems.size) assertEquals(generatedProcessItems[0], parsedProcessItems[0]) assertEquals(generatedProcessItems[1], parsedProcessItems[1]) } /** * Generates sample output from ps. It should produce items from [getProcessItemsList] after * parsing */ private fun getDummyPsOutput(): List<String> { val psStringList = ArrayList<String>() psStringList.add("USER NAME PID PPID VSIZE RSS PRIO NICE RTPRI SCHED " + "WCHAN PC") psStringList.add("root 1 0 724 444 20 0 0 0 c02cb2ef " + "0805d376 S /init") psStringList.add("root 2 1 0 0 20 2 0 0 c023edb3 " + "00000000 S kthreadd") return psStringList } /** * Return generated [List] of [ProcessItem] */ private fun getProcessItemsList(): List<ProcessItem> { val processItems = ArrayList<ProcessItem>() val p1 = ProcessItem("/init", "1", "0", "0", "root", "444", "724") val p2 = ProcessItem("kthreadd", "2", "1", "2", "root", "0", "0") processItems.add(p1) processItems.add(p2) return processItems } }
27
null
88
468
c14870ef298bc6be2c1355d36698c355c1f5fc51
2,446
cpu-info
Apache License 2.0
compiler/tests-spec/testData/diagnostics/linked/expressions/when-expression/p-6/neg/1.2.kt
JetBrains
3,432,266
false
null
// SKIP_TXT /* * KOTLIN DIAGNOSTICS SPEC TEST (NEGATIVE) * * SPEC VERSION: 0.1-296 * PLACE: expressions, when-expression -> paragraph 6 -> sentence 1 * NUMBER: 2 * DESCRIPTION: 'When' with bound value and type test condition on the non-type operand of the type checking operator. * HELPERS: classes */ // TESTCASE NUMBER: 1 fun case_1(value_1: Any, <!UNUSED_PARAMETER!>value_2<!>: Int): String { when (value_1) { is <!UNRESOLVED_REFERENCE!>value_2<!> -> return "" } return "" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
509
kotlin
Apache License 2.0
app-android/src/main/java/org/mtransit/android/ui/map/MapViewModel.kt
mtransitapps
24,649,585
false
null
package org.mtransit.android.ui.map import android.location.Location import androidx.collection.ArrayMap import androidx.core.content.edit import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.distinctUntilChanged import androidx.lifecycle.map import androidx.lifecycle.viewModelScope import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import org.mtransit.android.common.repository.LocalPreferenceRepository import org.mtransit.android.commons.MTLog import org.mtransit.android.commons.data.RouteTripStop import org.mtransit.android.commons.pref.liveData import org.mtransit.android.commons.provider.POIProviderContract import org.mtransit.android.data.DataSourceType import org.mtransit.android.data.IAgencyNearbyUIProperties import org.mtransit.android.datasource.DataSourcesRepository import org.mtransit.android.datasource.POIRepository import org.mtransit.android.ui.MTViewModelWithLocation import org.mtransit.android.ui.view.MapViewController.POIMarker import org.mtransit.android.ui.view.common.Event import org.mtransit.android.ui.view.common.PairMediatorLiveData import org.mtransit.android.ui.view.common.QuadrupleMediatorLiveData import org.mtransit.android.ui.view.common.TripleMediatorLiveData import org.mtransit.android.ui.view.common.getLiveDataDistinct import org.mtransit.android.util.containsEntirely import java.util.HashSet import javax.inject.Inject import kotlin.math.max import kotlin.math.min @HiltViewModel class MapViewModel @Inject constructor( private val savedStateHandle: SavedStateHandle, private val dataSourcesRepository: DataSourcesRepository, private val poiRepository: POIRepository, private val lclPrefRepository: LocalPreferenceRepository, ) : MTViewModelWithLocation() { companion object { private val LOG_TAG = MapViewModel::class.java.simpleName internal const val EXTRA_INITIAL_LOCATION = "extra_initial_location" internal const val EXTRA_SELECTED_UUID = "extra_selected_uuid" internal const val EXTRA_INCLUDE_TYPE_ID = "extra_include_type_id" internal const val EXTRA_INCLUDE_TYPE_ID_DEFAULT: Int = -1 } override fun getLogTag(): String = LOG_TAG val initialLocation = savedStateHandle.getLiveDataDistinct<Location?>(EXTRA_INITIAL_LOCATION) fun onInitialLocationSet() { savedStateHandle[EXTRA_INITIAL_LOCATION] = null // set once only } val selectedUUID = savedStateHandle.getLiveDataDistinct<String?>(EXTRA_SELECTED_UUID) fun onSelectedUUIDSet() { savedStateHandle[EXTRA_SELECTED_UUID] = null // set once only (then manage by map controller } private val allTypes = this.dataSourcesRepository.readingAllDataSourceTypes() // #onModulesUpdated val mapTypes = allTypes.map { it.filter { dst -> dst.isMapScreen } } private val includedTypeId = savedStateHandle.getLiveDataDistinct(EXTRA_INCLUDE_TYPE_ID, EXTRA_INCLUDE_TYPE_ID_DEFAULT) .map { if (it < 0) null else it } private val filterTypeIdsPref: LiveData<Set<String>> = lclPrefRepository.pref.liveData( LocalPreferenceRepository.PREFS_LCL_MAP_FILTER_TYPE_IDS, LocalPreferenceRepository.PREFS_LCL_MAP_FILTER_TYPE_IDS_DEFAULT ).distinctUntilChanged() fun saveFilterTypeIdsPref(filterTypeIds: Collection<Int>?) { val newFilterTypeIdStrings: Set<String> = filterTypeIds?.mapTo(HashSet()) { it.toString() } ?: LocalPreferenceRepository.PREFS_LCL_MAP_FILTER_TYPE_IDS_DEFAULT // NULL = EMPTY = ALL (valid) lclPrefRepository.pref.edit { putStringSet(LocalPreferenceRepository.PREFS_LCL_MAP_FILTER_TYPE_IDS, newFilterTypeIdStrings) } } val filterTypeIds: LiveData<Collection<Int>?> = TripleMediatorLiveData(mapTypes, filterTypeIdsPref, includedTypeId).map { (mapTypes, filterTypeIdsPref, includedTypeId) -> makeFilterTypeId(mapTypes, filterTypeIdsPref, includedTypeId) }.distinctUntilChanged() private fun makeFilterTypeId( availableTypes: List<DataSourceType>?, filterTypeIdsPref: Set<String>?, inclTypeId: Int? = null, ): Collection<Int>? { if (filterTypeIdsPref == null || availableTypes == null) { MTLog.d(this, "makeFilterTypeId() > SKIP (no pref or available types") return null } val filterTypeIds = mutableSetOf<Int>() var prefHasChanged = false filterTypeIdsPref.forEach { typeIdString -> try { val type = DataSourceType.parseId(typeIdString.toInt()) if (type == null) { MTLog.d(this, "makeFilterTypeId() > '$typeIdString' not valid") prefHasChanged = true return@forEach } if (!availableTypes.contains(type)) { MTLog.d(this, "makeFilterTypeId() > '$type' not available (in map screen)") prefHasChanged = true return@forEach } filterTypeIds.add(type.id) } catch (e: Exception) { MTLog.w(this, e, "Error while parsing filter type ID '%s'!", typeIdString) prefHasChanged = true } } inclTypeId?.let { includedTypeId -> if (filterTypeIds.isNotEmpty() && !filterTypeIds.contains(includedTypeId)) { prefHasChanged = try { val type = DataSourceType.parseId(includedTypeId) if (type == null) { MTLog.d(this, "makeFilterTypeId() > included '$includedTypeId' not valid") return@let // DO NOTHING } if (!availableTypes.contains(type)) { MTLog.d(this, "makeFilterTypeId() > included '$includedTypeId' not available") return@let // DO NOTHING } filterTypeIds.add(type.id) true } catch (e: java.lang.Exception) { MTLog.w(this, e, "Error while parsing filter type ID '%s'!", includedTypeId) true } } savedStateHandle[EXTRA_INCLUDE_TYPE_ID] = EXTRA_INCLUDE_TYPE_ID_DEFAULT // only once } if (prefHasChanged) { // old setting not valid anymore saveFilterTypeIdsPref(if (filterTypeIds.size == availableTypes.size) null else filterTypeIds) // asynchronous } return filterTypeIds } private val _loadedArea = MutableLiveData<LatLngBounds?>(null) private val _loadingArea = MutableLiveData<LatLngBounds?>(null) fun resetLoadedPOIMarkers() { this._loadedArea.value = null // loaded w/ wrong filter -> RESET -> trigger new load this._poiMarkersReset.value = Event(true) } private val _allAgencies = this.dataSourcesRepository.readingAllAgenciesBase() // #onModulesUpdated val typeMapAgencies: LiveData<List<IAgencyNearbyUIProperties>?> = PairMediatorLiveData(_allAgencies, filterTypeIds).map { (allAgencies, filterTypeIds) -> filterTypeIds?.let { theFilterTypeIds -> allAgencies?.filter { agency -> agency.type.isMapScreen && (theFilterTypeIds.isEmpty() || theFilterTypeIds.contains(agency.type.id)) } } } private val areaTypeMapAgencies: LiveData<List<IAgencyNearbyUIProperties>?> = PairMediatorLiveData(typeMapAgencies, _loadingArea).map { (typeMapAgencies, loadingArea) -> loadingArea?.let { theLoadingArea -> // loading area REQUIRED typeMapAgencies?.filter { agency -> agency.isInArea(theLoadingArea) } } }.distinctUntilChanged() val loaded: LiveData<Boolean?> = PairMediatorLiveData(_loadingArea, _loadedArea).map { (loadingArea, loadedArea) -> loadedArea.containsEntirely(loadingArea) } fun onCameraChange(newVisibleArea: LatLngBounds, getBigCameraPosition: () -> LatLngBounds?): Boolean { val loadedArea: LatLngBounds? = this._loadedArea.value val loadingArea: LatLngBounds? = this._loadingArea.value val loaded = loadedArea.containsEntirely(newVisibleArea) val loading = loadingArea.containsEntirely(newVisibleArea) if (loaded || loading) { return false // no change } var newLoadingArea = loadingArea?.let { if (!it.contains(newVisibleArea.northeast)) it.including(newVisibleArea.northeast) else it } newLoadingArea = newLoadingArea?.let { if (!it.contains(newVisibleArea.southwest)) it.including(newVisibleArea.southwest) else it } newLoadingArea = newLoadingArea ?: loadedArea?.let { if (!it.contains(newVisibleArea.northeast)) it.including(newVisibleArea.northeast) else it } newLoadingArea = newLoadingArea ?: loadedArea?.let { if (!it.contains(newVisibleArea.southwest)) it.including(newVisibleArea.southwest) else it } newLoadingArea = newLoadingArea ?: newVisibleArea.let { getBigCameraPosition() ?: it } this._loadingArea.value = newLoadingArea // set NOW (no post) return newLoadingArea != loadingArea // same area? } private val _poiMarkersReset = MutableLiveData(Event(false)) private val _poiMarkers = MutableLiveData<Collection<POIMarker>?>(null) val poiMarkers: LiveData<Collection<POIMarker>?> = _poiMarkers val poiMarkersTrigger: LiveData<Any?> = QuadrupleMediatorLiveData( areaTypeMapAgencies, _loadedArea, _loadingArea, _poiMarkersReset ).map { loadPOIMarkers() null } private var poiMarkersLoadJob: Job? = null private fun loadPOIMarkers() { poiMarkersLoadJob?.cancel() val reset: Boolean = _poiMarkersReset.value?.getContentIfNotHandled() ?: false if (reset) { _poiMarkers.value = null } poiMarkersLoadJob = viewModelScope.launch(context = viewModelScope.coroutineContext + Dispatchers.IO) { val areaTypeMapAgencies: List<IAgencyNearbyUIProperties>? = areaTypeMapAgencies.value val loadedArea: LatLngBounds? = _loadedArea.value val loadingArea: LatLngBounds? = _loadingArea.value val currentPOIMarkers: Collection<POIMarker>? = _poiMarkers.value if (loadingArea == null || areaTypeMapAgencies == null) { MTLog.d(this@MapViewModel, "loadPOIMarkers() > SKIP (no loading area OR agencies)") return@launch // SKIP (missing loading area or agencies) } val positionToPoiMarkers = ArrayMap<LatLng, POIMarker>() var positionTrunc: LatLng if (!reset) { currentPOIMarkers?.forEach { poiMarker -> positionTrunc = POIMarker.getLatLngTrunc(poiMarker.position.latitude, poiMarker.position.longitude) positionToPoiMarkers[positionTrunc] = positionToPoiMarkers[positionTrunc]?.apply { merge(poiMarker) } ?: poiMarker } } var hasChanged = false areaTypeMapAgencies.filter { agency -> !agency.isEntirelyInside(loadedArea) }.map { agency -> getAgencyPOIMarkers(agency, loadingArea, loadedArea, this).also { if (!hasChanged && !it.isEmpty) { hasChanged = true } } }.forEach { agencyPOIMarkers -> ensureActive() agencyPOIMarkers.forEach { (positionTrunc, poiMarker) -> positionToPoiMarkers[positionTrunc] = positionToPoiMarkers[positionTrunc]?.apply { merge(poiMarker) } ?: poiMarker } } ensureActive() if (loadedArea != loadingArea) { _loadedArea.postValue(loadingArea) // LOADED DONE } if (hasChanged) { _poiMarkers.postValue(positionToPoiMarkers.values) } } } private suspend fun getAgencyPOIMarkers( agency: IAgencyNearbyUIProperties, loadingArea: LatLngBounds, loadedArea: LatLngBounds? = null, coroutineScope: CoroutineScope, ): ArrayMap<LatLng, POIMarker> { val clusterItems = ArrayMap<LatLng, POIMarker>() val poiFilter = POIProviderContract.Filter.getNewAreaFilter( loadingArea.let { min(it.northeast.latitude, it.southwest.latitude) }, // MIN LAT loadingArea.let { max(it.northeast.latitude, it.southwest.latitude) }, // MAX LAT loadingArea.let { min(it.northeast.longitude, it.southwest.longitude) }, // MIN LNG loadingArea.let { max(it.northeast.longitude, it.southwest.longitude) }, // MAX LNG loadedArea?.let { min(it.northeast.latitude, it.southwest.latitude) }, loadedArea?.let { max(it.northeast.latitude, it.southwest.latitude) }, loadedArea?.let { min(it.northeast.longitude, it.southwest.longitude) }, loadedArea?.let { max(it.northeast.longitude, it.southwest.longitude) }, ) coroutineScope.ensureActive() val agencyPOIs = poiRepository.findPOIMs(agency.authority, poiFilter) val agencyShortName = agency.shortName var positionTrunc: LatLng var name: String var extra: String? var uuid: String var authority: String var color: Int? var secondaryColor: Int? agencyPOIs?.map { it to POIMarker.getLatLng(it) }?.filterNot { (_, position) -> !loadingArea.contains(position) && loadedArea?.contains(position) == true }?.forEach { (poim, position) -> coroutineScope.ensureActive() positionTrunc = POIMarker.getLatLngTrunc(poim) name = poim.poi.name extra = (poim.poi as? RouteTripStop)?.route?.shortestName uuid = poim.poi.uuid authority = poim.poi.authority color = poim.getColor(dataSourcesRepository) secondaryColor = agency.colorInt clusterItems[positionTrunc] = clusterItems[positionTrunc]?.apply { merge(position, name, agencyShortName, extra, color, secondaryColor, uuid, authority) } ?: POIMarker(position, name, agencyShortName, extra, color, secondaryColor, uuid, authority) } return clusterItems } }
5
null
4
34
dccaac0fe7f1604a191eaa63b936ba476a9a0682
15,112
mtransit-for-android
Apache License 2.0
src/main/kotlin/no/nav/syfo/application/RerunCronJob.kt
navikt
257,523,904
false
null
package no.nav.syfo.application import net.logstash.logback.argument.StructuredArguments import no.nav.syfo.db.DatabaseInterface import no.nav.syfo.logger import no.nav.syfo.metrics.MESSAGES_STILL_FAIL_AFTER_1H import no.nav.syfo.persistering.db.hentIkkeFullforteDialogmeldinger import java.time.LocalDateTime class RerunCronJob( val database: DatabaseInterface, val dialogmeldingProcessor: DialogmeldingProcessor, ) : Cronjob { override val initialDelayMinutes: Long = 2 override val intervalDelayMinutes: Long = 10 override suspend fun run() { val result = CronjobResult() database.hentIkkeFullforteDialogmeldinger().forEach { (dialogmeldingId, fellesformat, mottattDatetime) -> try { logger.info("Attempting reprocessing of $dialogmeldingId") dialogmeldingProcessor.processMessage(dialogmeldingId, fellesformat) result.updated++ } catch (e: Exception) { logger.warn("Exception caught while reprocessing message, will try again later: {}", e.message) result.failed++ if (mottattDatetime.isBefore(LocalDateTime.now().minusHours(1))) { MESSAGES_STILL_FAIL_AFTER_1H.inc() } } } logger.info( "Completed rerun cron job with result: {}, {}", StructuredArguments.keyValue("failed", result.failed), StructuredArguments.keyValue("updated", result.updated), ) } } data class CronjobResult( var updated: Int = 0, var failed: Int = 0 )
2
null
0
1
eff4595eb477829a9d7241466039c564a0a16bdf
1,606
padm2
MIT License
processor-kotlin/src/main/java/de/bwueller/environment/processor/actor/ActorManager.kt
Bw2801
131,579,843
false
null
package de.bwueller.environment.processor.actor import com.google.protobuf.GeneratedMessageV3 import de.bwueller.environment.processor.userManager import de.bwueller.environment.protocol.PlaySound import de.bwueller.environment.protocol.RegisterActor import de.bwueller.environment.protocol.serializePacket import org.java_websocket.WebSocket import java.util.* class ActorManager { private val actors = mutableMapOf<String, Actor>() private val socketActors = mutableMapOf<WebSocket, Actor>() /** * Handles a request to register a new actor. * * @param packet the packet to parse. * @param socket the WebSocket connection to reply to. */ fun handleRegisterActorRequest(packet: RegisterActor.RegisterActorRequest, socket: WebSocket) { val name = packet.name val packetMeta = packet.metaList val meta = mutableMapOf<Int, String>() packetMeta.forEach { entry -> meta[entry.identifier] = entry.value } val responseBuilder = RegisterActor.RegisterActorResponse.newBuilder() val actor: Actor if (actors.containsKey(name)) { // An actor with the same name is already connected. actor = actors[name]!! responseBuilder.status = RegisterActor.RegisterActorResponse.Status.ERR_ALREADY_CONNECTED } else { actor = Actor(UUID.randomUUID(), name, meta, socket) responseBuilder.status = RegisterActor.RegisterActorResponse.Status.SUC_CONNECTED actors[actor.name] = actor socketActors[socket] = actor } // Send response. responseBuilder.identifier = actor.uuid.toString() socket.send(serializePacket(responseBuilder.build())) println("Actor ${actor.name}(${actor.uuid}) has been registered.") } /** * Handles the request to unregister an actor. Typically called when a WebSocket connection to an actor is closed. * * @param socket the WebSocket to close the actor for. */ fun unregisterActor(socket: WebSocket) { val actor = socketActors.remove(socket) ?: return actors.remove(actor.name) if (actor.users.isNotEmpty()) { synchronized(actor) { for (i in actor.users.size - 1 downTo 0) { userManager.unregisterUser(actor.users[i]) } } } println("Actor ${actor.name}(${actor.uuid}) has been unregistered.") } fun isActorSocket(socket: WebSocket) = socketActors.containsKey(socket) fun getActor(socket: WebSocket) = socketActors[socket] }
10
null
1
5
5a20724ea66102bcebd1fd71f598c81178f478fd
2,432
environment
Apache License 2.0
src/main/kotlin/no/nav/personbruker/dittnav/eventaggregator/common/database/Database.kt
navikt
189,239,389
false
null
package no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.database import com.zaxxer.hikari.HikariDataSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.database.exception.RetriableDatabaseException import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.database.exception.UnretriableDatabaseException import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.health.HealthCheck import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.health.HealthStatus import no.nav.personbruker.dittnav.brukernotifikasjonbestiller.health.Status import org.postgresql.util.PSQLException import org.slf4j.Logger import org.slf4j.LoggerFactory import java.sql.Connection import java.sql.SQLException import java.sql.SQLRecoverableException import java.sql.SQLTransientException val log: Logger = LoggerFactory.getLogger(Database::class.java) interface Database: HealthCheck { val dataSource: HikariDataSource suspend fun <T> dbQuery(operationToExecute: Connection.() -> T): T = withContext(Dispatchers.IO) { dataSource.connection.use { openConnection -> try { openConnection.operationToExecute().apply { openConnection.commit() } } catch (e: Exception) { try { openConnection.rollback() } catch (rollbackException: Exception) { e.addSuppressed(rollbackException) } throw e } } } suspend fun <T> queryWithExceptionTranslation(operationToExecute: Connection.() -> T): T { return translateExternalExceptionsToInternalOnes { dbQuery { operationToExecute() } } } override suspend fun status(): HealthStatus { val serviceName = "Database" return withContext(Dispatchers.IO) { try { dbQuery { prepareStatement("""SELECT 1""").execute() } HealthStatus(serviceName, Status.OK, "200 OK") } catch (e: Exception) { log.error("Selftest mot databasen feilet", e) HealthStatus(serviceName, Status.ERROR, "Feil mot DB") }} } } inline fun <T> translateExternalExceptionsToInternalOnes(databaseActions: () -> T): T { return try { databaseActions() } catch (te: SQLTransientException) { val message = "Skriving til databasen feilet grunnet en periodisk feil." throw RetriableDatabaseException(message, te) } catch (re: SQLRecoverableException) { val message = "Skriving til databasen feilet grunnet en periodisk feil." throw RetriableDatabaseException(message, re) } catch (pe: PSQLException) { val message = "Det skjedde en SQL relatert feil ved skriving til databasen." val ure = UnretriableDatabaseException(message, pe) pe.sqlState?.map { sqlState -> ure.addContext("sqlState", sqlState) } throw ure } catch (se: SQLException) { val message = "Det skjedde en SQL relatert feil ved skriving til databasen." val ure = UnretriableDatabaseException(message, se) se.sqlState?.map { sqlState -> ure.addContext("sqlState", sqlState) } throw ure } catch (e: Exception) { val message = "Det skjedde en ukjent feil ved skriving til databasen." throw UnretriableDatabaseException(message, e) } }
1
null
0
1
a55db5d4c4f754454890cdd54d472227fa91a05d
3,567
dittnav-event-aggregator
MIT License
coincurrency/data/repository/MyCoinRepository.kt
EricMoin
658,075,629
false
null
package com.ericmoin.coincurrency.data.repository import com.ericmoin.coincurrency.data.remote.CoinPaprikaApi import com.ericmoin.coincurrency.data.remote.dto.CoinDetailDto import com.ericmoin.coincurrency.data.remote.dto.CoinDto import com.ericmoin.coincurrency.domain.repository.CoinRepository import javax.inject.Inject class MyCoinRepository @Inject constructor( private val api:CoinPaprikaApi ):CoinRepository{ override suspend fun getCoins() = api.getCoins() override suspend fun getCoinById(coinId: String) = api.getCoinById(coinId) }
0
Kotlin
0
0
70418759e896dda2fcf930a196272a7f558c55c1
552
Jetpack-Compose-Learning
Apache License 2.0
libs/shape/src/test/kotlin/mono/shape/shape/LineTest.kt
tuanchauict
325,686,408
false
null
package mono.shape.shape import mono.graphics.geo.DirectedPoint import mono.graphics.geo.Point import mono.shape.serialization.SerializableLine import mono.shape.shape.line.LineHelper import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue /** * A test for [Line] */ class LineTest { @Test fun testSerialization_init() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) val serializableLine = line.toSerializableShape(true) as SerializableLine assertEquals(startPoint, serializableLine.startPoint) assertEquals(endPoint, serializableLine.endPoint) assertEquals(line.reducedJoinPoints, LineHelper.reduce(serializableLine.jointPoints)) assertEquals(line.extra.toSerializableExtra(), serializableLine.extra) assertFalse(serializableLine.wasMovingEdge) } @Test fun testSerialization_moveAnchorPoints() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) val newStartPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 4, 5) val newEndPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 7, 8) line.moveAnchorPoint( Line.AnchorPointUpdate(Line.Anchor.START, newStartPoint), isReduceRequired = true ) line.moveAnchorPoint( Line.AnchorPointUpdate(Line.Anchor.END, newEndPoint), isReduceRequired = true ) val serializableLine = line.toSerializableShape(true) as SerializableLine assertEquals(newStartPoint, serializableLine.startPoint) assertEquals(newEndPoint, serializableLine.endPoint) assertEquals(line.reducedJoinPoints, LineHelper.reduce(serializableLine.jointPoints)) assertEquals(line.extra.toSerializableExtra(), serializableLine.extra) assertFalse(serializableLine.wasMovingEdge) } @Test fun testSerialization_moveEdge() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) line.moveEdge(line.edges.first().id, Point(10, 10), isReduceRequired = true) val serializableLine = line.toSerializableShape(true) as SerializableLine assertEquals(startPoint, serializableLine.startPoint) assertEquals(endPoint, serializableLine.endPoint) assertEquals(line.reducedJoinPoints, LineHelper.reduce(serializableLine.jointPoints)) assertEquals(line.extra.toSerializableExtra(), serializableLine.extra) assertTrue(serializableLine.wasMovingEdge) } @Test fun testSerialization_restoreInit() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) val serializableLine = line.toSerializableShape(true) as SerializableLine val line2 = Line(serializableLine, parentId = PARENT_ID) assertEquals(line.getDirection(Line.Anchor.START), line2.getDirection(Line.Anchor.START)) assertEquals(line.getDirection(Line.Anchor.END), line2.getDirection(Line.Anchor.END)) assertEquals(line.reducedJoinPoints, line2.reducedJoinPoints) assertEquals(line.extra, line2.extra) assertEquals(line.wasMovingEdge(), line2.wasMovingEdge()) } @Test fun testSerialization_restoreAfterMovingAnchorPoints() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) val newStartPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 4, 5) val newEndPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 7, 8) line.moveAnchorPoint( Line.AnchorPointUpdate(Line.Anchor.START, newStartPoint), isReduceRequired = true ) line.moveAnchorPoint( Line.AnchorPointUpdate(Line.Anchor.END, newEndPoint), isReduceRequired = true ) val serializableLine = line.toSerializableShape(true) as SerializableLine val line2 = Line(serializableLine, parentId = PARENT_ID) assertEquals(line.getDirection(Line.Anchor.START), line2.getDirection(Line.Anchor.START)) assertEquals(line.getDirection(Line.Anchor.END), line2.getDirection(Line.Anchor.END)) assertEquals(line.reducedJoinPoints, line2.reducedJoinPoints) assertEquals(line.extra, line2.extra) assertEquals(line.wasMovingEdge(), line2.wasMovingEdge()) } @Test fun testSerialization_restoreAfterMovingEdge() { val startPoint = DirectedPoint(DirectedPoint.Direction.VERTICAL, 1, 2) val endPoint = DirectedPoint(DirectedPoint.Direction.HORIZONTAL, 3, 4) val line = Line(startPoint, endPoint, parentId = PARENT_ID) line.moveEdge(line.edges.first().id, Point(10, 10), isReduceRequired = true) val serializableLine = line.toSerializableShape(true) as SerializableLine val line2 = Line(serializableLine, PARENT_ID) assertEquals(line.getDirection(Line.Anchor.START), line2.getDirection(Line.Anchor.START)) assertEquals(line.getDirection(Line.Anchor.END), line2.getDirection(Line.Anchor.END)) assertEquals(line.reducedJoinPoints, line2.reducedJoinPoints) assertEquals(line.extra, line2.extra) assertEquals(line.wasMovingEdge(), line2.wasMovingEdge()) } companion object { private const val PARENT_ID = "1" } }
15
null
9
91
21cef26b45c984eee31ea2c3ba769dfe5eddd92e
6,077
MonoSketch
Apache License 2.0
naver-map-compose/src/main/java/com/naver/maps/map/compose/FusedLocationSource.kt
fornewid
492,204,824
false
null
/* * Copyright 2023 SOUP * * 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.naver.maps.map.compose import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.os.Bundle import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.naver.maps.map.LocationSource @ExperimentalNaverMapApi @OptIn(ExperimentalPermissionsApi::class) @Composable public fun rememberFusedLocationSource(): LocationSource { val permissionsState = rememberMultiplePermissionsState( listOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, ) ) val context = LocalContext.current val locationSource = remember { object : FusedLocationSource(context) { override fun hasPermissions(): Boolean { return permissionsState.allPermissionsGranted } override fun onPermissionRequest() { permissionsState.launchMultiplePermissionRequest() } } } val allGranted = permissionsState.allPermissionsGranted LaunchedEffect(allGranted) { if (allGranted) { locationSource.onPermissionGranted() } } return locationSource } private abstract class FusedLocationSource(context: Context) : LocationSource { private val callback = object : FusedLocationCallback(context.applicationContext) { override fun onLocationChanged(location: Location?) { lastLocation = location } } private var listener: LocationSource.OnLocationChangedListener? = null private var isListening: Boolean = false private var lastLocation: Location? = null set(value) { field = value if (listener != null && value != null) { listener?.onLocationChanged(value) } } abstract fun hasPermissions(): Boolean abstract fun onPermissionRequest() fun onPermissionGranted() { setListening(true) } override fun activate(listener: LocationSource.OnLocationChangedListener) { this.listener = listener if (isListening.not()) { if (hasPermissions()) { setListening(true) } else { onPermissionRequest() } } } override fun deactivate() { if (isListening) { setListening(false) } this.listener = null } private fun setListening(listening: Boolean) { if (listening) { callback.startListening() } else { callback.stopListening() } isListening = listening } private abstract class FusedLocationCallback(private val context: Context) { private val locationCallback: LocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { onLocationChanged(locationResult.lastLocation) } } fun startListening() { GoogleApiClient.Builder(context) .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { @SuppressLint("MissingPermission") override fun onConnected(bundle: Bundle?) { val request = LocationRequest() request.priority = 100 request.interval = 1000L request.fastestInterval = 1000L LocationServices.getFusedLocationProviderClient(context) .requestLocationUpdates(request, locationCallback, null) } override fun onConnectionSuspended(i: Int) {} }) .addApi(LocationServices.API) .build() .connect() } fun stopListening() { LocationServices .getFusedLocationProviderClient(context) .removeLocationUpdates(locationCallback) } abstract fun onLocationChanged(location: Location?) } }
6
Kotlin
4
68
16847154a7175df8a62cc3d4a309a7b25f85d8a1
5,271
naver-map-compose
Apache License 2.0
sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2023 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.sync.settings.impl import androidx.arch.core.executor.testing.* import androidx.room.* import androidx.test.ext.junit.runners.* import androidx.test.platform.app.* import com.duckduckgo.app.* import com.duckduckgo.common.test.CoroutineTestRule import com.duckduckgo.common.test.FileUtilities import com.duckduckgo.sync.api.engine.* import com.duckduckgo.sync.api.engine.SyncMergeResult.Success import com.duckduckgo.sync.api.engine.SyncableDataPersister.SyncConflictResolution.DEDUPLICATION import com.duckduckgo.sync.api.engine.SyncableDataPersister.SyncConflictResolution.TIMESTAMP import kotlinx.coroutines.* import org.junit.* import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.runner.* import org.mockito.Mockito.* @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class SettingsSyncDataPersisterTest { @get:Rule @Suppress("unused") var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule var coroutineRule = CoroutineTestRule() val db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getInstrumentation().targetContext, SettingsDatabase::class.java) .allowMainThreadQueries() .build() val metadataDao = db.settingsSyncDao() val duckAddressSetting = spy(FakeSyncableSetting()) val settingSyncStore = FakeSettingsSyncStore() val syncableSettingsPP = SyncableSettingsPluginPoint(mutableListOf(duckAddressSetting)) private val testee = SettingsSyncDataPersister( syncableSettings = syncableSettingsPP, settingsSyncMetadataDao = metadataDao, syncSettingsSyncStore = settingSyncStore, syncCrypto = FakeCrypto(), dispatchers = coroutineRule.testDispatcherProvider, ) @After fun after() { db.close() } @Test fun whenPersistChangesDeduplicationWithdValueThenCallDeduplicateWithValue() { val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) verify(duckAddressSetting).deduplicate("fake_value") } @Test fun whenPersistChangesDeduplicationWithDeletedValueThenCallDeduplicateWithNull() { val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithDeletedObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) verify(duckAddressSetting).deduplicate(null) } @Test fun whenPersistChangesTimestampAndNoRecentChangeThenCallMergeWithValue() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting).save("fake_value") } @Test fun whenPersistChangesTimestampWithDeletedValueThenCallSaveWithNull() { val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithDeletedObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting).save(null) } @Test fun whenPersistChangesTimestampButRecentlyModifiedThenSkip() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" metadataDao.addOrUpdate( SettingsSyncMetadataEntity( key = "fake_setting", modified_at = "2023-08-31T10:06:17.022Z", deleted_at = null, ), ) val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting, times(0)).save("fake_value") } @Test fun whenPersistChangesSucceedsThenUpdateServerAndClientTimestamps() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.persist( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) assertEquals("2023-08-31T10:06:16.022Z", settingSyncStore.serverModifiedSince) assertEquals("2023-08-31T10:06:16.022Z", settingSyncStore.clientModifiedSince) } companion object { val responseWithDeletedObject = FileUtilities.loadText(javaClass.classLoader!!, "json/settings_with_deleted_object_response.json") val responseWithValuesObject = FileUtilities.loadText(javaClass.classLoader!!, "json/settings_with_values_response.json") } }
67
null
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
5,922
Android
Apache License 2.0
src/main/kotlin/org/easysql/visitor/output/OracleOutPutVisitor.kt
wz7982
537,805,512
false
null
package org.easysql.visitor.output import org.easysql.ast.limit.SqlLimit import org.easysql.ast.statement.upsert.SqlUpsert class OracleOutPutVisitor : OutPutVisitor() { override fun visitSqlLimit(sqlLimit: SqlLimit) { sqlBuilder.append("OFFSET ${sqlLimit.offset} ROWS FETCH FIRST ${sqlLimit.limit} ROWS ONLY") } override fun printWithRecursive() {} override fun visitSqlUpsert(sqlUpsert: SqlUpsert) { sqlBuilder.append("MERGE INTO ") visitSqlTableSource(sqlUpsert.table!!) sqlBuilder.append(" ${quote}t1$quote") sqlBuilder.append(" USING (") sqlBuilder.append("SELECT ") for (index in sqlUpsert.columns.indices) { visitSqlExpr(sqlUpsert.value[index]) sqlBuilder.append(" AS ") visitSqlExpr(sqlUpsert.columns[index]) if (index < sqlUpsert.columns.size - 1) { sqlBuilder.append(",") sqlBuilder.append(" ") } } sqlBuilder.append(" FROM ${quote}dual$quote) ${quote}t2$quote") sqlBuilder.append("\nON (") for (index in sqlUpsert.primaryColumns.indices) { sqlBuilder.append("${quote}t1$quote.") visitSqlExpr(sqlUpsert.primaryColumns[index]) sqlBuilder.append(" = ") sqlBuilder.append("${quote}t2$quote.") visitSqlExpr(sqlUpsert.primaryColumns[index]) if (index < sqlUpsert.primaryColumns.size - 1) { sqlBuilder.append(" AND ") } } sqlBuilder.append(")") sqlBuilder.append("\nWHEN MATCHED THEN UPDATE SET ") printList(sqlUpsert.updateColumns) { it -> sqlBuilder.append("${quote}t1$quote.") visitSqlExpr(it) sqlBuilder.append(" = ") sqlBuilder.append("${quote}t2$quote.") visitSqlExpr(it) } sqlBuilder.append("\nWHEN NOT MATCHED THEN INSERT") sqlBuilder.append(" (") printList(sqlUpsert.columns) { it -> sqlBuilder.append("${quote}t1$quote.") visitSqlExpr(it) } sqlBuilder.append(")") sqlBuilder.append(" VALUES") sqlBuilder.append(" (") printList(sqlUpsert.value, ::visitSqlExpr) sqlBuilder.append(")") } }
0
Kotlin
0
2
9098640d77a0c6be93a3331dfcbf92b9cfa81ff9
2,304
easysql-kt
Apache License 2.0
app/src/main/java/com/bhavnathacker/jettasks/presentation/theme/Color.kt
bhavnathacker
457,276,304
false
null
package com.bhavnathacker.jettasks.presentation.theme import androidx.compose.ui.graphics.Color //Used for Primary and It's variant val Purple200 = Color(0xFFCE93D8) val Purple400 = Color(0xFFAB47BC) val Purple600 = Color(0xFF8E24AA) val Purple800 = Color(0xFF6A1B9A) //Used for Secondary val Blue200 = Color(0xFF81D4FA) val Blue400 = Color(0xFF29B6F6) //Used for Task Priority val Amber500 = Color(0xFFFFC107) val Orange500 = Color(0xFFFF9800) val Red500 = Color(0xFFF44336) val Green500 = Color(0xFF4CAF50)
0
Kotlin
5
23
764992c627876e9303d6edf7b4d837269fd8eee0
512
JetTasks
Apache License 2.0
platform/workspace/storage/tests/testSrc/com/intellij/platform/workspace/storage/tests/EntityStorageSerializationTest.kt
ingokegel
72,937,917
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.platform.workspace.storage.tests import com.intellij.platform.workspace.storage.SerializationResult import com.intellij.platform.workspace.storage.impl.EntityStorageSerializerImpl import com.intellij.platform.workspace.storage.impl.MutableEntityStorageImpl import com.intellij.platform.workspace.storage.impl.url.VirtualFileUrlManagerImpl import com.intellij.platform.workspace.storage.testEntities.entities.* import com.intellij.platform.workspace.storage.url.VirtualFileUrlManager import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.nio.file.Files import java.nio.file.Path import java.util.* class EntityStorageSerializationTest { private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = VirtualFileUrlManagerImpl() } @Test fun `simple model serialization`() { val builder = createEmptyBuilder() builder addEntity SampleEntity(false, "MyEntity", ArrayList(), HashMap(), virtualFileManager.fromUrl("file:///tmp"), SampleEntitySource("test")) SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), VirtualFileUrlManagerImpl()) } @Test fun `entity properties serialization`() { val builder = createEmptyBuilder() mutableSetOf("c", "d") VirtualFileUrlManagerImpl() builder addEntity SampleEntity(false, stringProperty = "MyEntity", stringListProperty = mutableListOf("a", "b"), stringMapProperty = HashMap(), fileProperty = virtualFileManager.fromUrl("file:///tmp"), entitySource = SampleEntitySource("test")) SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), VirtualFileUrlManagerImpl()) } @Test fun `entity collections and map serialization`() { val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManagerImpl() val builder = createEmptyBuilder() val stringListProperty = buildList { this.add("a") this.add("b") } val stringMapProperty = buildMap { put("ab", "bc") put("bc", "ce") } val entity = SampleEntity(false, "MyEntity", stringListProperty, stringMapProperty, virtualFileManager.fromUrl("file:///tmp"), SampleEntitySource("test")) builder.addEntity(entity) val setProperty = buildSet { this.add(1) this.add(2) this.add(2) } builder.addEntity(CollectionFieldEntity(setProperty, listOf("one", "two", "three"), MySource)) builder.addEntity(CollectionFieldEntity(setOf(1, 2, 3, 3, 4), listOf("one", "two", "three"), MySource)) SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), virtualFileManager) } @Test fun `entity uuid serialization`() { val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManagerImpl() val builder = createEmptyBuilder() val entity = SampleEntity(false, "MyEntity", emptyList(), emptyMap(), virtualFileManager.fromUrl("file:///tmp"), SampleEntitySource("test")) { randomUUID = UUID.fromString("58e0a7d7-eebc-11d8-9669-0800200c9a66") } builder.addEntity(entity) SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toSnapshot(), virtualFileManager) } @Test fun `serialization with version changing`() { val builder = createEmptyBuilder() builder addEntity SampleEntity(false, "MyEntity", ArrayList(), HashMap(), VirtualFileUrlManagerImpl().fromUrl("file:///tmp"), SampleEntitySource("test")) val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) .also { it.serializerDataFormatVersion = "XYZ" } withTempFile { file -> serializer.serializeCache(file, builder.toSnapshot()) val deserialized = (deserializer.deserializeCache(file).getOrThrow() as? MutableEntityStorageImpl)?.toSnapshot() assertNull(deserialized) } } @Test fun `serializer version`() { val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl()) val (kryo, _) = serializer.createKryo() val registration = (10..1_000).mapNotNull { kryo.getRegistration(it) }.joinToString(separator = "\n") assertEquals("Have you changed kryo registration? Update the version number! (And this test)", expectedKryoRegistration, registration) } @Test fun `serialize empty lists`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() // Do not replace ArrayList() with emptyList(). This must be a new object for this test builder addEntity CollectionFieldEntity(emptySet(), ArrayList(), MySource) withTempFile { file -> serializer.serializeCache(file, builder.toSnapshot()) } } @Test fun `serialize abstract`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() builder addEntity SampleEntity(false, "myString", ArrayList(), HashMap(), VirtualFileUrlManagerImpl().fromUrl("file:///tmp"), SampleEntitySource("test")) withTempFile { file -> val result = serializer.serializeCache(file, builder.toSnapshot()) assertTrue(result is SerializationResult.Success) } } @Test fun `serialize rider like`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() builder.addEntity(ProjectModelTestEntity("info", DescriptorInstance("info"), MySource)) withTempFile { file -> val result = serializer.serializeCache(file, builder.toSnapshot()) assertTrue(result is SerializationResult.Success) } } @Test fun `read broken cache`() { val virtualFileManager = VirtualFileUrlManagerImpl() val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager) val builder = createEmptyBuilder() builder addEntity SampleEntity(false, "myString", ArrayList(), HashMap(), VirtualFileUrlManagerImpl().fromUrl("file:///tmp"), SampleEntitySource("test")) withTempFile { file -> serializer.serializeCache(file, builder.toSnapshot()) // Remove random byte from a serialised store Files.write(file, Files.readAllBytes(file).filterIndexed { i, _ -> i != 3 }.toByteArray()) val result = serializer.deserializeCache(file) assertNull(result.getOrNull()) } } } // Kotlin tip: Use the ugly ${'$'} to insert the $ into the multiline string private val expectedKryoRegistration = """ [10, com.intellij.platform.workspace.storage.impl.ConnectionId] [11, com.intellij.platform.workspace.storage.impl.ImmutableEntitiesBarrel] [12, com.intellij.platform.workspace.storage.impl.ChildEntityId] [13, com.intellij.platform.workspace.storage.impl.ParentEntityId] [14, it.unimi.dsi.fastutil.objects.ObjectOpenHashSet] [15, com.intellij.platform.workspace.storage.impl.indices.SymbolicIdInternalIndex] [16, com.intellij.platform.workspace.storage.impl.indices.EntityStorageInternalIndex] [17, com.intellij.platform.workspace.storage.impl.indices.MultimapStorageIndex] [18, com.intellij.platform.workspace.storage.impl.containers.BidirectionalLongMultiMap] [19, it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap] [20, it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap] [21, com.intellij.platform.workspace.storage.impl.EntityStorageSerializerImpl${'$'}TypeInfo] [22, java.util.List] [23, java.util.ArrayList] [24, java.util.HashMap] [25, com.intellij.util.SmartList] [26, java.util.LinkedHashMap] [27, com.intellij.platform.workspace.storage.impl.containers.BidirectionalMap] [28, com.intellij.platform.workspace.storage.impl.containers.BidirectionalSetMap] [29, com.intellij.util.containers.BidirectionalMultiMap] [30, com.google.common.collect.HashBiMap] [31, java.util.LinkedHashSet] [32, com.intellij.platform.workspace.storage.impl.containers.LinkedBidirectionalMap] [33, it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap] [34, it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap] [35, byte[]] [36, com.intellij.platform.workspace.storage.impl.ImmutableEntityFamily] [37, com.intellij.platform.workspace.storage.impl.indices.VirtualFileIndex] [38, int[]] [39, kotlin.Pair] [40, com.intellij.platform.workspace.storage.impl.EntityStorageSerializerImpl${'$'}SerializableEntityId] [41, com.intellij.platform.workspace.storage.impl.RefsTable] [42, com.intellij.platform.workspace.storage.impl.references.ImmutableOneToOneContainer] [43, com.intellij.platform.workspace.storage.impl.references.ImmutableOneToManyContainer] [44, com.intellij.platform.workspace.storage.impl.references.ImmutableAbstractOneToOneContainer] [45, com.intellij.platform.workspace.storage.impl.references.ImmutableOneToAbstractManyContainer] [46, com.intellij.platform.workspace.storage.impl.containers.MutableIntIntUniqueBiMap] [47, com.intellij.platform.workspace.storage.impl.containers.MutableNonNegativeIntIntBiMap] [48, com.intellij.platform.workspace.storage.impl.containers.MutableNonNegativeIntIntMultiMap${'$'}ByList] [49, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}AddEntity] [50, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}RemoveEntity] [51, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}ReplaceEntity] [52, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}ChangeEntitySource] [53, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}ReplaceAndChangeSource] [54, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}ReplaceEntity${'$'}Data] [55, com.intellij.platform.workspace.storage.impl.ChangeEntry${'$'}ReplaceEntity${'$'}References] [56, java.util.Collections${'$'}UnmodifiableCollection] [57, java.util.Collections${'$'}UnmodifiableSet] [58, java.util.Collections${'$'}UnmodifiableRandomAccessList] [59, java.util.Collections${'$'}UnmodifiableMap] [60, java.util.Collections${'$'}EmptyList] [61, java.util.Collections${'$'}EmptyMap] [62, java.util.Collections${'$'}EmptySet] [63, java.util.Collections${'$'}SingletonList] [64, java.util.Collections${'$'}SingletonMap] [65, java.util.Collections${'$'}SingletonSet] [66, com.intellij.util.containers.ContainerUtilRt${'$'}EmptyList] [67, com.intellij.util.containers.MostlySingularMultiMap${'$'}EmptyMap] [68, com.intellij.util.containers.MultiMap${'$'}EmptyMap] [69, kotlin.collections.EmptyMap] [70, kotlin.collections.EmptyList] [71, kotlin.collections.EmptySet] [72, Object[]] [73, java.util.UUID] """.trimIndent() private inline fun withTempFile(task: (file: Path) -> Unit) { val file = Files.createTempFile("", "") try { task(file) } finally { Files.deleteIfExists(file) } }
233
null
4931
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
11,528
intellij-community
Apache License 2.0
service/src/main/java/com/upnetix/applicationservice/pushtoken/IPushTokenService.kt
scalefocus
255,062,459
false
null
package com.upnetix.applicationservice.pushtoken import com.upnetix.applicationservice.base.ResponseWrapper interface IPushTokenService { suspend fun sendPushToken(pushToken: String): ResponseWrapper<Unit> }
19
null
5
29
05c23fc5013b592c556997f2a54492ad9a0a0e75
212
virusafe-android
Apache License 2.0
source/service/src/test/kotlin/ketchup/service/controllers/ItemControllerTest.kt
arshvirc
771,191,483
false
{"Kotlin": 166407, "CSS": 71990}
package ketchup.service.controllers import ketchup.console.TodoItem import ketchup.service.Program import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.io.File import java.io.PrintWriter import java.sql.DriverManager import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Date internal class ItemControllerTest : AbstractTest() { @Test fun addControllerTestOneItemNoTags() { val dbURL = "jdbc:sqlite:./AddControllerTest.db" val prog = Program(dbURL) val dbFile = File("./AddControllerTest.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let{ ItemController(it)} if(controller != null) { val title = "my first task" val desc = "a description" val deadline = Date(1672019404) val priority = 2 val item = TodoItem(title, desc, deadline, priority) val id = controller.addItem(item, 0) val testQueryString = "SELECT * FROM TodoItems WHERE item_id = ${id}" val query = conn!!.createStatement() val result = query.executeQuery(testQueryString) assertTrue(result.next()) assertTrue(result.getString("title") == title) assertTrue(result.getString("description") == desc) assertTrue(result.getString("deadline") == deadline.toString()) assertTrue(result.getInt("priority") == priority) assertFalse(result.next()) // should be one row } prog.close() deleteFile("./AddControllerTest.db") } @Test fun addControllerTestOneItemWithTags() { val dbURL = "jdbc:sqlite:./AddControllerTest.db" val prog = Program(dbURL) val dbFile = File("./AddControllerTest.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let{ ItemController(it) } if (controller != null) { val itemTitle = "my first task" val item = TodoItem(title = itemTitle) val tags = listOf("cs 346", "blue", "cs 350") for (tag in tags) { item.addTag(tag) } val id = controller.addItem(item, 0) val query = conn!!.createStatement() val itemFinderQueryString = "SELECT * FROM TodoItems WHERE title='my first task'" var result = query.executeQuery(itemFinderQueryString) assertTrue(result.next()) // get the item id from the result assertTrue(id == result.getInt("item_id")) assertFalse(result.next()) // should be one item // use the id to look up tags in the tags table val pairFinderQueryString = "SELECT tag FROM ItemTags WHERE item_id='${id}'" result = query.executeQuery(pairFinderQueryString) var i = 0 while (result.next()) { assertTrue(result.getString("tag") == tags[i]) ++i } assertTrue(i == tags.size) } prog.close() deleteFile("./AddControllerTest.db") } @Test fun addControllerTestOneItemNoTagsNullDeadline() { val dbURL = "jdbc:sqlite:./AddControllerTest.db" val prog = Program(dbURL) val dbFile = File("./AddControllerTest.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let{ ItemController(it)} if(controller != null) { val title = "my first task" val desc = "a description" val deadline = null val priority = 2 val item = TodoItem(title, desc, deadline, priority) val id = controller.addItem(item, 0) val testQueryString = "SELECT * FROM TodoItems WHERE item_id = ${id}" val query = conn!!.createStatement() val result = query.executeQuery(testQueryString) assertTrue(result.next()) assertTrue(result.getString("title") == title) assertTrue(result.getString("description") == desc) assertTrue(result.getString("deadline") == "NULL") assertTrue(result.getInt("priority") == priority) assertFalse(result.next()) // should be one row } prog.close() deleteFile("./AddControllerTest.db") } @Test fun editControllerTestOneItemRemoveTags() { val dbURL = "jdbc:sqlite:./EditControllerTest.db" val prog = Program(dbURL) val dbFile = File("./EditControllerTest.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let{ ItemController(it) } if (controller != null) { val query = conn!!.createStatement() // add item val itemTitle = "my first task" val itemDescription = "a cool task that's not annoying at all" val itemDeadline = Date( 1672019403) val itemPriority = 3 val item = TodoItem(itemTitle, itemDescription, itemDeadline, itemPriority) val tags = listOf("cs 346", "blue", "cs 350") for (tag in tags) { item.addTag(tag) } val id = controller.addItem(item, 0) // second item to replace val newTitle = "NEW TITLE" val newDesc = "NEW DESCRIPTION" val newDeadline = Date(1672019404) val newPriority = 2 val newItem = TodoItem(newTitle, newDesc, newDeadline, newPriority, id = id) controller.editItem(newItem) val pairFinderQueryString = "SELECT tag FROM ItemTags WHERE item_id='${id}'" val result = query.executeQuery(pairFinderQueryString) assertFalse(result.next()) // should be no more tags } prog.close() deleteFile("./EditControllerTest.db") } @Test fun editControllerTestOneItemAddTags() { val dbURL = "jdbc:sqlite:./EditControllerTest.db" val prog = Program(dbURL) val dbFile = File("./EditControllerTest.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let{ ItemController(it) } if (controller != null) { val query = conn!!.createStatement() // add item val itemTitle = "my first task" val itemDescription = "a cool task that's not annoying at all" val itemDeadline = Date( 1672019403) val itemPriority = 3 val item = TodoItem(itemTitle, itemDescription, itemDeadline, itemPriority) val tags = listOf("cs 346", "blue", "cs 350") for (tag in tags) { item.addTag(tag) } val id = controller.addItem(item, 0) // second item to replace val newTitle = "NEW TITLE" val newDesc = "NEW DESCRIPTION" val newDeadline = Date(1672019404) val newPriority = 2 val newItem = TodoItem(newTitle, newDesc, newDeadline, newPriority, id = id) val newTags = listOf("cs 346", "blue", "cs 350", "intellij", "kotlin") for (tag in newTags) { newItem.addTag(tag) } controller.editItem(newItem) val pairFinderQueryString = "SELECT tag FROM ItemTags WHERE item_id='${id}'" val result = query.executeQuery(pairFinderQueryString) var i = 0 while (result.next()) { assertTrue(result.getString("tag") == newTags[i]) ++i } assertTrue(i == newTags.size) } prog.close() deleteFile("./EditControllerTest.db") } @Test fun deleteItemTest() { val dbUrl = "jdbc:sqlite:./deleteItem.db" val prog = Program(dbUrl) val dbFile = File("./deleteItem.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let { ItemController(it) } if(controller != null) { val itemTitle = "my first task" val item = TodoItem(title = itemTitle) val tags = listOf("cs 346", "blue", "cs 350") for (tag in tags) { item.addTag(tag) } val item2 = TodoItem(title="my second title") controller.addItem(item, 0) // itemId == 1 controller.addItem(item2, 0) // itemId == 2 controller.deleteItem(1) val listController = conn?.let { ListController(it) } if(listController != null) { val list = listController.getAllLists() assertEquals(list.size, 1) assertEquals(list[0].list[0].id, 1) } controller.deleteItem(2) if(listController != null) { val list = listController.getAllLists() assertEquals(list.size, 1) } } prog.close() deleteFile("./deleteItem.db") } @Test fun getItemTest() { val dbUrl = "jdbc:sqlite:./getItem.db" val prog = Program(dbUrl) val dbFile = File("./getItem.db") createBlankFile(dbFile) val conn = prog.run() val controller = conn?.let { ItemController(it) } if(controller != null) { val itemTitle = "my first task" val item = TodoItem(title = itemTitle) var id = controller.addItem(item, 0) val getItemResponse = controller.getTodoItem(id) val getItem = getItemResponse?.item if (getItem != null) { assertEquals(getItem.title, itemTitle) assertEquals(getItem.id,id) } } prog.close() deleteFile("./getItem.db") } }
0
Kotlin
0
0
15f965cf1e8e60cb928fbcc3a8769a1ff6ee301d
9,938
ketchup
MIT License
apps/etterlatte-vilkaarsvurdering/src/test/kotlin/no/nav/etterlatte/vilkaarsvurdering/VilkaarsvurderingRoutesTest.kt
navikt
417,041,535
false
{"Kotlin": 6309786, "TypeScript": 1570250, "Handlebars": 27542, "Shell": 12438, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.vilkaarsvurdering import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.server.application.log import io.ktor.server.config.HoconApplicationConfig import io.ktor.server.testing.testApplication import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.runBlocking import no.nav.etterlatte.funksjonsbrytere.DummyFeatureToggleService import no.nav.etterlatte.libs.common.behandling.BehandlingType import no.nav.etterlatte.libs.common.behandling.DetaljertBehandling import no.nav.etterlatte.libs.common.behandling.SakType import no.nav.etterlatte.libs.common.behandling.SisteIverksatteBehandling import no.nav.etterlatte.libs.common.objectMapper import no.nav.etterlatte.libs.common.toJson import no.nav.etterlatte.libs.common.vilkaarsvurdering.Utfall import no.nav.etterlatte.libs.common.vilkaarsvurdering.VilkaarType import no.nav.etterlatte.libs.common.vilkaarsvurdering.VilkaarsvurderingDto import no.nav.etterlatte.libs.common.vilkaarsvurdering.VilkaarsvurderingUtfall import no.nav.etterlatte.libs.database.DataSourceBuilder import no.nav.etterlatte.libs.database.POSTGRES_VERSION import no.nav.etterlatte.libs.database.migrate import no.nav.etterlatte.libs.ktor.AZURE_ISSUER import no.nav.etterlatte.libs.ktor.restModule import no.nav.etterlatte.libs.testdata.behandling.VirkningstidspunktTestData import no.nav.etterlatte.libs.testdata.grunnlag.GrunnlagTestData import no.nav.etterlatte.libs.vilkaarsvurdering.VurdertVilkaarsvurderingResultatDto import no.nav.etterlatte.token.BrukerTokenInfo import no.nav.etterlatte.vilkaarsvurdering.klienter.BehandlingKlient import no.nav.etterlatte.vilkaarsvurdering.klienter.GrunnlagKlient import no.nav.security.mock.oauth2.MockOAuth2Server import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.testcontainers.containers.PostgreSQLContainer import org.testcontainers.junit.jupiter.Container import testsupport.buildTestApplicationConfigurationForOauth import java.util.UUID import javax.sql.DataSource @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class VilkaarsvurderingRoutesTest { @Container private val postgreSQLContainer = PostgreSQLContainer<Nothing>("postgres:$POSTGRES_VERSION") private val server = MockOAuth2Server() private lateinit var hoconApplicationConfig: HoconApplicationConfig private val behandlingKlient = mockk<BehandlingKlient>() private val grunnlagKlient = mockk<GrunnlagKlient>() private val featureToggleService = DummyFeatureToggleService() private lateinit var vilkaarsvurderingServiceImpl: VilkaarsvurderingService private lateinit var ds: DataSource @BeforeAll fun before() { server.start() val httpServer = server.config.httpServer hoconApplicationConfig = buildTestApplicationConfigurationForOauth(httpServer.port(), AZURE_ISSUER, CLIENT_ID) postgreSQLContainer.start() ds = DataSourceBuilder.createDataSource( postgreSQLContainer.jdbcUrl, postgreSQLContainer.username, postgreSQLContainer.password, ).also { it.migrate() } vilkaarsvurderingServiceImpl = VilkaarsvurderingService( VilkaarsvurderingRepository(ds, DelvilkaarRepository()), behandlingKlient, grunnlagKlient, featureToggleService, ) coEvery { behandlingKlient.hentBehandling(any(), any()) } returns detaljertBehandling() coEvery { behandlingKlient.kanSetteBehandlingStatusVilkaarsvurdert(any(), any()) } returns true coEvery { behandlingKlient.settBehandlingStatusVilkaarsvurdert(any(), any()) } returns true coEvery { behandlingKlient.settBehandlingStatusOpprettet(any(), any(), any()) } returns true coEvery { behandlingKlient.harTilgangTilBehandling(any(), any()) } returns true coEvery { grunnlagKlient.hentGrunnlag(any(), any(), any()) } returns GrunnlagTestData().hentOpplysningsgrunnlag() } @AfterEach fun afterEach() { ds.connection.use { it.prepareStatement("TRUNCATE vilkaarsvurdering CASCADE;").execute() } } @AfterAll fun after() { server.shutdown() postgreSQLContainer.stop() } private val token: String by lazy { server.issueToken( issuerId = AZURE_ISSUER, audience = CLIENT_ID, claims = mapOf( "navn" to "<NAME>", "NAVident" to "Saksbehandler01", ), ).serialize() } @Test fun `skal hente vilkaarsvurdering`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val response = client.get("/api/vilkaarsvurdering/$behandlingId") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vilkaarsvurdering = objectMapper.readValue(response.bodyAsText(), VilkaarsvurderingDto::class.java) val vilkaar = vilkaarsvurdering.vilkaar.first { it.hovedvilkaar.type == VilkaarType.BP_DOEDSFALL_FORELDER } assertEquals(HttpStatusCode.OK, response.status) assertEquals(behandlingId, vilkaarsvurdering.behandlingId) assertEquals(VilkaarType.BP_DOEDSFALL_FORELDER, vilkaar.hovedvilkaar.type) assertEquals("§ 18-4", vilkaar.hovedvilkaar.lovreferanse.paragraf) assertEquals("Dødsfall forelder", vilkaar.hovedvilkaar.tittel) assertEquals( """ For å ha rett på ytelsen må en eller begge foreldre være registrer død i folkeregisteret eller hos utenlandske myndigheter. """.trimIndent(), vilkaar.hovedvilkaar.beskrivelse, ) assertEquals("https://lovdata.no/lov/1997-02-28-19/%C2%A718-4", vilkaar.hovedvilkaar.lovreferanse.lenke) assertNull(vilkaar.vurdering) } } @Test fun `skal returnere no content dersom en vilkaarsvurdering ikke finnes`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val nyBehandlingId = UUID.randomUUID() val response = client.get("/api/vilkaarsvurdering/$nyBehandlingId") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(response.status, HttpStatusCode.NoContent) } } @Test fun `skal returnere not found dersom saksbehandler ikke har tilgang til behandlingen`() { val behandlingKlient = mockk<BehandlingKlient>() val nyBehandlingId = UUID.randomUUID() coEvery { behandlingKlient.harTilgangTilBehandling(nyBehandlingId, any()) } returns false testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val response = client.get("/api/vilkaarsvurdering/$nyBehandlingId") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(response.status, HttpStatusCode.NotFound) coVerify(exactly = 1) { behandlingKlient.harTilgangTilBehandling(nyBehandlingId, any()) } } } @Test fun `skal kaste feil dersom virkningstidspunkt ikke finnes ved opprettelse`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val nyBehandlingId = UUID.randomUUID() coEvery { behandlingKlient.hentBehandling(nyBehandlingId, any()) } returns detaljertBehandling().apply { every { virkningstidspunkt } returns null } val response = client.post("/api/vilkaarsvurdering/$nyBehandlingId/opprett") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(HttpStatusCode.PreconditionFailed, response.status) } } @Test fun `skal oppdatere en vilkaarsvurdering med et vurdert hovedvilkaar`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val vilkaarsvurdering = opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val vurdertVilkaarDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering.hentVilkaarMedHovedvilkaarType(VilkaarType.BP_DOEDSFALL_FORELDER)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( VilkaarType.BP_DOEDSFALL_FORELDER, Utfall.OPPFYLT, ), unntaksvilkaar = null, kommentar = "Søker oppfyller vilkåret", ) val oppdatertVilkaarsvurderingResponse = client.post("/api/vilkaarsvurdering/$behandlingId") { setBody(vurdertVilkaarDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val oppdatertVilkaarsvurdering = objectMapper .readValue(oppdatertVilkaarsvurderingResponse.bodyAsText(), VilkaarsvurderingDto::class.java) val oppdatertVilkaar = oppdatertVilkaarsvurdering.vilkaar.find { it.hovedvilkaar.type == vurdertVilkaarDto.hovedvilkaar.type } assertEquals(HttpStatusCode.OK, oppdatertVilkaarsvurderingResponse.status) assertEquals(behandlingId, oppdatertVilkaarsvurdering.behandlingId) assertEquals(vurdertVilkaarDto.hovedvilkaar.type, oppdatertVilkaar?.hovedvilkaar?.type) assertEquals(vurdertVilkaarDto.hovedvilkaar.resultat, oppdatertVilkaar?.hovedvilkaar?.resultat) assertEquals(vurdertVilkaarDto.kommentar, oppdatertVilkaar?.vurdering?.kommentar) assertEquals("Saksbehandler01", oppdatertVilkaar?.vurdering?.saksbehandler) assertNotNull(oppdatertVilkaar?.vurdering?.tidspunkt) } } @Test fun `skal opprette vurdering paa hovedvilkaar og endre til vurdering paa unntaksvilkaar`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val vilkaarsvurdering = opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val vurdertVilkaarDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering .hentVilkaarMedHovedvilkaarType(VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( type = VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP, resultat = Utfall.OPPFYLT, ), kommentar = "Søker oppfyller hovedvilkåret ${VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP}", ) client.post("/api/vilkaarsvurdering/$behandlingId") { setBody(vurdertVilkaarDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vurdertVilkaar = vilkaarsvurderingServiceImpl.hentVilkaarsvurdering(behandlingId)!! .vilkaar.first { it.hovedvilkaar.type == vurdertVilkaarDto.hovedvilkaar.type } assertNotNull(vurdertVilkaar) assertNotNull(vurdertVilkaar.vurdering) assertNotNull(vurdertVilkaar.hovedvilkaar.resultat) assertEquals(Utfall.OPPFYLT, vurdertVilkaar.hovedvilkaar.resultat) val vurdertVilkaarMedUnntakDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering .hentVilkaarMedHovedvilkaarType(VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( type = VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP, resultat = Utfall.IKKE_OPPFYLT, ), unntaksvilkaar = VilkaarTypeOgUtfall( type = VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP_UNNTAK_AVDOED_IKKE_FYLT_26_AAR, resultat = Utfall.OPPFYLT, ), kommentar = "Søker oppfyller unntaksvilkåret " + "${VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP_UNNTAK_AVDOED_IKKE_FYLT_26_AAR}", ) client.post("/api/vilkaarsvurdering/$behandlingId") { setBody(vurdertVilkaarMedUnntakDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vurdertVilkaarPaaUnntak = vilkaarsvurderingServiceImpl.hentVilkaarsvurdering(behandlingId)!! .vilkaar.first { it.hovedvilkaar.type == vurdertVilkaarDto.hovedvilkaar.type } assertEquals(Utfall.IKKE_OPPFYLT, vurdertVilkaarPaaUnntak.hovedvilkaar.resultat) assertNotNull(vurdertVilkaarPaaUnntak.vurdering) assertNotNull(vurdertVilkaarPaaUnntak.unntaksvilkaar) vurdertVilkaarPaaUnntak.unntaksvilkaar.forEach { if (it.type === VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP_UNNTAK_AVDOED_IKKE_FYLT_26_AAR) { assertEquals(Utfall.OPPFYLT, it.resultat) } else { assertNull(it.resultat) } } } } @Test fun `skal nullstille et vurdert hovedvilkaar fra vilkaarsvurdering`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val vilkaarsvurdering = opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val vurdertVilkaarDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering.hentVilkaarMedHovedvilkaarType(VilkaarType.BP_DOEDSFALL_FORELDER)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( type = VilkaarType.BP_DOEDSFALL_FORELDER, resultat = Utfall.OPPFYLT, ), kommentar = "Søker oppfyller vilkåret", ) client.post("/api/vilkaarsvurdering/$behandlingId") { setBody(vurdertVilkaarDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vurdertVilkaar = vilkaarsvurderingServiceImpl.hentVilkaarsvurdering(behandlingId)!! .vilkaar.first { it.hovedvilkaar.type == vurdertVilkaarDto.hovedvilkaar.type } assertNotNull(vurdertVilkaar) assertNotNull(vurdertVilkaar.vurdering) assertNotNull(vurdertVilkaar.hovedvilkaar.resultat) val response = client .delete("/api/vilkaarsvurdering/$behandlingId/${vurdertVilkaarDto.vilkaarId}") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vurdertVilkaarSlettet = vilkaarsvurderingServiceImpl.hentVilkaarsvurdering(behandlingId)!!.vilkaar .first { it.hovedvilkaar.type == vurdertVilkaarDto.hovedvilkaar.type } assertEquals(HttpStatusCode.OK, response.status) assertNull(vurdertVilkaarSlettet.vurdering) assertNull(vurdertVilkaarSlettet.hovedvilkaar.resultat) vurdertVilkaarSlettet.unntaksvilkaar.forEach { assertNull(it.resultat) } } } @Test fun `skal sette og nullstille totalresultat for en vilkaarsvurdering`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val resultat = VurdertVilkaarsvurderingResultatDto( resultat = VilkaarsvurderingUtfall.OPPFYLT, kommentar = "Søker oppfyller vurderingen", ) val oppdatertVilkaarsvurderingResponse = client.post("/api/vilkaarsvurdering/resultat/$behandlingId") { setBody(resultat.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val oppdatertVilkaarsvurdering = objectMapper .readValue(oppdatertVilkaarsvurderingResponse.bodyAsText(), VilkaarsvurderingDto::class.java) assertEquals(HttpStatusCode.OK, oppdatertVilkaarsvurderingResponse.status) assertEquals(behandlingId, oppdatertVilkaarsvurdering.behandlingId) assertEquals(resultat.resultat, oppdatertVilkaarsvurdering?.resultat?.utfall) assertEquals(resultat.kommentar, oppdatertVilkaarsvurdering?.resultat?.kommentar) assertEquals("Saksbehandler01", oppdatertVilkaarsvurdering?.resultat?.saksbehandler) assertNotNull(oppdatertVilkaarsvurdering?.resultat?.tidspunkt) val sletteResponse = client.delete("/api/vilkaarsvurdering/resultat/$behandlingId") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val slettetVilkaarsvurdering = objectMapper .readValue(sletteResponse.bodyAsText(), VilkaarsvurderingDto::class.java) assertEquals(HttpStatusCode.OK, sletteResponse.status) assertEquals(behandlingId, slettetVilkaarsvurdering.behandlingId) assertEquals(null, slettetVilkaarsvurdering?.resultat) } } @Test fun `skal ikke kunne endre eller slette vilkaar naar totalresultat er satt`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val vilkaarsvurdering = opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val resultat = VurdertVilkaarsvurderingResultatDto( resultat = VilkaarsvurderingUtfall.OPPFYLT, kommentar = "Søker oppfyller vurderingen", ) client.post("/api/vilkaarsvurdering/resultat/$behandlingId") { setBody(resultat.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vurdertVilkaarDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering.hentVilkaarMedHovedvilkaarType(VilkaarType.BP_DOEDSFALL_FORELDER)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( VilkaarType.BP_DOEDSFALL_FORELDER, Utfall.OPPFYLT, ), unntaksvilkaar = null, kommentar = "Søker oppfyller vilkåret", ) client.post("/api/vilkaarsvurdering/$behandlingId") { setBody(vurdertVilkaarDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") }.let { assertEquals(HttpStatusCode.PreconditionFailed, it.status) } client.delete("/api/vilkaarsvurdering/$behandlingId/${vurdertVilkaarDto.vilkaarId}") { setBody(vurdertVilkaarDto.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") }.let { assertEquals(HttpStatusCode.PreconditionFailed, it.status) } } } @Test fun `revurdering skal kopiere siste vilkaarsvurdering ved opprettele som default`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val resultat = VurdertVilkaarsvurderingResultatDto( resultat = VilkaarsvurderingUtfall.OPPFYLT, kommentar = "Søker oppfyller vurderingen", ) client.post("/api/vilkaarsvurdering/resultat/$behandlingId") { setBody(resultat.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val revurderingBehandlingId = UUID.randomUUID() coEvery { behandlingKlient.hentBehandling(revurderingBehandlingId, any()) } returns detaljertBehandling().apply { every { behandlingType } returns BehandlingType.REVURDERING every { id } returns revurderingBehandlingId } coEvery { behandlingKlient.hentSisteIverksatteBehandling(any(), any()) } returns SisteIverksatteBehandling(behandlingId) val response = client.post("/api/vilkaarsvurdering/$revurderingBehandlingId/opprett") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vilkaarsvurdering = objectMapper.readValue(response.bodyAsText(), VilkaarsvurderingDto::class.java) assertEquals(HttpStatusCode.OK, response.status) assertEquals(revurderingBehandlingId, vilkaarsvurdering.behandlingId) assertTrue(vilkaarsvurdering.resultat != null) } } @Test fun `revurdering skal ikke kopiere siste vilkaarsvurdering naar kopierVedRevurdering er false`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val resultat = VurdertVilkaarsvurderingResultatDto( resultat = VilkaarsvurderingUtfall.OPPFYLT, kommentar = "Søker oppfyller vurderingen", ) client.post("/api/vilkaarsvurdering/resultat/$behandlingId") { setBody(resultat.toJson()) header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val revurderingBehandlingId = UUID.randomUUID() coEvery { behandlingKlient.hentBehandling(revurderingBehandlingId, any()) } returns detaljertBehandling().apply { every { behandlingType } returns BehandlingType.REVURDERING every { id } returns revurderingBehandlingId } val response = client.post("/api/vilkaarsvurdering/$revurderingBehandlingId/opprett?kopierVedRevurdering=false") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } val vilkaarsvurdering = objectMapper.readValue(response.bodyAsText(), VilkaarsvurderingDto::class.java) assertEquals(HttpStatusCode.OK, response.status) assertEquals(revurderingBehandlingId, vilkaarsvurdering.behandlingId) assertTrue(vilkaarsvurdering.resultat == null) } } @Test fun `Skal slette eksisterende vilkaarsvurdering`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val response = client.delete("/api/vilkaarsvurdering/$behandlingId") { header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(HttpStatusCode.OK, response.status) assertEquals("", response.bodyAsText()) } } @Test fun `faar 401 hvis spoerring ikke har access token`() { testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val response = client.get("/api/vilkaarsvurdering/$behandlingId") assertEquals(HttpStatusCode.Unauthorized, response.status) } } @Test fun `statussjekk kalles paa en gang for aa sjekke tilstanden paa behandling`() { val behandlingKlient = mockk<BehandlingKlient>() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns detaljertBehandling() coEvery { behandlingKlient.kanSetteBehandlingStatusVilkaarsvurdert(any(), any()) } returns true coEvery { behandlingKlient.harTilgangTilBehandling(any(), any()) } returns true val vilkaarsvurderingServiceImpl = VilkaarsvurderingService( VilkaarsvurderingRepository(ds, DelvilkaarRepository()), behandlingKlient, grunnlagKlient, featureToggleService, ) testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) coVerify(exactly = 1) { behandlingKlient.kanSetteBehandlingStatusVilkaarsvurdert(any(), any()) } } } @Test fun `kan ikke opprette eller committe vilkaarsvurdering hvis statussjekk feiler`() { val behandlingKlient = mockk<BehandlingKlient>() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns detaljertBehandling() coEvery { behandlingKlient.kanSetteBehandlingStatusVilkaarsvurdert(any(), any()) } returns false coEvery { behandlingKlient.harTilgangTilBehandling(any(), any()) } returns true val vilkaarsvurderingServiceImpl = VilkaarsvurderingService( VilkaarsvurderingRepository(ds, DelvilkaarRepository()), behandlingKlient, grunnlagKlient, featureToggleService, ) testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val response = client.post("/api/vilkaarsvurdering/$behandlingId/opprett") { header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(HttpStatusCode.PreconditionFailed, response.status) coVerify(exactly = 0) { behandlingKlient.settBehandlingStatusVilkaarsvurdert(any(), any()) } } } @Test fun `skal ikke commite vilkaarsvurdering hvis statussjekk feiler ved sletting av totalvurdering`() { val behandlingKlient = mockk<BehandlingKlient>() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns detaljertBehandling() coEvery { behandlingKlient.settBehandlingStatusOpprettet(any(), any(), any()) } returns false coEvery { behandlingKlient.harTilgangTilBehandling(any(), any()) } returns true val vilkaarsvurderingServiceImpl = VilkaarsvurderingService( VilkaarsvurderingRepository(ds, DelvilkaarRepository()), behandlingKlient, grunnlagKlient, featureToggleService, ) testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } client.delete("/api/vilkaarsvurdering/resultat/$behandlingId") { header(HttpHeaders.Authorization, "Bearer $token") } } coVerify(exactly = 1) { behandlingKlient.settBehandlingStatusOpprettet(any(), any(), false) } coVerify(exactly = 0) { behandlingKlient.settBehandlingStatusOpprettet(any(), any(), true) } } @Test fun `kan ikke endre vilkaarsvurdering hvis statussjekk feiler`() { val behandlingKlient = mockk<BehandlingKlient>() coEvery { behandlingKlient.hentBehandling(any(), any()) } returns detaljertBehandling() coEvery { behandlingKlient.kanSetteBehandlingStatusVilkaarsvurdert(any(), any()) } returnsMany listOf( true, false, ) coEvery { behandlingKlient.harTilgangTilBehandling(any(), any()) } returns true val vilkaarsvurderingServiceImpl = VilkaarsvurderingService( VilkaarsvurderingRepository(ds, DelvilkaarRepository()), behandlingKlient, grunnlagKlient, featureToggleService, ) testApplication { environment { config = hoconApplicationConfig } application { restModule(this.log) { vilkaarsvurdering(vilkaarsvurderingServiceImpl, behandlingKlient) } } val vilkaarsvurdering = opprettVilkaarsvurdering(vilkaarsvurderingServiceImpl) val vurdertVilkaarDto = VurdertVilkaarDto( vilkaarId = vilkaarsvurdering .hentVilkaarMedHovedvilkaarType(VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP)?.id!!, hovedvilkaar = VilkaarTypeOgUtfall( type = VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP, resultat = Utfall.OPPFYLT, ), kommentar = "Søker oppfyller hovedvilkåret ${VilkaarType.BP_FORUTGAAENDE_MEDLEMSKAP}", ) val response = client.post("/api/vilkaarsvurdering/$behandlingId") { header(HttpHeaders.Authorization, "Bearer $token") header(HttpHeaders.ContentType, "application/json") setBody(vurdertVilkaarDto.toJson()) } assertEquals(HttpStatusCode.PreconditionFailed, response.status) val actual = vilkaarsvurderingServiceImpl.hentVilkaarsvurdering(behandlingId) assertEquals(vilkaarsvurdering, actual) } } private fun opprettVilkaarsvurdering(vilkaarsvurderingService: VilkaarsvurderingService): Vilkaarsvurdering = runBlocking { vilkaarsvurderingService.opprettVilkaarsvurdering(behandlingId, oboToken) } private fun detaljertBehandling() = mockk<DetaljertBehandling>().apply { every { id } returns UUID.randomUUID() every { sak } returns 1L every { sakType } returns SakType.BARNEPENSJON every { behandlingType } returns BehandlingType.FØRSTEGANGSBEHANDLING every { soeker } returns "10095512345" every { virkningstidspunkt } returns VirkningstidspunktTestData.virkningstidsunkt() every { revurderingsaarsak } returns null } private companion object { val behandlingId: UUID = UUID.randomUUID() val oboToken = BrukerTokenInfo.of("token", "s1", null, null, null) const val CLIENT_ID = "azure-id for saksbehandler" } }
9
Kotlin
0
6
e715675c319d4a0a826855615749573e45ae7a75
35,382
pensjon-etterlatte-saksbehandling
MIT License
kodein-di-erased/src/commonTest/kotlin/org/kodein/di/erased/ErasedTests_17_NewInstance.kt
Inego
229,547,014
true
{"Kotlin": 683683, "Java": 16368}
package org.kodein.di.erased import org.kodein.di.Kodein import org.kodein.di.newInstance import org.kodein.di.test.FixMethodOrder import org.kodein.di.test.MethodSorters import org.kodein.di.test.Person import kotlin.test.Test import kotlin.test.assertEquals @FixMethodOrder(MethodSorters.NAME_ASCENDING) class ErasedTests_17_NewInstance { class Wedding(val him: Person, val her: Person) @Test fun test_00_NewInstance() { val kodein = Kodein { bind<Person>(tag = "Author") with singleton { Person("Salomon") } bind<Person>(tag = "Spouse") with singleton { Person("Laila") } } val wedding by kodein.newInstance { Wedding(instance(tag = "Author"), instance(tag = "Spouse")) } assertEquals("Salomon", wedding.him.name) assertEquals("Laila", wedding.her.name) } @Test fun test_01_DirectNewInstance() { val kodein = Kodein.direct { bind<Person>(tag = "Author") with singleton { Person("Salomon") } bind<Person>(tag = "Spouse") with singleton { Person("Laila") } } val wedding = kodein.newInstance { Wedding(instance(tag = "Author"), instance(tag = "Spouse")) } assertEquals("Salomon", wedding.him.name) assertEquals("Laila", wedding.her.name) } }
0
null
0
0
7a25cde6fa8e998ddba2f9cb6275d902aa780b66
1,307
Kodein-DI
MIT License
app/src/main/java/sample/books/domain/dagger/BooksDomainModule.kt
annypatel
209,951,354
false
null
package sample.books.domain.dagger import sample.books.domain.FetchBooksUseCase import sample.books.domain.FetchBooksUseCaseImpl import sample.books.domain.FlattenBookGroupsUseCase import sample.books.domain.FlattenBookGroupsUseCaseImpl import sample.books.domain.GetBooksUseCase import sample.books.domain.GetBooksUseCaseImpl import sample.books.domain.SortBooksByNameUseCase import sample.books.domain.SortBooksByNameUseCaseImpl import sample.books.domain.SortBooksByWeekUseCase import sample.books.domain.SortBooksByWeekUseCaseImpl import sample.books.domain.SortBooksUseCase import sample.books.domain.SortBooksUseCaseImpl import dagger.Binds import dagger.Module /** * Module to inject domain use-cases into application component for books feature. */ @Module abstract class BooksDomainModule { @Binds abstract fun getBooksUseCase(getBooks: GetBooksUseCaseImpl): GetBooksUseCase @Binds abstract fun fetchBooksUseCase(fetchBooks: FetchBooksUseCaseImpl): FetchBooksUseCase @Binds abstract fun sortBooksUseCase(sortBooks: SortBooksUseCaseImpl): SortBooksUseCase @Binds abstract fun sortBooksByNameUseCase(sortBooksByName: SortBooksByNameUseCaseImpl): SortBooksByNameUseCase @Binds abstract fun sortBooksByWeekUseCase(sortBooksByWeek: SortBooksByWeekUseCaseImpl): SortBooksByWeekUseCase @Binds abstract fun flattenBookGroupsUseCase(flattenBookGroups: FlattenBookGroupsUseCaseImpl): FlattenBookGroupsUseCase }
0
Kotlin
0
0
9637b6158cbb8b78052919944c5fbf79076218d9
1,468
BooksSample
Apache License 2.0
data/src/test/java/com/me/data/quote/repository/QuoteRepositoryImplTest.kt
MohamedHatemAbdu
275,196,930
false
null
package com.me.data.quote.repository import com.me.data.quote.datasource.local.QuoteCacheDataSourceImpl import com.me.data.quote.datasource.remote.QuoteRemoteDataSourceImpl import com.me.data.quoteData import com.me.data.quoteEntity import io.reactivex.Completable import io.reactivex.Single import org.junit.Before import org.junit.Test import org.mockito.Mockito.* class QuoteRepositoryImplTest { private lateinit var repository: QuoteRepositoryImpl private val mockCacheDataSource: QuoteCacheDataSourceImpl = mock(QuoteCacheDataSourceImpl::class.java) private val mockRemoteDataSource: QuoteRemoteDataSourceImpl = mock(QuoteRemoteDataSourceImpl::class.java) private val id = quoteData.id private val cacheItem = quoteEntity.copy(description = "cache") private val remoteItem = quoteEntity.copy(description = "remote") private val throwable = Throwable() @Before fun setUp() { repository = QuoteRepositoryImpl(mockCacheDataSource, mockRemoteDataSource) } @Test fun `get quote cache fail fallback remote succeeds`() { // given `when`(mockCacheDataSource.getLatestQuote()).thenReturn(Single.error(throwable)) `when`(mockRemoteDataSource.getRandomQuote()).thenReturn(Single.just(remoteItem)) `when`(mockCacheDataSource.addQuote(remoteItem)).thenReturn(Single.just(remoteItem)) // when val test = repository.getQuote(false).test() // then verify(mockCacheDataSource).getLatestQuote() verify(mockRemoteDataSource).getRandomQuote() verify(mockCacheDataSource).addQuote(remoteItem) test.assertValue(remoteItem) } @Test fun `get quote cache fail fallback remote fails`() { // given `when`(mockCacheDataSource.getLatestQuote()).thenReturn(Single.error(throwable)) `when`(mockRemoteDataSource.getRandomQuote()).thenReturn(Single.error(throwable)) // when val test = repository.getQuote(false).test() // then verify(mockCacheDataSource).getLatestQuote() verify(mockRemoteDataSource).getRandomQuote() test.assertError(throwable) } @Test fun `get quote caches success`() { // given `when`(mockCacheDataSource.getLatestQuote()).thenReturn(Single.just(cacheItem)) // when val test = repository.getQuote(false).test() // then verify(mockCacheDataSource).getLatestQuote() test.assertValue(cacheItem) } @Test fun `get quote remote success`() { // given `when`(mockRemoteDataSource.getRandomQuote()).thenReturn(Single.just(remoteItem)) `when`(mockCacheDataSource.addQuote(remoteItem)).thenReturn(Single.just(remoteItem)) // when val test = repository.getQuote(true).test() // then verify(mockRemoteDataSource).getRandomQuote() verify(mockCacheDataSource).addQuote(remoteItem) test.assertValue(remoteItem) } @Test fun `get quote remote fail`() { // given `when`(mockRemoteDataSource.getRandomQuote()).thenReturn(Single.error(throwable)) // when val test = repository.getQuote(true).test() // then verify(mockRemoteDataSource).getRandomQuote() test.assertError(throwable) } @Test fun `clear quotes cache success`() { // given `when`(mockCacheDataSource.clearAllQuotes()).thenReturn(Completable.complete()) // when val test = repository.clearAllQuotes().test() // then verify(mockCacheDataSource).clearAllQuotes() test.assertComplete() } }
0
Kotlin
0
0
b875c147a1a7ee0591f3e1d0610f78379d9a5473
3,672
random-quote
Apache License 2.0
app/src/main/java/com/kashif/newsapp/presentation/navGraph/Route.kt
kashifansari786
804,837,818
false
{"Kotlin": 91890}
package com.kashif.newsapp.presentation.navGraph /** * Created by <NAME> on 19,May,2024 */ sealed class Route(val route:String) { object OnBoardingScreen:Route(route = "onBoardingScreen") object HomeScreen:Route(route = "homeScreen") object SearchScreen:Route(route = "searchScreen") object BookmarkScreen:Route(route = "bookmarkScreen") object DetailsScreen:Route(route = "detailsScreen") object AppStartNavigation:Route(route = "appStartNavigation") object NewsNavigation:Route(route = "newsNavigation") object NewsNavigatorScreen:Route(route = "newsNavigatorScreen") }
0
Kotlin
0
0
e6da12dc856b620af5776a168ec60df092c4b900
607
newsAppCompose
MIT License
publish-component/src/main/java/com/kotlin/android/publish/component/widget/article/view/event/PEvent.kt
R-Gang-H
538,443,254
false
null
package com.kotlin.android.publish.component.widget.article.view.event /** * 键盘事件(删除/回车/完成关闭键盘) * * Created on 2022/4/1. * * @author o.s */ enum class PEvent { /** * 上一个 */ PRE, /** * 下一个 */ NEXT, /** * 完成:关闭键盘 */ DONE }
0
Kotlin
0
1
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
284
Mtime
Apache License 2.0
app/src/main/java/dev/nynp/nothanks/NoThanksSettingsManager.kt
NewYearNewPhil
871,308,636
false
{"Kotlin": 22879}
package dev.nynp.nothanks import android.content.Context import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow data class BlockedView( val id: String, val name: String, var isBlocked: Boolean ) object SettingsManager { private lateinit var sharedPreferences: android.content.SharedPreferences private val _isBlockingEnabled = MutableStateFlow(true) val isBlockingEnabled = _isBlockingEnabled.asStateFlow() private val _blockedViews = MutableStateFlow<List<BlockedView>>(emptyList()) val blockedViews = _blockedViews.asStateFlow() fun init(context: Context) { sharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE) loadSettings() initializeBlockedViews(context) } private fun initializeBlockedViews(context: Context) { val initialBlockedViews = listOf( BlockedView("com.instagram.android:id/clips_viewer_view_pager", context.getString(R.string.instagram_reels_title), true), BlockedView("com.google.android.youtube:id/reel_player_page_container", context.getString(R.string.youtube_shorts_title), true) ) val savedBlockedViews = sharedPreferences.getStringSet("blocked_views", null) _blockedViews.value = if (savedBlockedViews != null) { initialBlockedViews.map { view -> view.copy(isBlocked = savedBlockedViews.contains(view.id)) } } else { initialBlockedViews } } fun setBlockingEnabled(enabled: Boolean) { _isBlockingEnabled.value = enabled sharedPreferences.edit().putBoolean("blocking_enabled", enabled).apply() } fun toggleBlockedView(id: String) { val updatedList = _blockedViews.value.map { view -> if (view.id == id) view.copy(isBlocked = !view.isBlocked) else view } _blockedViews.value = updatedList saveBlockedViews() } private fun loadSettings() { _isBlockingEnabled.value = sharedPreferences.getBoolean("blocking_enabled", true) } private fun saveBlockedViews() { val blockedViewIds = _blockedViews.value.filter { it.isBlocked }.map { it.id }.toSet() sharedPreferences.edit().putStringSet("blocked_views", blockedViewIds).apply() } }
2
Kotlin
0
1
50996f32ab45232edcc3d87b153f92b64b1ecb87
2,367
nothanks
MIT License
src/main/kotlin/jp/assasans/araumi/tx/server/ecs/IEntityTemplate.kt
AraumiTX
604,259,602
false
null
package jp.assasans.araumi.tx.server.ecs import kotlin.reflect.KClass import kotlin.reflect.full.findAnnotation import jp.assasans.araumi.tx.server.extensions.inject import jp.assasans.araumi.tx.server.protocol.ProtocolId interface IEntityTemplate val KClass<out IEntityTemplate>.templateId: Long get() = requireNotNull(findAnnotation<ProtocolId>()) { "No @ProtocolId annotation on template $this" }.id inline fun IEntityTemplate.entity(configPath: String?, block: IEntityBuilder.() -> Unit): IEntity { val entityRegistry: IEntityRegistry by inject() return EntityBuilder(entityRegistry.freeId) .also { it.templateAccessor(this::class.templateId, configPath) } .apply(block) .build() }
0
Kotlin
1
3
4828d26c8ff73b902015c0bf68996bbf4f4eb561
708
game-server
MIT License
src/main/kotlin/com/papsign/ktor/openapigen/modules/providers/ParameterProvider.kt
papsign
186,148,881
false
null
package com.papsign.ktor.openapigen.modules.providers import com.papsign.ktor.openapigen.OpenAPIGen import com.papsign.ktor.openapigen.model.operation.ParameterModel import com.papsign.ktor.openapigen.modules.ModuleProvider import com.papsign.ktor.openapigen.modules.OpenAPIModule interface ParameterProvider: OpenAPIModule { fun getParameters(apiGen: OpenAPIGen, provider: ModuleProvider<*>): List<ParameterModel<*>> }
24
Kotlin
35
172
8362dafa8a8b701983ad7d0119a15a12b863953f
427
Ktor-OpenAPI-Generator
Apache License 2.0
app/src/main/java/com/keru/novelly/ui/components/BottomNavBar.kt
jordan-jakisa
758,352,302
false
null
package com.keru.novelly.ui.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Explore import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.LocalLibrary import androidx.compose.material.icons.rounded.Menu import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.vector.ImageVector import androidx.navigation.NavController import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.compose.currentBackStackEntryAsState import com.keru.novelly.ui.navigation.Routes val bottomNavItems = listOf( BottomNavItem.Home, BottomNavItem.Search, BottomNavItem.MyLibrary, BottomNavItem.More ) @Composable fun BottomNavBar( navController: NavController ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentDestination = navBackStackEntry?.destination NavigationBar { bottomNavItems.forEachIndexed { index, item -> NavigationBarItem( alwaysShowLabel = true, selected = currentDestination?.hierarchy?.any { it.route == item.route } == true, onClick = { navController.navigate(item.route) { restoreState = true launchSingleTop = true /*popUpTo(navController.graph.findStartDestination().id) { saveState = true }*/ } }, icon = { Icon(imageVector = item.icon, contentDescription = item.label) }, label = { Text(text = item.label) } ) } } } sealed class BottomNavItem( val route: String, val icon: ImageVector, val label: String ) { data object Home : BottomNavItem( route = Routes.Home.path, icon = Icons.Rounded.Home, label = "Home" ) data object Search : BottomNavItem( route = Routes.Search.path, icon = Icons.Rounded.Explore, label = "Explore" ) data object MyLibrary : BottomNavItem( route = Routes.Downloads.path, icon = Icons.Rounded.LocalLibrary, label = "My Library" ) data object More : BottomNavItem( route = Routes.More.path, icon = Icons.Rounded.Menu, label = "More" ) }
0
null
0
4
e0d6a13de40ff3e3c9cc4d2d78cba07bbc85be97
2,677
chapterly
MIT License
library/implementations/timber/src/main/java/timber/log/BaseTree.kt
MFlisar
71,460,539
false
{"Kotlin": 138941}
package timber.log import android.util.Log import com.michaelflisar.lumberjack.implementation.timber.TimberLogger import com.michaelflisar.lumberjack.implementation.timber.data.StackData import java.io.PrintWriter import java.io.StringWriter abstract class BaseTree : Timber.Tree() { open fun isConsoleLogger(): Boolean = false // we overwrite all log functions because the base classes Timber.prepareLog is private and we need to make a small adjustment // to get correct line numbers for kotlin exceptions (only the IDE does convert the line limbers correctly based on a mapping table) override fun v(message: String?, vararg args: Any?) { prepareLog( Log.VERBOSE, null, message, *args ) } override fun v(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.VERBOSE, t, message, *args ) } override fun v(t: Throwable?) { prepareLog(Log.VERBOSE, t, null) } override fun d(message: String?, vararg args: Any?) { prepareLog(Log.DEBUG, null, message, *args) } override fun d(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.DEBUG, t, message, *args ) } override fun d(t: Throwable?) { prepareLog(Log.DEBUG, t, null) } override fun i(message: String?, vararg args: Any?) { prepareLog(Log.INFO, null, message, *args) } override fun i(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.INFO, t, message, *args ) } override fun i(t: Throwable?) { prepareLog(Log.INFO, t, null) } override fun w(message: String?, vararg args: Any?) { prepareLog(Log.WARN, null, message, *args) } override fun w(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.WARN, t, message, *args ) } override fun w(t: Throwable?) { prepareLog(Log.WARN, t, null) } override fun e(message: String?, vararg args: Any?) { prepareLog(Log.ERROR, null, message, *args) } override fun e(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.ERROR, t, message, *args ) } override fun e(t: Throwable?) { prepareLog(Log.ERROR, t, null) } override fun wtf(message: String?, vararg args: Any?) { prepareLog( Log.ASSERT, null, message, *args ) } override fun wtf(t: Throwable?, message: String?, vararg args: Any?) { prepareLog( Log.ASSERT, t, message, *args ) } override fun wtf(t: Throwable?) { prepareLog(Log.ASSERT, t, null) } override fun log(priority: Int, message: String?, vararg args: Any?) { prepareLog( priority, null, message, *args ) } override fun log(priority: Int, t: Throwable?, message: String?, vararg args: Any?) { prepareLog( priority, t, message, *args ) } override fun log(priority: Int, t: Throwable?) { prepareLog(priority, t, null) } override fun isLoggable(tag: String?, priority: Int): Boolean { return tag == null || (TimberLogger.filter?.isTagEnabled(this, tag) ?: true) } // copied from Timber.Tree because it's private in the base class private fun getStackTraceString(t: Throwable): String { // Don't replace this with Log.getStackTraceString() - it hides // UnknownHostException, which is not what we want. val sw = StringWriter(256) val pw = PrintWriter(sw, false) t.printStackTrace(pw) pw.flush() return sw.toString() } // -------------------- // custom code // -------------------- private fun prepareLog(priority: Int, t: Throwable?, message: String?, vararg args: Any?) { // custom: we create a stack data object val callStackCorrection = getCallStackCorrection() ?: 0 var stackData = getStackTrace() stackData = stackData.copy(callStackIndex = stackData.callStackIndex + callStackCorrection) // Consume tag even when message is not loggable so that next message is correctly tagged. @Suppress("NAME_SHADOWING") var message = message val customTag = super.getTag() val prefix = getPrefix(customTag, stackData) if (!isLoggable(customTag, priority)) { return } if (message != null && message.isEmpty()) { message = null } if (message == null) { if (t == null) { return // Swallow message if it's null and there's no throwable. } message = getStackTraceString(t) } else { if (args.isNotEmpty()) { message = String.format(message, *args) } if (t != null) { message += " - " + getStackTraceString(t).trimIndent() } } log(priority, prefix, message, t, stackData) } final override fun log( priority: Int, tag: String?, message: String, t: Throwable? ) { /* empty, we use our own function with StackData */ } abstract fun log( priority: Int, prefix: String, message: String, t: Throwable?, stackData: StackData ) // -------------------- // custom code - extended tag // -------------------- protected fun formatLine(prefix: String, message: String) = TimberLogger.formatter.formatLine(this, prefix, message) // -------------------- // custom code - extended tag // -------------------- private fun getPrefix(customTag: String?, stackData: StackData): String { return TimberLogger.formatter.formatLogPrefix(customTag, stackData) } // -------------------- // custom code - callstack depth // -------------------- companion object { internal const val CALL_STACK_INDEX = 4 } private val callStackCorrection = ThreadLocal<Int>() private fun getCallStackCorrection(): Int? { val correction = callStackCorrection.get() if (correction != null) { callStackCorrection.remove() } return correction } internal fun setCallStackCorrection(value: Int) { callStackCorrection.set(value) } private val stackTrace = ThreadLocal<StackData>() private fun getStackTrace(): StackData { val trace = stackTrace.get()!! stackTrace.remove() return trace } internal fun setStackTrace(trace: StackData) { stackTrace.set(trace) } }
2
Kotlin
7
42
5e97f50775d286f10e82599235bad788dbdccaf0
7,121
Lumberjack
Apache License 2.0
src/test/kotlin/tr/emreone/adventofcode/days/Day09Test.kt
EmRe-One
726,902,443
false
{"Kotlin": 91413, "Python": 18319}
package tr.emreone.adventofcode.days import org.junit.jupiter.api.Test import tr.emreone.kotlin_utils.Resources import tr.emreone.kotlin_utils.automation.solve internal class Day09Test { @Test fun `execute_tests`() { solve<Day09>(false) { Resources.resourceAsList("day09_example.txt") .joinToString("\n") part1 15 part2 1134 } } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
391
advent-of-code-2023
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/personrecord/integration/MultiNodeTestBase.kt
ministryofjustice
608,040,205
false
{"Kotlin": 215136, "PLpgSQL": 13812, "Shell": 2601, "Dockerfile": 1145, "Makefile": 160}
package uk.gov.justice.digital.hmpps.personrecord.integration import com.microsoft.applicationinsights.TelemetryClient import org.assertj.core.api.Assertions.assertThat import org.awaitility.kotlin.await import org.awaitility.kotlin.untilAsserted import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.BeforeEach import org.mockito.kotlin.eq import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.verification.VerificationMode import org.springframework.boot.builder.SpringApplicationBuilder import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest import uk.gov.justice.digital.hmpps.personrecord.HmppsPersonRecord import uk.gov.justice.digital.hmpps.personrecord.jpa.repository.PersonRepository import uk.gov.justice.digital.hmpps.personrecord.service.type.TelemetryEventType import uk.gov.justice.hmpps.sqs.HmppsQueueService import java.time.Duration abstract class MultiNodeTestBase { internal val courtCaseEventsTopic = (instance1.context().getBean("hmppsQueueService") as HmppsQueueService) .findByTopicId("courtcaseeventstopic") internal val courtCaseEventsQueue = (instance1.context().getBean("hmppsQueueService") as HmppsQueueService) .findByQueueId("cprcourtcaseeventsqueue") internal val cprDeliusOffenderEventsQueue = (instance1.context().getBean("hmppsQueueService") as HmppsQueueService) .findByQueueId("cprdeliusoffendereventsqueue") internal val telemetryClient = (instance1.context().getBean("telemetryClient") as TelemetryClient) internal val personRepository: PersonRepository = (instance1.context().getBean("personRepository") as PersonRepository) internal fun checkTelemetry( event: TelemetryEventType, expected: Map<String, String>, verificationMode: VerificationMode = times(1), ) { await.atMost(Duration.ofSeconds(3)) untilAsserted { verify(telemetryClient, verificationMode).trackEvent( eq(event.eventName), org.mockito.kotlin.check { assertThat(it).containsAllEntriesOf(expected) }, eq(null), ) } } @BeforeEach fun beforeEach() { personRepository.deleteAll() courtCaseEventsQueue?.sqsDlqClient!!.purgeQueue( PurgeQueueRequest.builder().queueUrl(courtCaseEventsQueue.dlqUrl).build(), ).get() courtCaseEventsQueue.sqsClient.purgeQueue( PurgeQueueRequest.builder().queueUrl(courtCaseEventsQueue.queueUrl).build(), ).get() cprDeliusOffenderEventsQueue?.sqsClient?.purgeQueue( PurgeQueueRequest.builder().queueUrl(cprDeliusOffenderEventsQueue.queueUrl).build(), ) cprDeliusOffenderEventsQueue?.sqsDlqClient?.purgeQueue( PurgeQueueRequest.builder().queueUrl(cprDeliusOffenderEventsQueue.dlqUrl).build(), ) } companion object { internal val instance1: SpringApplicationBuilder = SpringApplicationBuilder(HmppsPersonRecord::class.java) .profiles("test", "test-instance-1") internal val instance2: SpringApplicationBuilder = SpringApplicationBuilder(HmppsPersonRecord::class.java) .profiles("test", "test-instance-2") @JvmStatic @BeforeAll fun beforeAll() { instance1.run() instance2.run() } @JvmStatic @AfterAll fun afterAll() { instance1.context().close() instance2.context().close() } } }
5
Kotlin
2
1
489b6d5c3d75bfc96bed2883a82b9990f97b92f9
3,378
hmpps-person-record
MIT License
app/src/main/java/com/skelterlabs/events/PurchaseStartEvent.kt
SkelterLabsInc
365,889,870
false
null
package com.skelterlabs.events import com.skelterlabs.client.CustomField class PurchaseStartEvent : Event { override val type: EventType = EventType.PURCHASE_START override fun makeEventSpecificCustomField(): CustomField = mapOf() }
0
Kotlin
0
1
cf4a80f69b2365f13b475232bd5434de7a2d8aaa
239
aware-android-sdk
Apache License 2.0
qr-code/src/commonMain/kotlin/in/procyk/compose/qrcode/options/dsl/InternalQrShapesBuilderScope.kt
avan1235
705,304,457
false
{"Kotlin": 203607}
/** * Based on QRose by <NAME> from [Github](https://github.com/alexzhirkevich/qrose) * * MIT License * * Copyright (c) 2023 <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 `in`.procyk.compose.qrcode.options.dsl import `in`.procyk.compose.qrcode.options.* internal class InternalQrShapesBuilderScope( private val builder: QrOptions.Builder, centralSymmetry : Boolean, ) : QrShapesBuilderScope { init { builder.shapes = builder.shapes.copy( centralSymmetry = centralSymmetry ) } override var pattern: QrCodeShape get() = builder.shapes.code set(value) = with(builder){ shapes = shapes.copy( code = value ) } override var darkPixel: QrPixelShape get() = builder.shapes.darkPixel set(value) = with(builder){ shapes = shapes.copy( darkPixel = value ) } override var lightPixel: QrPixelShape get() = builder.shapes.lightPixel set(value) = with(builder){ shapes = shapes.copy( lightPixel = value ) } override var ball: QrBallShape get() = builder.shapes.ball set(value) = with(builder){ shapes = shapes.copy( ball = value ) } override var frame: QrFrameShape get() = builder.shapes.frame set(value) = with(builder){ shapes = shapes.copy( frame = value ) } }
1
Kotlin
0
4
93b9ff7354194d3f9754e1f292cd1cfd4a1743c6
2,596
compose-extensions
MIT License
src/sorting/Main.kt
ArtemBotnev
136,745,749
false
{"Kotlin": 79256, "Shell": 292}
package sorting import heaps.SortHeap import utils.Timer import java.util.* import kotlin.math.sign fun main(args: Array<String>) { // source arrays val array = arrayOf(10, 123, 34, 205, 0, 75, 94, 75, -92, 345, 12, 73, 110, 542, 243, 315, -54) val bigArray = Array(5_000) { Random().nextInt(10_000) } // apply bubble sort sort(array) { bubbleSort(it) } sort(bigArray) { bubbleSort(it) } // apply selection sort sort(array) { selectSort(it) } sort(bigArray) { selectSort(it) } // apply insert sort sort(array) { insertSort(it) } sort(bigArray) { insertSort(it) } // apply quick sort sort(array) { quickSort(it) } sort(bigArray) { quickSort(it) } // apply right edge pivot quick sort sort(array) { rightEdgePivotQuickSort(it) } sort(bigArray) { rightEdgePivotQuickSort(it) } // apply quick sort with median as a pivot sort(array) { medianQuickSort(it) } sort(bigArray) { medianQuickSort(it) } // apply merge sort sort(array) { mergeSort(it) } sort(bigArray) { mergeSort(it) } // apply Shell sort sort(array) { shellSort(it) } sort(bigArray) { shellSort(it) } // apply Heap sort println("Heap sort:") sort(array) { SortHeap(it.size).sort(it) } println("Heap sort:") sort(bigArray) { SortHeap(it.size).sort(it) } } private inline fun <T> sort(arr: Array<T>, sortFin: (Array<T>) -> Array<T>) { val timer = Timer() val arrCopy = Arrays.copyOf(arr, arr.size) timer.start() sortFin(arrCopy) val arraySize = if (arrCopy.size < 1_000) "small" else "big" print("For $arraySize array ") println(timer.stopAndShowTime()) println() }
0
Kotlin
0
0
530c02e5d769ab0a49e7c3a66647dd286e18eb9d
1,694
Algorithms-and-Data-Structures
MIT License
compiler/util-klib-abi/src/org/jetbrains/kotlin/library/abi/LibraryAbi.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.library.abi import org.jetbrains.kotlin.library.abi.impl.AbiSignatureVersions /** * The result of reading ABI from KLIB. * * @property manifest Information from the manifest that may be useful. * @property uniqueName The library's unique name that is a part of the library ABI. * Corresponds to the `unique_name` manifest property. * @property signatureVersions The versions of signatures supported by the KLIB. Note that not every [AbiSignatureVersion] * which is supported by the KLIB is also supported by the ABI reader. To check this please use * [AbiSignatureVersion.isSupportedByAbiReader]. An attempt to obtain a signature of unsupported version will result * in an exception. See also [AbiSignatures.get]. * @property topLevelDeclarations The list of top-level declarations. */ @ExperimentalLibraryAbiReader class LibraryAbi( val manifest: LibraryManifest, val uniqueName: String, val signatureVersions: Set<AbiSignatureVersion>, val topLevelDeclarations: AbiTopLevelDeclarations ) /** * The representation of the version of IR signatures supported by a KLIB. * * @property versionNumber The unique version number of the IR signature. * @property isSupportedByAbiReader Whether this IR signature version is supported by the current implementation of * the ABI reader. If it's not supported then such signatures can't be read by the ABI reader, and the version itself * just serves for information purposes. * @property description Brief description of the IR signature version, if available. To be used purely for discovery * purposes by ABI reader clients. Warning: The description text may be freely changed in the future. So, it should * NEVER be used for making ABI snapshots. */ @ExperimentalLibraryAbiReader interface AbiSignatureVersion { val versionNumber: Int val isSupportedByAbiReader: Boolean val description: String? companion object { /** All [AbiSignatureVersion]s supported by the current implementation of the ABI reader. */ val allSupportedByAbiReader: List<AbiSignatureVersion> get() = AbiSignatureVersions.Supported.entries /** * A function to get an instance of [AbiSignatureVersion] by the unique [versionNumber]. */ fun resolveByVersionNumber(versionNumber: Int): AbiSignatureVersion = AbiSignatureVersions.resolveByVersionNumber(versionNumber) } } /** * A set of ABI signatures for a specific [AbiDeclaration]. This set can contain at most one signature per an [AbiSignatureVersion]. */ @ExperimentalLibraryAbiReader interface AbiSignatures { /** * Returns the signature of the specified [AbiSignatureVersion]. * * - If the signature version is not supported by the ABI reader (according to [AbiSignatureVersion.isSupportedByAbiReader]) * then throw an exception. * - If the signature version is supported by the ABI reader, but the signature is unavailable for some other reason * (e.g. a particular type of declaration misses a signature of a particular version), then return `null`. **/ operator fun get(signatureVersion: AbiSignatureVersion): String? } /** * Simple name. * Examples: "TopLevelClass", "topLevelFun", "List", "EMPTY". */ @ExperimentalLibraryAbiReader @JvmInline value class AbiSimpleName(val value: String) : Comparable<AbiSimpleName> { init { require(AbiCompoundName.SEPARATOR !in value && AbiQualifiedName.SEPARATOR !in value) { "Simple name contains illegal characters: $value" } } override fun compareTo(other: AbiSimpleName) = value.compareTo(other.value) override fun toString() = value } /** * Compound name. An equivalent of one or more [AbiSimpleName]s which are concatenated with dots. * Examples: "TopLevelClass", "topLevelFun", "List", "CharRange.Companion.EMPTY". */ @ExperimentalLibraryAbiReader @JvmInline value class AbiCompoundName(val value: String) : Comparable<AbiCompoundName> { init { require(AbiQualifiedName.SEPARATOR !in value) { "Compound name contains illegal characters: $value" } } /** All name segments comprising this compound name. */ val nameSegments: List<AbiSimpleName> get() = value.split(SEPARATOR).map(::AbiSimpleName) /** The count of name segments comprising this compound name. */ val nameSegmentsCount: Int get() = value.count { it == SEPARATOR } + 1 /** The right-most name segment of this compound name. */ val simpleName: AbiSimpleName get() = AbiSimpleName(value.substringAfterLast(SEPARATOR)) override fun compareTo(other: AbiCompoundName) = value.compareTo(other.value) override fun toString() = value /** * Whether a declaration with `this` instance of [AbiCompoundName] is a container of a declaration with `member` [AbiCompoundName]. * * Examples: * ``` * AbiCompoundName("") isContainerOf AbiCompoundName(<any>) == true * AbiCompoundName("foo.bar") isContainerOf AbiCompoundName("foo.bar.baz.qux") == true * AbiCompoundName("foo.bar") isContainerOf AbiCompoundName("foo.bar.baz") == true * AbiCompoundName("foo.bar") isContainerOf AbiCompoundName("foo.barbaz") == false * AbiCompoundName("foo.bar") isContainerOf AbiCompoundName("foo.bar") == false * AbiCompoundName("foo.bar") isContainerOf AbiCompoundName("foo") == false * ``` */ infix fun isContainerOf(member: AbiCompoundName): Boolean { val containerName = value return when (val containerNameLength = containerName.length) { 0 -> true else -> { val memberName = member.value val memberNameLength = memberName.length memberNameLength > containerNameLength + 1 && memberName.startsWith(containerName) && memberName[containerNameLength] == SEPARATOR } } } companion object { /** The symbol that is used for separation of individual name segments in [AbiCompoundName]. */ const val SEPARATOR = '.' } } /** * Fully qualified name. * Examples: "/TopLevelClass", "/topLevelFun", "kotlin.collections/List", "kotlin.ranges/CharRange.Companion.EMPTY". */ @ExperimentalLibraryAbiReader data class AbiQualifiedName(val packageName: AbiCompoundName, val relativeName: AbiCompoundName) : Comparable<AbiQualifiedName> { init { require(relativeName.value.isNotEmpty()) { "Empty relative name" } } override fun compareTo(other: AbiQualifiedName): Int { val diff = packageName.compareTo(other.packageName) return if (diff != 0) diff else relativeName.compareTo(other.relativeName) } override fun toString() = "$packageName$SEPARATOR$relativeName" companion object { /** * The symbol that is used to separate the package name from the relative declaration name in * the single-string representation of [AbiQualifiedName]. */ const val SEPARATOR = '/' } } /** * The common interface for entities that can have annotations. */ @ExperimentalLibraryAbiReader interface AbiAnnotatedEntity { /** * Annotations are not a part of ABI. But sometimes it is useful to have the ability to check if some declaration * has a specific annotation. See [AbiReadingFilter.NonPublicMarkerAnnotations] as an example. */ fun hasAnnotation(annotationClassName: AbiQualifiedName): Boolean } /** * The common interface for all declarations. * * @property qualifiedName The declaration qualified name. * @property signatures The set of signatures of the declaration. */ @ExperimentalLibraryAbiReader sealed interface AbiDeclaration : AbiAnnotatedEntity { val qualifiedName: AbiQualifiedName val signatures: AbiSignatures } /** * A declaration that also has a modality. * * @property modality The modality of the declaration. */ @ExperimentalLibraryAbiReader sealed interface AbiDeclarationWithModality : AbiDeclaration { val modality: AbiModality } /** * All known types of modality. */ @ExperimentalLibraryAbiReader enum class AbiModality { FINAL, OPEN, ABSTRACT, SEALED } /** * The entity that can contain nested [AbiDeclaration]s. * * @property declarations Nested declarations. * Important: The order of declarations is preserved exactly as in serialized IR. */ @ExperimentalLibraryAbiReader interface AbiDeclarationContainer { val declarations: List<AbiDeclaration> } /** * The auxiliary container used just to keep together all top-level [AbiDeclaration]s in a KLIB. */ @ExperimentalLibraryAbiReader interface AbiTopLevelDeclarations : AbiDeclarationContainer /** * An [AbiDeclaration] that represents a Kotlin class. * * @property kind Class kind. * @property isInner Whether the class is an inner class. * @property isValue Whether the class is a value-class. * @property isFunction Whether the interface represented by this [AbiClass] is a fun-interface. * @property superTypes The set of non-trivial supertypes (i.e. excluding [kotlin.Any]). * Important: The order of supertypes is preserved exactly as in serialized IR. */ @ExperimentalLibraryAbiReader interface AbiClass : AbiDeclarationWithModality, AbiDeclarationContainer, AbiTypeParametersContainer { val kind: AbiClassKind val isInner: Boolean val isValue: Boolean val isFunction: Boolean val superTypes: List<AbiType> } /** * All known Kotlin class kinds. */ @ExperimentalLibraryAbiReader enum class AbiClassKind { CLASS, INTERFACE, OBJECT, ENUM_CLASS, ANNOTATION_CLASS } /** An [AbiDeclaration] that represents a particular enum entry. */ @ExperimentalLibraryAbiReader interface AbiEnumEntry : AbiDeclaration /** * An [AbiDeclaration] that represents a function or a class constructor. * * @property isConstructor Whether this is a class constructor. * @property isInline Whether this is an `inline` function. * @property isSuspend Whether this is a `suspend` function. * @property hasExtensionReceiverParameter If this function has an extension receiver parameter. * @property contextReceiverParametersCount The number of context receiver parameters. * @property valueParameters The function value parameters. * Important: All value parameters of the function are stored in the single place, in the [valueParameters] list in * a well-defined order. First, unless [hasExtensionReceiverParameter] is false, goes the extension receiver parameter. * It is followed by [contextReceiverParametersCount] context receiver parameters. The remainder are the regular * value parameters of the function. * @property returnType The function's return type. Always `null` for constructors. */ @ExperimentalLibraryAbiReader interface AbiFunction : AbiDeclarationWithModality, AbiTypeParametersContainer { val isConstructor: Boolean val isInline: Boolean val isSuspend: Boolean val hasExtensionReceiverParameter: Boolean val contextReceiverParametersCount: Int val valueParameters: List<AbiValueParameter> val returnType: AbiType? } /** * An individual value parameter of a function. * * @property type The type of the value parameter. * @property isVararg Whether the value parameter is a var-arg parameter. * @property hasDefaultArg Whether the value parameter has a default value. * @property isNoinline If the parameter is marked with `noinline` keyword. * @property isCrossinline If the parameter is marked with `crossinline` keyword. */ @ExperimentalLibraryAbiReader interface AbiValueParameter { val type: AbiType val isVararg: Boolean val hasDefaultArg: Boolean val isNoinline: Boolean val isCrossinline: Boolean } /** * An [AbiDeclaration] that represents a property. * * @property kind The property kind. * @property getter The getter accessor, if any. * @property setter The setter accessor, if any. * @property backingField The backing field, if any. */ @ExperimentalLibraryAbiReader interface AbiProperty : AbiDeclarationWithModality { val kind: AbiPropertyKind val getter: AbiFunction? val setter: AbiFunction? val backingField: AbiField? } /** * An entity that represents a field. * * Since fields are not a part of ABI, [AbiField] is not inherited from [AbiDeclaration]. And consequently don't have * such attributes as [AbiDeclaration.qualifiedName] or [AbiDeclaration.signatures]. */ @ExperimentalLibraryAbiReader interface AbiField : AbiAnnotatedEntity /** All known kinds of properties. */ @ExperimentalLibraryAbiReader enum class AbiPropertyKind { VAL, CONST_VAL, VAR } /** * A declaration that also may have type parameters. * * @property typeParameters The declaration's type parameters. * Important: The order of [typeParameters] is preserved exactly as in serialized IR. */ @ExperimentalLibraryAbiReader sealed interface AbiTypeParametersContainer : AbiDeclaration { val typeParameters: List<AbiTypeParameter> } /** * An individual type parameter. * * @property tag A unique string identifying the type parameter withing the containing declaration's scope. Can be used * to distinguish this type parameter from other type parameters. Important: Please note that the [tag] property is * automatically generated by the ABI reader. The [tag] is not read from KLIB, and therefore it has no connection * with the type parameter's name. * @property variance The type parameter variance. * @property isReified Whether the type parameter is a reified parameter. * @property upperBounds The set of non-trivial upper bounds (i.e. excluding nullable [kotlin.Any]). * Important: The order of upper bounds is preserved exactly as in serialized IR. */ @ExperimentalLibraryAbiReader interface AbiTypeParameter { val tag: String val variance: AbiVariance val isReified: Boolean val upperBounds: List<AbiType> } /** Represents a Kotlin type. Can be either of: [Dynamic], [Error], [Simple]. */ @ExperimentalLibraryAbiReader sealed interface AbiType { /** The Kotlin/JavaScript `dynamic` type. */ interface Dynamic : AbiType /** * The error type. Normally, this type should not occur in a KLIB, because by its own nature this type implies that * there was an error during compilation such that the compiler failed to fully resolve the type leading to compilation halted * even before anything has been written to the KLIB. */ interface Error : AbiType /** * A regular type. * * @property classifierReference A reference pointing to the concrete classified used in the type. * @property arguments Type arguments. * @property nullability The nullability flag of the type. */ interface Simple : AbiType { val classifierReference: AbiClassifierReference val arguments: List<AbiTypeArgument> val nullability: AbiTypeNullability } } /** * An individual argument of a type. */ @ExperimentalLibraryAbiReader sealed interface AbiTypeArgument { /** A `<*>` (start projection) type argument. */ interface StarProjection : AbiTypeArgument /** * A regular type argument. * * @property type The type argument's type. * @property variance The type arguemnt's variance. */ interface TypeProjection : AbiTypeArgument { val type: AbiType val variance: AbiVariance } } /** * A reference to a concrete classifier. Used in [AbiType.Simple]. */ @ExperimentalLibraryAbiReader sealed interface AbiClassifierReference { /** * A reference that points to the concrete class. */ interface ClassReference : AbiClassifierReference { val className: AbiQualifiedName } /** * A reference that points to a type parameter (the matching is done by [tag]). */ interface TypeParameterReference : AbiClassifierReference { val tag: String } } /** * All known types of type nullability. */ @ExperimentalLibraryAbiReader enum class AbiTypeNullability { MARKED_NULLABLE, NOT_SPECIFIED, DEFINITELY_NOT_NULL } /** * All known sorts of type argument's variance, */ @ExperimentalLibraryAbiReader enum class AbiVariance { INVARIANT, IN, OUT }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
16,466
kotlin
Apache License 2.0
library-base/src/main/java/com/pp/library_base/adapter/DefaultBindingPagingDataAdapter.kt
PPQingZhao
548,315,946
false
null
package com.pp.library_base.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.DiffUtil class DefaultBindingPagingDataAdapter<VB : ViewDataBinding, VM : Any, T : Any>( private val getItemViewType: (position: Int) -> Int = { 0 }, private val onCreateViewModel: (binding: VB, item: T?, cacheItemViewModel: VM?) -> VM?, private val onCreateBinding: (parent: ViewGroup, viewType: Int, inflater: LayoutInflater) -> VB, diffCallback: DiffUtil.ItemCallback<T>, ) : BindingPagingDataAdapter<VB, VM, T>(diffCallback) { override fun getItemViewType(position: Int): Int { return getItemViewType.invoke(position) } override fun createViewModel(binding: VB, item: T?, cacheItemViewModel: VM?): VM? { return onCreateViewModel.invoke(binding, item, cacheItemViewModel) } override fun onCreateBinding(parent: ViewGroup, viewType: Int): VB { return onCreateBinding.invoke(parent, viewType, LayoutInflater.from(parent.context)) } }
0
null
0
5
904d9a980811d502f88479cb450c3a6e8d027f09
1,086
Eyepetizer
Apache License 2.0
BaseExtend/src/main/java/com/chen/baseextend/util/TimeTransUtil.kt
chen397254698
268,411,455
false
null
package com.chen.baseextend.util /** * Created by chen on 2019/9/24 **/ object TimeTransUtil { fun timeToTip(minute: Int? = 0): Pair<String, String> { return when (minute) { 30 -> Pair("30","分钟") 60 -> Pair("1","小时") 120 -> Pair("2","小时") 180 -> Pair("3","小时") 240 -> Pair("4","小时") 300 -> Pair("5","小时") 360 -> Pair("6","小时") 720 -> Pair("12","小时") 1440 -> Pair("1","天") 2880 -> Pair("2","天") 4320 -> Pair("3","天") 5760 -> Pair("4","天") 7200 -> Pair("5","天") 8640 -> Pair("6","天") 10080 -> Pair("7","天") else -> Pair("0","分钟") } } fun tipToTime(tip: String): Int { return when (tip) { "30分钟" -> 30 "1小时" -> 60 "2小时" -> 120 "3小时" -> 180 "4小时" -> 240 "5小时" -> 300 "6小时" -> 360 "12小时" -> 720 "1天" -> 1440 "2天" -> 2880 "3天" -> 4320 "4天" -> 5760 "5天" -> 7200 "6天" -> 8640 "7天" -> 10080 else -> 0 } } }
1
Kotlin
14
47
85ffc5e307c6171767e14bbfaf992b8d62ec1cc6
1,235
EasyAndroid
Apache License 2.0
src/main/kotlin/rui/leetcode/kt/q/Q1356.kt
ruislan
307,862,179
false
{"Kotlin": 78523}
package rui.leetcode.kt.q import org.junit.Assert.assertTrue import org.junit.Test class Q1356 { fun sortByBits(arr: IntArray): IntArray { // 方法1 // 因为数字大小范围在 0 <= arr[i] <= 10^4 // 创建数组长度10001,统计数字的频率 // 然后按从小数字到大数字的顺序统计二进制1的个数 // 最后将32位的数组中的数字取出来进行返回 // Passed 300ms 38.3mb // val freqs = IntArray(10001) // arr.forEach { freqs[it] += 1 } // val bits = Array<MutableList<Int>>(32) { mutableListOf() } // freqs.forEachIndexed { num, freq -> // var n = num // var countOneBits = 0 // while (n > 0) { // countOneBits += n and 1 // n = n shr 1 // } // (0 until freq).forEach { _ -> // bits[countOneBits].add(num) // } // } // return bits.toList().flatten().toIntArray() // 方法2 // 其实数字少的情况下排序更快,直接统计二进制,然后排序就行了 // Passed 260ms 38.3mb return arr.sortedWith(Comparator { a, b -> val o1 = Integer.bitCount(a) val o2 = Integer.bitCount(b) if (o1 == o2) a.compareTo(b) else o1.compareTo(o2) }).toIntArray() } @Test fun test() { assertTrue(sortByBits(intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8)).contentEquals(intArrayOf(0, 1, 2, 4, 8, 3, 5, 6, 7))) assertTrue(sortByBits(intArrayOf(1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1)).contentEquals(intArrayOf(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024))) assertTrue(sortByBits(intArrayOf(10000, 10000)).contentEquals(intArrayOf(10000, 10000))) assertTrue(sortByBits(intArrayOf(2, 3, 5, 7, 11, 13, 17, 19)).contentEquals(intArrayOf(2, 3, 5, 17, 7, 11, 13, 19))) assertTrue(sortByBits(intArrayOf(10, 100, 1000, 10000)).contentEquals(intArrayOf(10, 100, 10000, 1000))) assertTrue(sortByBits(intArrayOf(1111, 7644, 1107, 6978, 8742, 1, 7403, 7694, 9193, 4401, 377, 8641, 5311, 624, 3554, 6631)).contentEquals(intArrayOf(1, 624, 1107, 4401, 8641, 8742, 377, 1111, 6978, 3554, 7694, 9193, 5311, 6631, 7403, 7644))) } }
0
Kotlin
0
1
55baacd5c536864bbc82536bb60ff892cd127aa8
2,092
leetcode-kotlin
MIT License
client/src/commonTest/kotlin/SearchTest.kt
DRSchlaubi
732,514,157
false
{"Kotlin": 15627}
import org.junit.jupiter.api.Test import kotlin.test.assertEquals class SearchTest { @Test fun `search for isrc`() = withClient { val result = search("gbdhc2227201") assertEquals(1, result.size) val track= result.first() assertEquals("AhTypsCd3dM", track.videoId) assertEquals("We Got the Moves", track.title) } }
0
Kotlin
0
0
fbb35276ab0b614d1955641aba7035f63101e026
368
lyrics.kt
MIT License
app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/storiesinstagram/scenes/InstagramStoryScene3Activity.kt
rodrigomartind
265,013,640
false
null
package com.rodrigodominguez.mixanimationsmotionlayout.storiesinstagram.scenes import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.rodrigodominguez.mixanimationsmotionlayout.R class InstagramStoryScene3Activity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_instagram_story_scene3) } }
1
Kotlin
63
610
17e3d8ad36a3b9806c828bd03cc71eb37af789dc
441
MixAnimationsMotionLayout
Apache License 2.0
app/src/main/java/com/domatix/yevbes/nucleus/sga/view/adapter/ProductDataViewHolder.kt
sm2x
234,568,179
true
{"Kotlin": 782306}
package com.domatix.yevbes.nucleus.sga.view.adapter import android.support.v7.widget.RecyclerView import com.domatix.yevbes.nucleus.databinding.ProductProductRowBinding class ProductDataViewHolder(val binding: ProductProductRowBinding) : RecyclerView.ViewHolder(binding.root)
0
null
0
0
237e9496b5fb608f543e98111269da9b91a06ed3
282
nucleus
MIT License
compiler/testData/codegen/box/properties/lateinit/privateSetterFromLambda.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND_FIR: JVM_IR class My { lateinit var x: String private set fun init(arg: String, f: (String) -> String) { x = f(arg) } } fun box(): String { val my = My() my.init("O") { it + "K" } return my.x }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
242
kotlin
Apache License 2.0
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/config/dump.kt
kotest
47,071,082
false
null
package io.kotest.engine.config import io.kotest.core.config.Configuration import io.kotest.engine.tags.runtimeTags import io.kotest.mpp.bestName fun Configuration.createConfigSummary(): String { val sb = StringBuilder() sb.buildOutput("Parallelization factor", parallelism.toString()) sb.buildOutput("Concurrent specs", concurrentSpecs.toString()) sb.buildOutput("Global concurrent tests", concurrentTests.toString()) sb.buildOutput("Dispatcher affinity", dispatcherAffinity.toString()) sb.buildOutput("Coroutine debug probe", coroutineDebugProbes.toString()) sb.buildOutput("Spec execution order", specExecutionOrder.name) sb.buildOutput("Default test execution order", testCaseOrder.name) sb.buildOutput("Default test timeout", timeout.toString() + "ms") sb.buildOutput("Default test invocation timeout", invocationTimeout.toString() + "ms") if (projectTimeout != null) sb.buildOutput("Overall project timeout", projectTimeout.toString() + "ms") sb.buildOutput("Default isolation mode", isolationMode.name) sb.buildOutput("Global soft assertions", globalAssertSoftly.toString()) sb.buildOutput("Write spec failure file", writeSpecFailureFile.toString()) if (writeSpecFailureFile) { sb.buildOutput("Spec failure file path", specFailureFilePath.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }) } sb.buildOutput("Fail on ignored tests", failOnIgnoredTests.toString()) sb.buildOutput("Fail on empty test suite", failOnEmptyTestSuite.toString()) sb.buildOutput("Duplicate test name mode", duplicateTestNameMode.name) if (includeTestScopeAffixes != null) sb.buildOutput("Include test scope affixes", includeTestScopeAffixes.toString()) sb.buildOutput("Remove test name whitespace", removeTestNameWhitespace.toString()) sb.buildOutput("Append tags to test names", testNameAppendTags.toString()) if (registry().isNotEmpty()) { sb.buildOutput("Extensions") registry().all().map(::mapClassName).forEach { sb.buildOutput(it, indentation = 1) } } runtimeTags().expression?.let { sb.buildOutput("Tags", it) } return sb.toString() } fun Configuration.dumpProjectConfig() { println("~~~ Kotest Configuration ~~~") println(createConfigSummary()) } private fun StringBuilder.buildOutput(key: String, value: String? = null, indentation: Int = 0) { if (indentation == 0) { append("-> ") } else { for (i in 0 until indentation) { append(" ") } append("- ") } append(key) value?.let { append(": $it") } append("\n") } private fun mapClassName(any: Any) = any::class.bestName()
98
null
623
4,318
e7f7e52a732010fae899d1fcc4d074c055463e0b
2,694
kotest
Apache License 2.0
src/test/kotlin/org/rust/lang/core/completion/RustCompletionTestBase.kt
ujpv
68,909,564
true
{"Kotlin": 1020989, "Rust": 91489, "Java": 69391, "Lex": 19613, "HTML": 8841, "Shell": 377, "RenderScript": 229}
package org.rust.lang.core.completion import com.intellij.psi.PsiElement import org.intellij.lang.annotations.Language import org.rust.lang.RustTestCaseBase abstract class RustCompletionTestBase : RustTestCaseBase() { protected fun checkSingleCompletionByFile() = checkByFile { executeSoloCompletion() } protected fun checkSingleCompletion(target: String, @Language("Rust") code: String) { InlineFile(code).withCaret() val variants = myFixture.completeBasic() check(variants == null) { "Expected a single completion, but got ${variants.size}\n" + "${variants.toList()}" } val fnName = target.substringBeforeLast("()").substringAfterLast("::").substringAfterLast(".") val shift = if (target.endsWith("()")) 3 else 1 val element = myFixture.file.findElementAt(myFixture.caretOffset - shift)!! check(element.text == fnName && element.correspondsToText(target)) { "Wrong completion, expected `$target`, but got `${element.text}`" } } protected fun checkNoCompletion(@Language("Rust") code: String) { InlineFile(code).withCaret() val variants = myFixture.completeBasic() checkNotNull(variants) { val element = myFixture.file.findElementAt(myFixture.caretOffset - 1) "Expected zero completions, but one completion was auto inserted: `${element?.text}`." } check(variants.isEmpty()) { "Expected zero completions, got ${variants.size}." } } protected fun executeSoloCompletion() { val variants = myFixture.completeBasic() if (variants != null) { error("Expected a single completion, but got ${variants.size}\n" + "${variants.toList()}") } } private fun PsiElement.correspondsToText(target: String): Boolean = when { text == target -> true text.length > target.length -> false parent != null -> parent.correspondsToText(target) else -> false } }
0
Kotlin
0
0
2581d2b9e1b08ab0fa83b7e8b2e41186ccca721c
2,076
intellij-rust
MIT License
grammar/testData/grammar/annotations/nameAsUseSiteTargetPrefix/paramInBackticks.kt
Kotlin
39,459,058
false
null
class Foo(@`param` private val field: Int) {} class Foo { @ann @`param` var field: Int = 10 } class Foo(@`param` @ann protected val field: Int) {} class Foo { @ann @`param` var field: Int = 10 } class Foo(@ann @`param` val field: Int) {} class Foo(@`param` @ann val field: Int) {}
15
Kotlin
71
312
4411e49bb2b03f7d0d01d1c967723b901edd2105
294
kotlin-spec
Apache License 2.0
src/main/kotlin/dev/struggzard/samples/coroutines/HelloFlowSingle.kt
struggzard
349,768,186
false
null
package dev.struggzard.samples.coroutines import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.single import kotlinx.coroutines.launch fun main() { GlobalScope.launch { getNumbers().single().forEach { number -> println(number) } } Thread.sleep(1000) } fun getNumbers(): Flow<List<Int>> { return flowOf(listOf(1, 2, 3, 4, 5)) }
0
Kotlin
0
0
e048a34c71af18807f52719be4c50d7769326200
466
coroutines-playground
The Unlicense
app/src/main/java/com/android/musicplayer/presentation/playlist/PlaylistAdapter.kt
ZahraHeydari
224,468,018
false
null
package com.android.musicplayer.presentation.playlist import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import coil.api.load import coil.transform.CircleCropTransformation import com.android.musicplayer.R import com.android.musicplayer.data.model.Song import com.android.musicplayer.presentation.playlist.PlaylistAdapter.SongViewHolder import kotlinx.android.synthetic.main.holder_song.view.* import java.io.File import kotlin.properties.Delegates /** * This class is responsible for converting each data entry [Song] * into [SongViewHolder] that can then be added to the AdapterView. * * Created by ZARA. */ internal class PlaylistAdapter(val mListener: OnPlaylistAdapterListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val TAG = PlaylistAdapter::class.java.name var songs: List<Song> by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } /** * This method is called right when adapter is created & * is used to initialize ViewHolders * */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val viewSongItemHolder = LayoutInflater.from(parent.context).inflate(R.layout.holder_song, parent, false) return SongViewHolder(viewSongItemHolder) } /** It is called for each ViewHolder to bind it to the adapter & * This is where we pass data to ViewHolder * */ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as SongViewHolder).onBind(getItem(position)) } private fun getItem(position: Int): Song { return songs[position] } /** * This method returns the size of collection that contains the items we want to display * */ override fun getItemCount(): Int { return songs.size } inner class SongViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun onBind(song: Song) { Log.i(TAG, "SongViewHolder onBind: $song") itemView.music_item_name_text_view.text = song.title ?: "" song.clipArt?.let { nonNullImage -> itemView.music_item__avatar_image_view.load(File(nonNullImage)) { crossfade(true) placeholder( ContextCompat.getDrawable( itemView.context, R.drawable.placeholder ) ) error( ContextCompat.getDrawable( itemView.context, R.drawable.placeholder ) ) } } itemView.setOnLongClickListener { mListener.removeSongItem(song) true } itemView.setOnClickListener { mListener.playSong(song, songs as ArrayList<Song>) } } } }
2
null
85
549
a2c90b33df8b98aed4a1bd742d97a3364f77e822
3,181
MusicPlayer
Apache License 2.0
recycli/src/main/java/com/detmir/recycli/adapters/InfinityState.kt
detmir
358,579,304
false
null
package com.detmir.recycli.adapters import androidx.annotation.Keep @Keep data class InfinityState ( val items: List<RecyclerItem> = listOf(), val page: Int = 0, val endReached: Boolean = false, val requestState: Request = Request.IDLE ) { enum class Request { IDLE, LOADING, ERROR } @Suppress("unused") fun toPageLoading(page: Int? = null): InfinityState = this.copy( page = page ?: this.page, requestState = Request.LOADING ) @Suppress("unused") fun toPageError( page: Int? = null, items: List<RecyclerItem>? = null ): InfinityState = this.copy( page = page ?: this.page, items = items ?: this.items, requestState = Request.ERROR ) @Suppress("unused") fun toIdle( items: List<RecyclerItem>? = null, endReached: Boolean? = null, page: Int? = null ): InfinityState = this.copy( items = items ?: this.items, endReached = endReached ?: this.endReached, requestState = Request.IDLE, page = page ?: this.page ) }
3
null
3
32
5e12ba06400f02f93441af9ed6a5b17c436cd67d
1,102
recycli
Apache License 2.0
appupdatewrapper/src/main/java/com/motorro/appupdatewrapper/ImmediateUpdateState.kt
motorro
198,185,007
false
{"Kotlin": 126024}
/* * Copyright 2019 <NAME> (motorro). * 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.motorro.appupdatewrapper import android.app.Activity import com.google.android.play.core.appupdate.AppUpdateInfo import com.google.android.play.core.appupdate.AppUpdateOptions import com.google.android.play.core.install.model.AppUpdateType.IMMEDIATE import com.google.android.play.core.install.model.UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS import com.google.android.play.core.install.model.UpdateAvailability.UPDATE_AVAILABLE import com.motorro.appupdatewrapper.AppUpdateException.Companion.ERROR_NO_IMMEDIATE_UPDATE import com.motorro.appupdatewrapper.AppUpdateException.Companion.ERROR_UPDATE_FAILED import com.motorro.appupdatewrapper.AppUpdateException.Companion.ERROR_UPDATE_TYPE_NOT_ALLOWED /** * Immediate update flow */ internal sealed class ImmediateUpdateState: AppUpdateState(), Tagged { companion object { /** * Starts immediate update flow * @param stateMachine Application update stateMachine state-machine */ fun start(stateMachine: AppUpdateStateMachine) { stateMachine.setUpdateState(Initial()) } } /** * Transfers to checking state */ protected fun checking() { setUpdateState(Checking()) } /** * Transfers to update state */ protected fun update(appUpdateInfo: AppUpdateInfo) { setUpdateState(Update(appUpdateInfo)) } /** * Transfers to update ui check */ protected fun updateUiCheck() { setUpdateState(UpdateUiCheck()) } /** * Initial state */ internal class Initial : ImmediateUpdateState() { /** * Handles lifecycle `onStart` */ override fun onStart() { super.onStart() timber.d("onStart") checking() } } /** * Checks for update */ internal class Checking: ImmediateUpdateState() { /* * Set to true on [onStop] to prevent view interaction * as there is no way to abort task */ private var stopped: Boolean = false /** * Handles lifecycle `onStart` */ override fun onStart() { super.onStart() timber.d("onStart") timber.i("Getting application update info for IMMEDIATE update...") withUpdateView { updateChecking() } updateManager .appUpdateInfo .addOnSuccessListener { timber.i("Application update info: %s", it.format()) if (!stopped) { processUpdateInfo(it) } } .addOnFailureListener { timber.w(it, "Error getting application update info: ") if (!stopped) { reportUpdateCheckFailure(it) } } } /** * Called by state-machine when state is being replaced */ override fun cleanup() { super.cleanup() timber.d("cleanup") stopped = true } /** * Handles lifecycle `onStop` */ override fun onStop() { super.onStop() timber.d("onStop") complete() } /** * Transfers to failed state */ private fun reportUpdateCheckFailure(appUpdateException: Throwable) { timber.d("Failing update due to update check...") fail(AppUpdateException(ERROR_UPDATE_FAILED, appUpdateException)) } /** * Starts update on success or transfers to failed state */ private fun processUpdateInfo(appUpdateInfo: AppUpdateInfo) { timber.d("Evaluating update info...") when (appUpdateInfo.updateAvailability()) { UPDATE_AVAILABLE, DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> update(appUpdateInfo) else -> fail(AppUpdateException(ERROR_NO_IMMEDIATE_UPDATE)) } } } /** * Updates application * @param updateInfo Update info to start immediate update */ internal class Update(private val updateInfo: AppUpdateInfo): ImmediateUpdateState() { /** * Handles lifecycle `onResume` */ override fun onResume() { super.onResume() timber.d("onResume") if (false == updateInfo.isUpdateTypeAllowed(IMMEDIATE)) { timber.d("Update type IMMEDIATE is not allowed!") fail(AppUpdateException(ERROR_UPDATE_TYPE_NOT_ALLOWED)) } else withUpdateView { timber.d("Starting play-core update installer for IMMEDIATE state...") // As consent activity starts current activity looses focus. // So we need to transfer to the next state to break popup cycle. updateUiCheck() updateManager.startUpdateFlowForResult( updateInfo, stateMachine.launcher, AppUpdateOptions.newBuilder(IMMEDIATE).build() ) updateInstallUiVisible() } } } /** * Checks for update ui errors */ internal class UpdateUiCheck: ImmediateUpdateState() { /** * Checks activity result and returns `true` if result is an update result and was handled * Use to check update activity result in [android.app.Activity.onActivityResult] */ override fun checkActivityResult(resultCode: Int): Boolean { timber.d("checkActivityResult: resultCode(%d)", resultCode) if (Activity.RESULT_OK == resultCode) { timber.d("Update installation complete") complete() } else { timber.d("Failing update due to installation failure...") fail(AppUpdateException(ERROR_UPDATE_FAILED)) } return true } } }
1
Kotlin
2
35
53f96f89b0dace51c46f34b9912007dd261d7596
6,702
AppUpdateWrapper
Apache License 2.0
src/section6/section6.5/app/src/main/java/com/nigelhenshaw/ktxwork/ColorWorkers.kt
PacktPublishing
139,799,019
false
{"Kotlin": 43640}
package com.nigelhenshaw.ktxwork import com.nigelhenshaw.ktxwork.MainActivity.Companion.KEY_GET_COLOR import com.nigelhenshaw.ktxwork.MainActivity.Companion.KEY_SET_COLOR /** * This collection will be used by both workers * which will either set the data or get the data */ private val colors by lazy { arrayOfNulls<String>(4) } /** * Create a worker to populate colors */ /** * Create a worker to set colors to the * output data */
1
Kotlin
4
4
83b8bbf71cc67c156798c964c5b6134b10d267da
451
Kotlin-Tips-Tricks-and-Techniques
MIT License
cesium-kotlin/src/jsMain/kotlin/cesium/engine/CreditDisplay.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! @file:JsModule("@cesium/engine") @file:Suppress( "EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER", ) package cesium.engine import web.html.HTMLElement /** * The credit display is responsible for displaying credits on screen. * ``` * // Add a credit with a tooltip, image and link to display onscreen * const credit = new Credit(`<a href="https://cesium.com/" target="_blank"><img src="/images/cesium_logo.png" title="Cesium"/></a>`, true); * viewer.creditDisplay.addStaticCredit(credit); * ``` * ``` * // Add a credit with a plaintext link to display in the lightbox * const credit = new Credit('<a href="https://cesium.com/" target="_blank">Cesium</a>'); * viewer.creditDisplay.addStaticCredit(credit); * ``` * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html">Online Documentation</a> * * @constructor * @property [container] The HTML element where credits will be displayed * @param [delimiter] The string to separate text credits * Default value - `'•'` * @param [viewport] The HTML element that will contain the credits popup * Default value - `document.body` * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html">Online Documentation</a> */ external class CreditDisplay( var container: HTMLElement, delimiter: String? = definedExternally, viewport: HTMLElement? = definedExternally, ) { /** * Adds a [Credit] that will show on screen or in the lightbox until * the next frame. This is mostly for internal use. Use [CreditDisplay.addStaticCredit] to add a persistent credit to the screen. * @param [credit] The credit to display in the next frame. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#addCreditToNextFrame">Online Documentation</a> */ fun addCreditToNextFrame(credit: Credit) /** * Adds a [Credit] that will show on screen or in the lightbox until removed with [CreditDisplay.removeStaticCredit]. * ``` * // Add a credit with a tooltip, image and link to display onscreen * const credit = new Credit(`<a href="https://cesium.com/" target="_blank"><img src="/images/cesium_logo.png" title="Cesium"/></a>`, true); * viewer.creditDisplay.addStaticCredit(credit); * ``` * ``` * // Add a credit with a plaintext link to display in the lightbox * const credit = new Credit('<a href="https://cesium.com/" target="_blank">Cesium</a>'); * viewer.creditDisplay.addStaticCredit(credit); * ``` * @param [credit] The credit to added * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#addStaticCredit">Online Documentation</a> */ fun addStaticCredit(credit: Credit) /** * Removes a static credit shown on screen or in the lightbox. * @param [credit] The credit to be removed. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#removeStaticCredit">Online Documentation</a> */ fun removeStaticCredit(credit: Credit) /** * Updates the credit display before a new frame is rendered. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#update">Online Documentation</a> */ fun update() /** * Resets the credit display to a beginning of frame state, clearing out current credits. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#beginFrame">Online Documentation</a> */ fun beginFrame() /** * Sets the credit display to the end of frame state, displaying credits from the last frame in the credit container. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#endFrame">Online Documentation</a> */ fun endFrame() /** * Destroys the resources held by this object. Destroying an object allows for deterministic * release of resources, instead of relying on the garbage collector to destroy this object. * * Once an object is destroyed, it should not be used; calling any function other than * `isDestroyed` will result in a [DeveloperError] exception. Therefore, * assign the return value (`undefined`) to the object as done in the example. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#destroy">Online Documentation</a> */ fun destroy() /** * Returns true if this object was destroyed; otherwise, false. * @return `true` if this object was destroyed; otherwise, `false`. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#isDestroyed">Online Documentation</a> */ fun isDestroyed(): Boolean companion object { /** * Gets or sets the Cesium logo credit. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/CreditDisplay.html#.cesiumCredit">Online Documentation</a> */ var cesiumCredit: Credit } }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
4,983
types-kotlin
Apache License 2.0
feature/note/src/main/java/com/teamwiney/notecollection/components/NoteSortBottomSheet.kt
AdultOfNineteen
639,481,288
false
null
package com.teamwiney.notecollection.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.teamwiney.ui.components.HeightSpacer import com.teamwiney.ui.theme.WineyTheme @Composable fun NoteSortBottomSheet( modifier: Modifier = Modifier, sortItems: List<String>, selectedSort: String, onSelectSort: (String) -> Unit, applyFilter: () -> Unit ) { Column( modifier = modifier .fillMaxWidth() .background( color = WineyTheme.colors.gray_950, shape = RoundedCornerShape(topStart = 6.dp, topEnd = 6.dp) ) .padding( top = 10.dp, bottom = 20.dp ), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer( modifier = Modifier .width(66.dp) .height(5.dp) .background( color = WineyTheme.colors.gray_900, shape = RoundedCornerShape(6.dp) ) ) HeightSpacer(height = 20.dp) sortItems.forEachIndexed { index, sort -> Row( modifier = Modifier .fillMaxWidth() .clickable { onSelectSort(sort) applyFilter() }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding( start = 24.dp, top = 20.dp, bottom = 20.dp ), text = sort, style = WineyTheme.typography.bodyB1.copy( color = WineyTheme.colors.gray_50 ) ) if (selectedSort == sort) { Icon( modifier = Modifier.padding(end = 24.dp), painter = painterResource(id = com.teamwiney.core.design.R.drawable.ic_arrow_down), contentDescription = "IC_ARROW_DOWN", tint = WineyTheme.colors.gray_50 ) } } if (index != sortItems.size - 1) { Spacer( modifier = Modifier .fillMaxWidth() .padding(horizontal = 24.dp) .height(1.dp) .background( color = WineyTheme.colors.gray_900 ) ) } } } }
8
null
1
8
4bb17621738030f0234f1592036930cfb7172397
3,531
WINEY-Android
MIT License
src/commonTest/kotlin/responses/GetBookmarks.kt
MrNuggelz
866,645,099
false
{"Kotlin": 154248}
const val GetBookmarksResponse = """ { "subsonic-response": { "status": "ok", "version": "1.16.1", "type": "AwesomeServerName", "serverVersion": "0.1.3 (tag)", "openSubsonic": true, "bookmarks": { "bookmark": [ { "entry": { "id": "113bf5989ad15ce2cf1834ba9622983f", "parent": "b87a936c682c49d4494c7ccb08c22d23", "isDir": false, "title": "Stay Out Here", "album": "Shaking The Habitual", "artist": "The Knife", "track": 11, "year": 2013, "genre": "Electronic", "coverArt": "al-b87a936c682c49d4494c7ccb08c22d23_0", "size": 21096309, "contentType": "audio/mp4", "suffix": "m4a", "duration": 642, "bitRate": 257, "bitDepth": 16, "samplingRate": 44100, "channelCount": 2, "path": "The Knife/Shaking The Habitual/11 - Stay Out Here.m4a", "created": "2023-03-13T16:30:35Z", "albumId": "b87a936c682c49d4494c7ccb08c22d23", "artistId": "b29e9a9d780cb0e133f3add5662771b9", "type": "music", "isVideo": false, "bookmarkPosition": 129000 }, "position": 129000, "username": "demo", "comment": "", "created": "2023-03-13T16:30:35Z", "changed": "2023-03-13T16:30:35Z" }, { "entry": { "id": "2b42782333450d02b177823e729664af", "parent": "dc8d8889a6fe08d8da7698c7ee1de61c", "isDir": false, "title": "Ill with the Skills", "album": "First Words", "artist": "The Polish Ambassador", "track": 17, "year": 2014, "coverArt": "mf-2b42782333450d02b177823e729664af_641edeb3", "size": 6219581, "contentType": "audio/mpeg", "suffix": "mp3", "duration": 255, "bitRate": 194, "bitDepth": 16, "samplingRate": 44100, "channelCount": 2, "path": "The Polish Ambassador/First Words/17 - Ill with the Skills.mp3", "playCount": 1, "played": "2023-03-15T15:23:37Z", "created": "2023-03-25T11:44:51Z", "albumId": "dc8d8889a6fe08d8da7698c7ee1de61c", "artistId": "64e1f796b283545d329cdf6a31a31dbe", "type": "music", "isVideo": false, "bookmarkPosition": 7000 }, "position": 7000, "username": "demo", "comment": "playSub bookmark", "created": "2023-03-25T11:44:51Z", "changed": "2023-03-25T11:44:51Z" } ] } } } """
1
Kotlin
0
1
b822e7775c4f1271bc821db17e6b8ecc500d5346
2,800
OpenSubsonicClient
Apache License 2.0
plugins/kotlin/navigation/tests/test/org/jetbrains/kotlin/idea/k2/navigation/AbstractKotlinNavigationToLibrarySourceTest.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.navigation import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.common.runAll import org.jetbrains.kotlin.analysis.project.structure.KtLibrarySourceModule import org.jetbrains.kotlin.analysis.project.structure.ProjectStructureProvider import org.jetbrains.kotlin.idea.fir.invalidateCaches import org.jetbrains.kotlin.idea.resolve.AbstractReferenceResolveTest import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace abstract class AbstractKotlinNavigationToLibrarySourceTest : AbstractReferenceResolveTest() { override fun isFirPlugin(): Boolean = true override fun getProjectDescriptor(): KotlinLightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstanceFullJdk() override fun performAdditionalResolveChecks(results: List<PsiElement>) { for (result in results) { val navigationElement = result.navigationElement val ktModule = ProjectStructureProvider.getModule(project, navigationElement, null) UsefulTestCase.assertTrue( "reference should be resolved to the psi element from ${KtLibrarySourceModule::class} but was resolved to ${ktModule::class}", ktModule is KtLibrarySourceModule ) } } override fun render(element: PsiElement): String { return when (val navigationElement = element.navigationElement) { is KtNamedDeclaration -> "(" + (navigationElement.fqName?.asString() ?: "<local>") + ") " + navigationElement.signatureText() else -> super.render(element) } } private fun KtNamedDeclaration.signatureText(): String { val firstElement = children.first { it !is PsiComment && it !is PsiWhiteSpace } val endOffset = when (this) { is KtNamedFunction -> typeReference ?: valueParameterList?.rightParenthesis is KtProperty -> typeReference ?: equalsToken?.getPrevSiblingIgnoringWhitespace() is KtClassOrObject -> primaryConstructor?.valueParameterList?.rightParenthesis ?: getColon()?.getPrevSiblingIgnoringWhitespace() ?: body?.getPrevSiblingIgnoringWhitespace() else -> lastChild } return containingFile.text.subSequence(firstElement.startOffset, endOffset?.endOffset ?: lastChild!!.endOffset).toString() .replace("\n", " ") } override fun tearDown() { runAll( { project.invalidateCaches() }, { super.tearDown() } ) } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,260
intellij-community
Apache License 2.0
war/src/main/java/code/Controller.kt
benjefferies
103,452,581
false
null
package code import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody import java.sql.Connection @Controller class Controller @Autowired constructor(val connection: Connection) { @RequestMapping(path = arrayOf("ping"), method = arrayOf(RequestMethod.GET)) @ResponseBody fun ping() : String { connection.prepareStatement("update ping set counter = counter + 1;").executeUpdate() connection.commit() val results = connection.createStatement().executeQuery("select counter from ping;") results.next() val counter = results.getInt(1) return "pinged: " + counter } }
5
Kotlin
1
0
97069026b4be3b801012709f7aed1a9a8163b394
865
tomcat-war-jndi
MIT License