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
src/main/kotlin/ink/ptms/chemdah/module/command/CommandChemdahPlayerLevel.kt
TabooLib
338,114,548
false
null
package ink.ptms.chemdah.module.command import ink.ptms.chemdah.api.ChemdahAPI.chemdahProfile import ink.ptms.chemdah.module.level.LevelSystem import ink.ptms.chemdah.module.level.LevelSystem.getLevelOption import ink.ptms.chemdah.module.level.LevelSystem.giveExperience import ink.ptms.chemdah.module.level.LevelSystem.giveLevel import ink.ptms.chemdah.module.level.LevelSystem.setExperience import ink.ptms.chemdah.module.level.LevelSystem.setLevel import org.bukkit.command.CommandSender import org.bukkit.entity.Player import taboolib.common.platform.command.* import taboolib.common5.Coerce import taboolib.expansion.createHelper import taboolib.platform.util.sendLang /** * Chemdah * ink.ptms.chemdah.command.CommandChemdahPlayerLevel * * @author sky * @since 2021/2/11 7:19 下午 */ @Suppress("SpellCheckingInspection") @CommandHeader(name = "ChemdahPlayerLevel", aliases = ["chpl"], permission = "chemdah.command") object CommandChemdahPlayerLevel { @CommandBody val main = mainCommand { createHelper() } @CommandBody val addlevel = subCommand { dynamic(comment = "player") { suggestPlayers() // level dynamic(comment = "level") { suggestion<CommandSender> { _, _ -> LevelSystem.level.keys.toList() } // value dynamic(comment = "value") { execute<CommandSender> { sender, ctx, argument -> val option = getLevelOption(ctx.argument(-1))!! val profile = ctx.player(-2).cast<Player>().chemdahProfile profile.giveLevel(option, Coerce.toInteger(argument)).thenAccept { sender.sendLang("command-level-change", "§7${option.id} (LEVEL) §8+= §f${argument} §7(Lv.${it.level}, ${it.experience})") } } } } } } @CommandBody val setlevel = subCommand { dynamic(comment = "player") { suggestPlayers() // level dynamic(comment = "level") { suggestion<CommandSender> { _, _ -> LevelSystem.level.keys.toList() } // value dynamic(comment = "value") { execute<CommandSender> { sender, ctx, argument -> val option = getLevelOption(ctx.argument(-1))!! val profile = ctx.player(-2).cast<Player>().chemdahProfile profile.setLevel(option, Coerce.toInteger(argument)).thenAccept { sender.sendLang("command-level-change", "§7${option.id} (LEVEL) §8= §f${argument} §7(Lv.${it.level}, ${it.experience})") } } } } } } @CommandBody val addexp = subCommand { dynamic(comment = "player") { suggestPlayers() // level dynamic(comment = "level") { suggestion<CommandSender> { _, _ -> LevelSystem.level.keys.toList() } // value dynamic(comment = "value") { execute<CommandSender> { sender, ctx, argument -> val option = getLevelOption(ctx.argument(-1))!! val profile = ctx.player(-2).cast<Player>().chemdahProfile profile.giveExperience(option, Coerce.toInteger(argument)).thenAccept { sender.sendLang("command-level-change", "§7${option.id} (EXP) §8+= §f${argument} §7(Lv.${it.level}, ${it.experience})") } } } } } } @CommandBody val setexp = subCommand { dynamic(comment = "player") { suggestPlayers() // level dynamic(comment = "level") { suggestion<CommandSender> { _, _ -> LevelSystem.level.keys.toList() } // value dynamic(comment = "value") { execute<CommandSender> { sender, ctx, argument -> val option = getLevelOption(ctx.argument(-1))!! val profile = ctx.player(-2).cast<Player>().chemdahProfile profile.setExperience(option, Coerce.toInteger(argument)).thenAccept { sender.sendLang("command-level-change", "§7${option.id} (EXP) §8= §f${argument} §7(Lv.${it.level}, ${it.experience})") } } } } } } }
8
Kotlin
37
52
f2e2c0616e223d58491e38a6f9abd5fb7f52565f
4,626
chemdah
MIT License
wisefy/src/androidTest/java/com/isupatches/wisefy/GetCurrentNetworkInfoTest.kt
project-kotinos
277,452,347
false
{"Gradle": 16, "Markdown": 23, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 3, "INI": 3, "Proguard": 3, "Kotlin": 190, "XML": 37, "Java": 1, "CSS": 1, "HTML": 195, "CODEOWNERS": 1}
package com.isupatches.wisefy import android.net.NetworkInfo import com.isupatches.wisefy.callbacks.GetCurrentNetworkInfoCallbacks import com.isupatches.wisefy.constants.MISSING_PARAMETER import com.isupatches.wisefy.internal.base.BaseInstrumentationTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.fail import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.timeout import org.mockito.Mockito.verify /** * Tests the ability to retrieve a device's current network information. * * @author Patches * @since 3.0 */ internal class GetCurrentNetworkInfoTest : BaseInstrumentationTest() { @Test fun sync_failure_prechecks() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_failure() assertEquals(null, wisefy.getCurrentNetworkInfo()) verificationUtil.didNotTryToGetCurrentNetworkInfo() } @Test fun sync_failure_nullCurrentNetwork() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() assertEquals(null, wisefy.getCurrentNetworkInfo()) verificationUtil.triedToGetCurrentNetworkInfo() } @Test fun sync_success() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() val currentNetworkInfo = wisefy.getCurrentNetworkInfo() if (currentNetworkInfo != null) { assertNotNull(currentNetworkInfo) verificationUtil.triedToGetCurrentNetworkInfo() } else { fail() } } @Test fun async_failure_prechecks() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_failure() val mockCallbacks = mock(GetCurrentNetworkInfoCallbacks::class.java) wisefy.getCurrentNetworkInfo(mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER) verificationUtil.didNotTryToGetCurrentNetworkInfo() } @Test fun async_failure_prechecks_nullCallbacks() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_failure() nullCallbackUtil.callGetCurrentNetworkInfo() verificationUtil.didNotTryToGetCurrentNetworkInfo() } @Test fun async_failure_nullCurrentNetwork() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() val mockCallbacks = mock(GetCurrentNetworkInfoCallbacks::class.java) wisefy.getCurrentNetworkInfo(mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noCurrentNetworkInfo() verificationUtil.triedToGetCurrentNetworkInfo() } @Test fun async_failure_nullCurrentNetwork_nullCallbacks() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() nullCallbackUtil.callGetCurrentNetworkInfo() verificationUtil.triedToGetCurrentNetworkInfo() } @Test fun async_success() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() val mockCallbacks = mock(GetCurrentNetworkInfoCallbacks::class.java) wisefy.getCurrentNetworkInfo(mockCallbacks) verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedCurrentNetworkInfo(any(NetworkInfo::class.java)) verificationUtil.triedToGetCurrentNetworkInfo() } @Test fun async_success_nullCallback() { mockWiseFyPrechecksUtil.getCurrentNetworkInfo_success() mockNetworkUtil.activeNetwork() nullCallbackUtil.callGetCurrentNetworkInfo() verificationUtil.triedToGetCurrentNetworkInfo() } }
1
null
1
1
dc056a2a725072d1c58d1803b5b12edf796f93ad
3,552
WiseFy
Apache License 2.0
arouter-compiler/src/main/java/com/alibaba/android/arouter/compiler/utils/KspUtils.kt
CxrHowen
625,142,750
false
{"Java Properties": 2, "Markdown": 3, "Gradle": 12, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "INI": 5, "Java": 82, "Kotlin": 12, "XML": 25, "YAML": 1, "Groovy": 6, "Proguard": 1, "HTML": 1}
package com.alibaba.android.arouter.compiler.utils import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.getAnnotationsByType import com.google.devtools.ksp.isAnnotationPresent import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.Origin import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.ksp.toTypeName import com.squareup.kotlinpoet.ksp.toTypeParameterResolver import com.squareup.kotlinpoet.tags.TypeAliasTag @OptIn(KspExperimental::class) @Suppress("unused") internal fun KSClassDeclaration.isKotlinClass(): Boolean { return origin == Origin.KOTLIN || origin == Origin.KOTLIN_LIB || isAnnotationPresent(Metadata::class) } @OptIn(KspExperimental::class) internal inline fun <reified T : Annotation> KSAnnotated.findAnnotationWithType(): T? { return getAnnotationsByType(T::class).firstOrNull() } /** * Judge whether a class [KSClassDeclaration] is a subclass of another class [superClassName] * https://www.raywenderlich.com/33148161-write-a-symbol-processor-with-kotlin-symbol-processing * */ internal fun KSClassDeclaration.isSubclassOf(superClassName: String): Boolean { val superClasses = superTypes.toMutableList() while (superClasses.isNotEmpty()) { val current: KSTypeReference = superClasses.first() val declaration: KSDeclaration = current.resolve().declaration when { declaration is KSClassDeclaration && declaration.qualifiedName?.asString() == superClassName -> { return true } declaration is KSClassDeclaration -> { superClasses.removeAt(0) superClasses.addAll(0, declaration.superTypes.toList()) } else -> { superClasses.removeAt(0) } } } return false } /** * 判断当前类是否继承自给定的某个父类或者父接口 * @param superClassNames 给定的父类或父接口的全限定名列表 * @return 若继承自某个给定的父类或父接口,则返回其在superClassNames列表中的索引(从0开始);否则返回-1 */ internal fun KSClassDeclaration.isSubclassOf(superClassNames: List<String>): Int { val superClasses = superTypes.toMutableList()// 获取当前类的所有父类型,并将其转化为可变列表 while (superClasses.isNotEmpty()) { val current: KSTypeReference = superClasses.first()// 取出第一个父类型 val declaration: KSDeclaration = current.resolve().declaration// 解析该父类型,获取其对应的声明对象 when { // 如果该父类型对应的声明是一个类声明,并且其全限定名在superClassNames列表中,则说明当前类继承自该父类,直接返回其索引 declaration is KSClassDeclaration && (superClassNames.indexOf(declaration.qualifiedName?.asString())) != -1 -> { return superClassNames.indexOf(declaration.qualifiedName?.asString()) } // 如果该父类型对应的声明是一个类声明,但其全限定名不在superClassNames列表中,则将其父类型加入待检查列表中 declaration is KSClassDeclaration -> { superClasses.removeAt(0) superClasses.addAll(0, declaration.superTypes.toList()) } // 如果该父类型对应的声明既不是类声明,也不是接口声明,则直接将其移出待检查列表 else -> { superClasses.removeAt(0) } } } return -1 } internal fun KSPropertyDeclaration.isSubclassOf(superClassName: String): Boolean { val propertyType = type.resolve().declaration return if (propertyType is KSClassDeclaration) { propertyType.isSubclassOf(superClassName) } else { false } } internal fun KSPropertyDeclaration.isSubclassOf(superClassNames: List<String>): Int { val propertyType = type.resolve().declaration return if (propertyType is KSClassDeclaration) { propertyType.isSubclassOf(superClassNames) } else { -1 } } internal fun String.quantifyNameToClassName(): ClassName { val index = lastIndexOf(".") return ClassName(substring(0, index), substring(index + 1, length)) } /** * such: val map = Map<String, String> ==> Map<String, String> (used for kotlinpoet for %T) * 考虑类型别名 * */ internal fun KSPropertyDeclaration.getKotlinPoetTTypeGeneric(): TypeName { val classTypeParams = this.typeParameters.toTypeParameterResolver() val typeName = this.type.toTypeName(classTypeParams) // Fix: typealias-handling // https://square.github.io/kotlinpoet/interop-ksp/#typealias-handling // Alias class -> such as: var a = arrayList<String>() -> ArrayList<String> typeName.tags[TypeAliasTag::class]?.let { val typeAliasTag = (it as? TypeAliasTag)?.abbreviatedType if (typeAliasTag != null) { return typeAliasTag } } return typeName } /** * such: val map = Map<String, String> ==> Map (used for kotlinpoet for %T) * 不考虑类型别名 * */ @Suppress("unused") internal fun KSPropertyDeclaration.getKotlinPoetTType(): TypeName { return this.type.resolve().toTypeName() }
1
null
1
1
1b9adf4300ab8b6d701996c7977c330f55832de7
5,026
ARouter
Apache License 2.0
simulator/runtime/src/main/kotlin/net/corda/simulator/runtime/SimulatedNodeBase.kt
corda
346,070,752
false
{"Kotlin": 18686067, "Java": 321931, "Smarty": 79539, "Shell": 56594, "Groovy": 28415, "TypeScript": 5826, "PowerShell": 4985, "Solidity": 2024}
package net.corda.simulator.runtime import net.corda.simulator.SimulatedNode import net.corda.simulator.crypto.HsmCategory import net.corda.simulator.runtime.messaging.SimFiber import net.corda.v5.application.persistence.PersistenceService import org.slf4j.LoggerFactory import java.security.PublicKey abstract class SimulatedNodeBase : SimulatedNode { companion object { val log = LoggerFactory.getLogger(this::class.java.enclosingClass) } protected abstract val fiber: SimFiber override fun getPersistenceService(): PersistenceService = fiber.getOrCreatePersistenceService(member) override fun generateKey(alias: String, hsmCategory: HsmCategory, scheme: String) : PublicKey { log.info("Generating key with alias \"$alias\", hsm category \"$hsmCategory\", scheme \"$scheme\" " + "for member \"$member\"" ) return fiber.generateAndStoreKey(alias, hsmCategory, scheme, member) } }
130
Kotlin
15
42
6ef36ce2d679a07abf7a5d95a832e98bd4d4d763
967
corda-runtime-os
Apache License 2.0
app/src/main/java/com/hani/btapp/core/service/FirmwareUpdateUiState.kt
tomrodinger
534,168,828
false
{"Kotlin": 135017}
package com.hani.btapp.core.service /** * Created by hanif on 2022-08-20. */ data class FirmwareUpdateUiState( val isUpdating: Boolean = false, val updateSteps: List<FirmwareUpdateUiStep> = listOf(), val totalBytes: Int = 0, val sentBytes: Int = 0, ) { fun addStep(step: FirmwareUpdateUiStep): FirmwareUpdateUiState { val steps = ArrayList(updateSteps) steps.add(step) return this.copy(updateSteps = steps) } }
0
Kotlin
0
0
7bf08f9d0c2fc1d0eaee9e7bdb1071dcb7079e64
461
Android_app_for_line_following_robot
Apache License 2.0
remark-sdk/src/main/java/com/stelmashchuk/remark/feature/post/PostComment.kt
VovaStelmashchuk
350,405,976
false
null
package com.stelmashchuk.remark.feature.post import com.stelmashchuk.remark.api.comment.CommentRoot import com.stelmashchuk.remark.api.comment.EditCommentUseCase import com.stelmashchuk.remark.api.comment.PostCommentUseCase internal class PostComment( private val postCommentUseCase: PostCommentUseCase, private val postCommentStorage: PostCommentStorage, private val editCommentUseCase: EditCommentUseCase, private val editMode: EditMode, private val commentRoot: CommentRoot, ) { internal suspend fun postComment() { if (editMode.flowEditCommentId().value != null) { editComment() } else { postNewComment() } } private suspend fun postNewComment() { val text = postCommentStorage.flowText().value val result = postCommentUseCase.postComment(commentRoot, text) if (result.isSuccess) { postCommentStorage.clear() } } private suspend fun editComment() { val id = requireNotNull(editMode.flowEditCommentId().value) val text = postCommentStorage.flowText().value if (editCommentUseCase.editComment(id, text).isSuccess) { postCommentStorage.clear() editMode.closeEditMode() } } }
8
Kotlin
2
4
b18c9f3adb05f33d84bf60f3de7fbeb75edf195c
1,188
RadiotApp
MIT License
cadenas-core/src/commonTest/kotlin/com/galois/cadenas/crypto/RoundTrip.kt
GaloisInc
873,867,559
false
{"Kotlin": 297817}
package com.galois.cadenas.crypto import io.kotest.core.spec.style.StringSpec import io.kotest.property.Arb import io.kotest.property.arbitrary.byte import io.kotest.property.arbitrary.byteArray import io.kotest.property.arbitrary.constant import io.kotest.property.arbitrary.int import io.kotest.property.forAll private fun roundTripProperty( scs: SymmetricCryptoSystem, plaintext: ByteArray, ): Boolean { val res = scs.encrypt(plaintext) val finishDecrypt = scs.beginDecrypt(res.sliceArray(0 until scs.numBytesToCheck)) ?: return false val decrypted = finishDecrypt(res.sliceArray(scs.numBytesToCheck until res.size)) return plaintext.contentEquals(decrypted) } /** * Round-trip tests for [SymmetricCryptoSystem]s. * * For library maintainers: After implementing a new `SymmetricCryptoSystem`, * make sure to add a test for it here! */ class RoundTrip : StringSpec({ "SivChaChaWithSentinel" { val keyArb = Arb.byteArray(Arb.constant(32), Arb.byte()) val plaintextArb = Arb.byteArray(Arb.int(0, 32), Arb.byte()) forAll(keyArb, plaintextArb) { key, plaintext -> roundTripProperty(SivChaChaWithSentinel(key), plaintext) } } "SivAesWithSentinel" { val keyArb = Arb.byteArray(Arb.constant(32), Arb.byte()) val plaintextArb = Arb.byteArray(Arb.int(0, 32), Arb.byte()) forAll(keyArb, plaintextArb) { key, plaintext -> roundTripProperty(SivAesWithSentinel(key), plaintext) } } })
1
Kotlin
0
0
13bec2fb2959936fce8d3461518cc2b3e542540c
1,513
Cadenas
MIT License
baseRes/src/main/java/cn/mtjsoft/www/baseres/cache/SpUtlils.kt
mtjsoft
481,203,216
false
{"Kotlin": 35029, "Java": 12689}
package cn.mtjsoft.www.baseres.cache object SpUtlils : ISp { private val sp by lazy { MmkvManager.mmkv } override fun putString(key: String, value: String) { sp?.putString(key, value) } override fun getString(key: String, default: String): String { return sp?.getString(key, default) ?: default } override fun putBoolean(key: String, value: Boolean) { sp?.putBoolean(key, value) } override fun getBoolean(key: String, default: Boolean): Boolean { return sp?.getBoolean(key, default) ?: default } override fun putInt(key: String, value: Int) { sp?.putInt(key, value) } override fun getInt(key: String, default: Int): Int { return sp?.getInt(key, default) ?: default } override fun putLong(key: String, value: Long) { sp?.putLong(key, value) } override fun getLong(key: String, default: Long): Long { return sp?.getLong(key, default) ?: default } override fun putBytes(key: String, value: ByteArray) { sp?.putBytes(key, value) } override fun getBytes(key: String, default: ByteArray): ByteArray { return sp?.getBytes(key, default) ?: default } }
0
Kotlin
0
0
2c258fb55e1c1e4f8e292661de58096d022d2d91
1,233
AudioAndVideoProject
Apache License 2.0
app/src/main/java/com/example/toncontest/ui/theme/screens/main/settings/SettingsScreen.kt
L0mTiCk
625,185,980
false
null
package com.example.toncontest.ui.theme.screens.main.settings import android.content.Context import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.toncontest.data.main.MainStrings import com.example.toncontest.ui.theme.robotoFamily //navController: NavController @Composable fun SettingsScreen(navController: NavController, context: Context) { Scaffold( topBar = { Row( modifier = Modifier .height(56.dp) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { IconButton( onClick = { navController.popBackStack() }, modifier = Modifier.size(48.dp) ) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Back arrow", tint = Color.White) } Text( text = MainStrings.walletSettings, fontSize = 20.sp, fontFamily = robotoFamily, color = Color.White, modifier = Modifier .padding(horizontal = 20.dp, vertical = 12.dp) ) } }, content = { Column( modifier = Modifier .padding(it) .fillMaxSize() .background(color = Color.White, shape = RoundedCornerShape(12.dp)) ) { SettingsColumn(navController = navController, context = context) } }, backgroundColor = Color.Black ) }
0
Kotlin
0
0
2115bf7c3bc4558a40d2ab9181b295940848df7b
2,637
TONContest
MIT License
src/commonMain/kotlin/io/revenuemonster/sdk/model/response/TopUpHistory.kt
RevenueMonster
370,565,536
false
{"Kotlin": 74776}
package io.revenuemonster.sdk.model.response import kotlinx.datetime.Instant import kotlinx.serialization.Serializable @Serializable data class TopUpHistory( val id: String, val walletId: String, val referenceId: String, val adminId: String, val detail: String, val method: String, val status: String, val credit: String, val createdAt: Instant )
5
Kotlin
0
2
d5c60e62cc9242839dc45c7bafba1b4ef2d639ab
384
rm-kotlin-sdk
MIT License
wraith/src/main/java/com/nomba/wraith/ui/shelters/transfer/TransferExpiredShelter.kt
kudi-inc
762,178,069
false
{"Kotlin": 110256}
package com.nomba.wraith.ui.shelters.transfer import com.nomba.wraith.core.NombaManager import com.nomba.wraith.core.Shelter import com.nomba.wraith.databinding.TransferExpiredViewBinding class TransferExpiredShelter(private var manager : NombaManager, activityTransferExpiredViewBinding: TransferExpiredViewBinding) : Shelter(activityTransferExpiredViewBinding) { override fun layout(): TransferExpiredViewBinding { return super.layout() as TransferExpiredViewBinding } override fun showShelter() { super.showShelter() layout().tryAgainBtn.setOnClickListener { manager.showTransferView() } layout().transferExpiredChangePaymentMtdBtn.setOnClickListener { manager.showPaymentOptionsView() } layout().sentMnyBtn.setOnClickListener { hideShelter() manager.showTransferConfirmationView() } } }
0
Kotlin
0
0
339d91132edcc0c6fd72b1f79ce8287437fb2754
926
nomba-android-sdk
MIT License
app/src/main/java/com/battlelancer/seriesguide/shows/search/discover/ShowsDiscoverViewModel.kt
UweTrottmann
1,990,682
false
{"Kotlin": 2280980, "Java": 880919, "PowerShell": 1268}
// SPDX-License-Identifier: Apache-2.0 // Copyright 2018-2024 <NAME> package com.battlelancer.seriesguide.shows.search.discover import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.shows.ShowsSettings import com.battlelancer.seriesguide.streaming.SgWatchProvider import com.battlelancer.seriesguide.streaming.StreamingSearch import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.launch import timber.log.Timber class ShowsDiscoverViewModel(application: Application) : AndroidViewModel(application) { val isRefreshing = MutableStateFlow(false) // Replay so combine gets an initial value on subscribing private val refresh = MutableSharedFlow<Unit>( replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST ) private val watchProviderIds = SgRoomDatabase.getInstance(getApplication()).sgWatchProviderHelper() .getEnabledWatchProviderIdsFlow(SgWatchProvider.Type.SHOWS.id) val data = combine( refresh, watchProviderIds ) { _: Unit, watchProviderIds: List<Int> -> watchProviderIds }.flatMapLatest { val languageCode = ShowsSettings.getShowsSearchLanguage(getApplication()) val watchRegion = StreamingSearch.getCurrentRegionOrNull(getApplication()) val firstReleaseYear = ShowsDiscoverSettings.getFirstReleaseYear(getApplication()) val originalLanguage = ShowsDiscoverSettings.getOriginalLanguage(getApplication()) ShowsDiscoverLiveData( application, viewModelScope, isRefreshing, languageCode, it, watchRegion, firstReleaseYear, originalLanguage ).asFlow() }.shareIn( scope = viewModelScope, started = SharingStarted.Lazily, replay = 1 ) init { refresh.tryEmit(Unit) } /** * Returns whether new data will be loaded. */ fun refreshData() { viewModelScope.launch { refresh.emit(Unit) } } fun changeResultsLanguage(languageCode: String) { ShowsSettings.saveShowsSearchLanguage(getApplication(), languageCode) Timber.d("Set search language to %s", languageCode) refreshData() } fun changeFirstReleaseYear(year: Int?) { ShowsDiscoverSettings.setFirstReleaseYear(getApplication(), year) refreshData() } fun changeOriginalLanguage(languageCode: String?) { ShowsDiscoverSettings.setOriginalLanguage(getApplication(), languageCode) refreshData() } }
56
Kotlin
401
1,966
c7bc6445ecc58b841c1887a56146dc2d2f817007
3,134
SeriesGuide
Apache License 2.0
quickhttpclient/src/main/java/com/relatablecode/quickhttpclient/logging_utils/Logger.kt
thaer-al-khishen
709,499,444
false
{"Kotlin": 56738}
package com.relatablecode.quickhttpclient.logging_utils import android.util.Log /** * A utility logger to aid in logging messages of different levels. */ object Logger { var condition: Boolean = true fun d(tag: String, message: String) { if (condition) { Log.d(tag, message) } } fun e(tag: String, message: String) { if (condition) { Log.e(tag, message) } } // ... add methods for other log levels }
0
Kotlin
0
0
66365a96a81a038bf5703ce48c20f8f6afb3db98
487
quick-http-client
Apache License 2.0
src/main/kotlin/com/microservices/service/SquigglyConfig.kt
nsm257
190,715,422
false
null
package com.microservices.service import com.fasterxml.jackson.databind.ObjectMapper import com.github.bohnman.squiggly.web.SquigglyRequestFilter import com.github.bohnman.squiggly.context.provider.SquigglyFilterHolder.setFilter import com.github.bohnman.squiggly.web.RequestSquigglyContextProvider import com.github.bohnman.squiggly.Squiggly import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.web.servlet.FilterRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration //@Configuration //@ConditionalOnClass(ObjectMapper::class) //class SquigglyAutoconfigure { // // @Bean // fun squigglyRequestFilter(objectMapper: ObjectMapper): Any { // Squiggly.init(objectMapper, RequestSquigglyContextProvider()) // // val filter = FilterRegistrationBean<SquigglyRequestFilter>() // filter.filter = SquigglyRequestFilter() // filter.order = 1 // // return filter // } //}
0
Kotlin
0
0
6123dc49fa486ef353e47f96a8ba72060f73c302
1,034
filter-service
Apache License 2.0
library/src/main/java/net/sarangnamu/common/arch/adapter/BkAdapter.kt
aucd29
46,907,830
false
null
/* * Copyright 2016 <NAME> All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sarangnamu.common.arch.adapter import android.arch.lifecycle.ViewModel import android.content.Context import android.databinding.ViewDataBinding import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.slf4j.LoggerFactory /** * Created by <a href="mailto:<EMAIL>"><NAME></a> on 2018. 5. 11.. <p/> */ interface IBkItem { fun type() : Int } interface BkContentDiffCallback { fun diffContent(oldItem: Any?, newItem: Any?): Boolean } class BkViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { lateinit var binding: ViewDataBinding } class BkAdapter<I> : RecyclerView.Adapter<BkViewHolder> { companion object { private val log = LoggerFactory.getLogger(BkAdapter::class.java) protected fun bindClassName(context: Context, layoutId: String): String { val sb = StringBuilder() sb.append(context.packageName) sb.append(".databinding.") sb.append(Character.toUpperCase(layoutId[0])) var i = 1 while (i < layoutId.length) { var c = layoutId[i] if (c == '_') { c = layoutId[++i] sb.append(Character.toUpperCase(c)) } else { sb.append(c) } } sb.append("Binding") return sb.toString() } protected fun invokeMethod(binding: ViewDataBinding, methodName: String, argType: Class<Any>, argVal: Any, logmsg: Boolean) { try { val method = binding.javaClass.getDeclaredMethod(methodName, argType) method.invoke(binding, argVal) } catch (e: Exception) { if (logmsg) { if (log.isDebugEnabled) { log.debug("NOT FOUND : ${e.message}") } } } } } private lateinit var layoutIds: Array<String> var items: List<I>? = null var vmodel: ViewModel? = null var diffCallback: BkContentDiffCallback? = null constructor(layoutId : String) { layoutIds = arrayOf(layoutId) } constructor(layoutIds: Array<String>) { this.layoutIds = layoutIds } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BkViewHolder? { val context = parent.context val layoutId = context.resources.getIdentifier(layoutIds[viewType], "layout", context.packageName) val view = LayoutInflater.from(context).inflate(layoutId, parent, false) if (log.isTraceEnabled()) { log.trace(String.format("LAYOUT ID : %s (%d)", layoutIds[viewType], layoutId)) } try { val classPath = bindClassName(context, layoutIds[viewType]) if (log.isTraceEnabled()) { log.trace("BINDING CLASS : $classPath") } val bindingClass = Class.forName(classPath) val method = bindingClass.getDeclaredMethod("bind", View::class.java) val vh = BkViewHolder(view) vh.binding = method.invoke(null, view) as ViewDataBinding return vh } catch (e: Exception) { e.printStackTrace() log.error("ERROR: ${e.message}") return null } } override fun onBindViewHolder(holder: BkViewHolder?, position: Int) { holder?.let { h -> vmodel?.let { invokeMethod(h.binding, "setModel", it.javaClass, it, false) } items?.let { invokeMethod(h.binding, "setItem", it.javaClass, it, false) } } } override fun getItemCount(): Int = items?.size ?: 0 override fun getItemViewType(position: Int): Int { if (items == null) { return 0 } val item = items!!.get(position) return if (item is IBkItem) item.type() else 0 } fun changeItems(newItems: ArrayList<I>) { if (this.items == null) { this.items = newItems notifyItemRangeInserted(0, newItems.size) return } if (diffCallback != null) { val diffRes = DiffUtil.calculateDiff(object: DiffUtil.Callback() { override fun getOldListSize(): Int = items!!.size override fun getNewListSize(): Int = newItems.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = items!!.get(oldItemPosition) == newItems.get(newItemPosition) override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return diffCallback!!.diffContent(items!!.get(oldItemPosition), newItems.get(newItemPosition)) } }) this.items = newItems diffRes.dispatchUpdatesTo(this) } else { this.items = newItems } } }
0
Kotlin
0
0
bc0630be6e34e4a3425883b49b70b507b6b184db
5,749
common
Apache License 2.0
src/commonMain/kotlin/fr/acinq/lightning/db/ChannelsDb.kt
ACINQ
243,326,972
false
null
package fr.acinq.lightning.db import fr.acinq.bitcoin.ByteVector32 import fr.acinq.lightning.CltvExpiry import fr.acinq.lightning.channel.ChannelStateWithCommitments interface ChannelsDb { suspend fun addOrUpdateChannel(state: ChannelStateWithCommitments) suspend fun removeChannel(channelId: ByteVector32) suspend fun listLocalChannels(): List<ChannelStateWithCommitments> suspend fun addHtlcInfo(channelId: ByteVector32, commitmentNumber: Long, paymentHash: ByteVector32, cltvExpiry: CltvExpiry) suspend fun listHtlcInfos(channelId: ByteVector32, commitmentNumber: Long): List<Pair<ByteVector32, CltvExpiry>> fun close() }
16
Kotlin
10
38
57af9b447df16b7a0b537d054bf6112e6d9c13c5
655
lightning-kmp
Apache License 2.0
kmm/kmm-gradle-plugins/src/main/kotlin/com/gchristov/newsfeed/kmmgradleplugins/KmmModulePlugin.kt
gchristov
473,375,093
false
{"Kotlin": 171793, "Swift": 75033, "Shell": 1988}
package com.gchristov.newsfeed.kmmgradleplugins import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension open class KmmModulePlugin : KmmPlatformPlugin() { override fun apply(target: Project) { super.apply(target) target.configureKotlin() target.configureDependencyInjection() target.configureTests() } } private fun Project.configureKotlin() { extensions.configure<KotlinMultiplatformExtension> { sourceSets.maybeCreate("commonMain").dependencies { api(project(":kmm-common-kotlin")) } } } private fun Project.configureDependencyInjection() { extensions.configure<KotlinMultiplatformExtension> { sourceSets.maybeCreate("commonMain").dependencies { api(project(":kmm-common-di")) } } } private fun Project.configureTests() { extensions.configure<KotlinMultiplatformExtension> { sourceSets.maybeCreate("commonMain").dependencies { api(project(":kmm-common-test")) } } }
4
Kotlin
0
9
9beaad41f6111545edd6b70c792d3a9d0787794a
1,102
newsfeed-kmm
Apache License 2.0
newm-shared/src/main/kotlin/io/newm/shared/exception/HttpStatusException.kt
projectNEWM
447,979,150
false
{"Kotlin": 2397847, "HTML": 185274, "Dockerfile": 2535, "Shell": 1986, "Procfile": 60}
package io.newm.shared.exception import io.ktor.http.HttpStatusCode sealed class HttpStatusException( val statusCode: HttpStatusCode, message: String ) : Exception(message) { companion object { fun HttpStatusCode.toException(message: String): HttpStatusException = when (this) { HttpStatusCode.BadRequest -> HttpBadRequestException(message) HttpStatusCode.Unauthorized -> HttpUnauthorizedException(message) HttpStatusCode.NotFound -> HttpUnauthorizedException(message) HttpStatusCode.Forbidden -> HttpUnauthorizedException(message) HttpStatusCode.UnprocessableEntity -> HttpUnauthorizedException(message) HttpStatusCode.Conflict -> HttpUnauthorizedException(message) HttpStatusCode.ServiceUnavailable -> HttpServiceUnavailableException(message) HttpStatusCode.PaymentRequired -> HttpPaymentRequiredException(message) else -> HttpUnknownException(this, message) } } } class HttpBadRequestException( message: String ) : HttpStatusException(HttpStatusCode.BadRequest, message) class HttpUnauthorizedException( message: String ) : HttpStatusException(HttpStatusCode.Unauthorized, message) class HttpNotFoundException( message: String ) : HttpStatusException(HttpStatusCode.NotFound, message) class HttpForbiddenException( message: String ) : HttpStatusException(HttpStatusCode.Forbidden, message) class HttpUnprocessableEntityException( message: String ) : HttpStatusException(HttpStatusCode.UnprocessableEntity, message) class HttpConflictException( message: String ) : HttpStatusException(HttpStatusCode.Conflict, message) class HttpServiceUnavailableException( message: String ) : HttpStatusException(HttpStatusCode.ServiceUnavailable, message) class HttpPaymentRequiredException( message: String ) : HttpStatusException(HttpStatusCode.PaymentRequired, message) class HttpUnknownException( httpStatusCode: HttpStatusCode, message: String ) : HttpStatusException(httpStatusCode, message)
1
Kotlin
4
10
8ec8b7c249290f4d34dca9275d45b74571c7aaeb
2,129
newm-server
Apache License 2.0
src/main/kotlin/maliwan/mcbl/weapons/gun/behaviour/smg/Bitch.kt
HannahSchellekens
868,217,631
false
{"Kotlin": 661924}
package maliwan.mcbl.weapons.gun.behaviour.smg import maliwan.mcbl.weapons.gun.* import maliwan.mcbl.weapons.gun.behaviour.PostGenerationBehaviour import maliwan.mcbl.weapons.gun.behaviour.UniqueGun import maliwan.mcbl.weapons.gun.parts.SmgParts /** * @author <NAME> */ open class Bitch : UniqueGun, PostGenerationBehaviour { override val baseName = "Bitch" override val redText = "yup. back." override fun onFinishGeneration(properties: GunProperties, assembly: WeaponAssembly) { SmgParts.Barrel.HYPERION.applyStatModifiers(properties) statModifiers.applyAll(properties) } companion object { val statModifiers = statModifierList { multiply(1.15, StatModifier.Property.BASE_DAMAGE) multiply(1.35, StatModifier.Property.MAGAZINE_SIZE) add(0.50, StatModifier.Property.BONUS_CRIT_MULTIPLIER) } } }
0
Kotlin
0
1
794eb28189b26c92e8de3ade5eb0d36b9e799d08
894
MCBorderlands
MIT License
observablevalidatorsample/src/main/java/com/umobi/observablevalidatorsample/ui/login/MainActivity.kt
thalisvilela
208,066,283
false
null
package com.umobi.observablevalidatorsample.ui.login import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.umobi.observablevalidatorsample.databinding.ActivityMainBinding import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var registerViewModel: RegisterViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) binding.lifecycleOwner = this setContentView(binding.root) registerViewModel = ViewModelProviders.of(this) .get(RegisterViewModel::class.java) binding.viewModel = registerViewModel register.setOnClickListener { if(registerViewModel.validator.validateAll()){ Snackbar.make(binding.root, "All good! Proceeding to register!", Snackbar.LENGTH_LONG).show() }else{ Snackbar.make(binding.root, "Validation failed!", Snackbar.LENGTH_LONG).show() } } } }
0
Kotlin
2
9
cffd45c65b73f6f1e3155fcafcaad63cf81c48d0
1,217
ObservableValidator
Apache License 2.0
observablevalidatorsample/src/main/java/com/umobi/observablevalidatorsample/ui/login/MainActivity.kt
thalisvilela
208,066,283
false
null
package com.umobi.observablevalidatorsample.ui.login import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.umobi.observablevalidatorsample.databinding.ActivityMainBinding import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private lateinit var registerViewModel: RegisterViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) binding.lifecycleOwner = this setContentView(binding.root) registerViewModel = ViewModelProviders.of(this) .get(RegisterViewModel::class.java) binding.viewModel = registerViewModel register.setOnClickListener { if(registerViewModel.validator.validateAll()){ Snackbar.make(binding.root, "All good! Proceeding to register!", Snackbar.LENGTH_LONG).show() }else{ Snackbar.make(binding.root, "Validation failed!", Snackbar.LENGTH_LONG).show() } } } }
0
Kotlin
2
9
cffd45c65b73f6f1e3155fcafcaad63cf81c48d0
1,217
ObservableValidator
Apache License 2.0
app/src/main/java/com/weixin/wuyezhiguhun/ydandroid/ydjoke/viewmodel/YDJokeViewModel.kt
wuyezhiguhun
144,582,482
false
null
package com.weixin.wuyezhiguhun.ydandroid.ydjoke.viewmodel import com.weixin.wuyezhiguhun.ydandroid.ydjoke.data.YDJokeInfo import okhttp3.* import org.json.JSONObject import java.io.IOException import java.util.* class YDJokeViewModel { var dataList: ArrayList<YDJokeInfo> = ArrayList() // var viewModelBack: YDViewModelBack? = null // lateinit var mListen:() -> Unit interface YDJokeViewModelBack { fun networkingSuccess() fun networkingFailure() } lateinit var mListen: YDJokeViewModelBack fun setListeren(viewModelBack: YDJokeViewModelBack) { this.mListen = viewModelBack // this.mListen() } // override fun networkingFailure() { // // } // // override fun networkingSuccess() { // // } init { addDataList() } fun addDataList() : ArrayList<YDJokeInfo> { val textArray: ArrayList<String> = ArrayList() textArray.add("你站在桥上看风景,看风景的人在桥上看你;明月装饰了你的窗子,你装饰了别人的梦!") textArray.add("死生契阔,与子成说。执子之手,与子偕老。") textArray.add("有美人兮,见之不忘,一日不见兮,思之如狂。") textArray.add("君若扬路尘,妾若浊水泥,浮沈各异势,会合何时谐?") textArray.add("如何让你遇见我,在我最美丽的时刻为这,我已在佛前求了五百年,求他让我们结一段尘缘。") textArray.add("自君之出矣,明镜暗不治。思君如流水,何有穷已时。") for (i in 1..20) { val homeInfo: YDJokeInfo = YDJokeInfo() val random: Int = Random().nextInt(6) homeInfo.content = textArray.get(random) val number: Int = Random().nextInt(13) + 1 homeInfo.image_name = "anime_" + number.toString() dataList.add(homeInfo) } return dataList } //网络请求数据 fun setJokeXiaohuaData(pageIndex: Int,pageSize: Int) { val host: String = "http://jisuxhdq.market.alicloudapi.com" val path: String = "/xiaohua/text" val querys: String = "?pagenum=" + pageIndex.toString() + "&pagesize=" + pageSize.toString() + "&sort=rand" val url: String = host + path + querys println("wuyezhiguhun: " + url) val httpClient: OkHttpClient = OkHttpClient() val request: Request = Request.Builder().url(url).get().addHeader("Authorization", "APPCODE 9b2dd63024474f79b69a8aab70c8d658").build() val call: Call = httpClient.newCall(request) call.enqueue( object : Callback{ override fun onFailure(call: Call?, e: IOException?) { // runOnUiThread { } mListen.networkingFailure() println("wuyezhiguhun: " + "网络请求失败!") } override fun onResponse(call: Call?, response: Response?) { val bodyString = response?.body()?.string() val jsonObject = JSONObject(bodyString) val dataObject = jsonObject.getJSONObject("result") val dataArray = dataObject.getJSONArray("list") // val jokeList: ArrayList<YDJokeInfo> = ArrayList() dataList.clear() for (num in 0..dataArray.length() - 1) { val jokeJson = dataArray.getJSONObject(num) val homeInfo: YDJokeInfo = YDJokeInfo() homeInfo.content = jokeJson.getString("content") homeInfo.addtime = jokeJson.getString("addtime") val number: Int = Random().nextInt(13) + 1 homeInfo.image_name = "anime_" + number.toString() dataList.add(homeInfo) } // dataList = jokeList mListen.networkingSuccess() } }) } }
0
Kotlin
0
1
aaf13dc341cc525d4232d56fe803bc3a73fbc055
3,571
YDAndroid
MIT License
gui/src/main/kotlin/no/uib/inf219/gui/backend/cb/simple/StringClassBuilder.kt
elgbar
232,797,797
false
null
/* * Copyright 2020 <NAME> * * 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 no.uib.inf219.gui.backend.cb.simple import javafx.event.EventTarget import javafx.scene.control.TreeItem import no.uib.inf219.gui.backend.cb.api.ClassBuilder import no.uib.inf219.gui.backend.cb.api.ParentClassBuilder import no.uib.inf219.gui.backend.cb.api.SimpleClassBuilder import no.uib.inf219.gui.controllers.ObjectEditorController import no.uib.inf219.gui.controllers.cbn.ClassBuilderNode import no.uib.inf219.gui.converter.StringStringConverter import no.uib.inf219.gui.loader.ClassInformation import tornadofx.textarea /** * Note that the default value is the empty String `""` and not the default value `null` */ class StringClassBuilder( initial: String = "", key: ClassBuilder?, parent: ParentClassBuilder?, property: ClassInformation.PropertyMetadata? = null, immutable: Boolean = false, item: TreeItem<ClassBuilderNode> ) : SimpleClassBuilder<String>(String::class, initial, key, parent, property, immutable, StringStringConverter, item) { override fun createEditView( parent: EventTarget, controller: ObjectEditorController ) = parent.textarea { bindStringProperty(textProperty(), converter, serObjectObservable) } override fun validate(text: String): Boolean { // A string is always a valid string return true } }
0
Kotlin
0
1
4ce6a92bfbe71e0245bd495f5dc9736741e022fd
1,917
HandcraftObjectsTool
Apache License 2.0
app/src/main/java/com/siju/acexplorer/storage/view/DragHelper.kt
siju-s
427,592,750
false
null
/* * Copyright (C) 2017 Ace Explorer owned by Siju Sakaria * * 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.siju.acexplorer.storage.view import android.content.ClipDescription import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.util.Log import android.view.DragEvent import android.view.View import com.siju.acexplorer.R import com.siju.acexplorer.analytics.Analytics import com.siju.acexplorer.common.types.FileInfo import com.siju.acexplorer.main.view.dialog.DialogHelper import java.util.* private const val TEXT_WIDTH_PX = 200 private const val TAG = "DragHelper" class DragHelper(private val context: Context, private val filesList: FilesList) { val dragListener = DragEventListener() private fun writeOnDrawable(text: String): BitmapDrawable { val bitmap = Bitmap.createBitmap(TEXT_WIDTH_PX, TEXT_WIDTH_PX, Bitmap.Config.ARGB_8888) bitmap.eraseColor(Color.DKGRAY) val paint = Paint() paint.style = Paint.Style.FILL paint.isAntiAlias = true paint.color = Color.WHITE val countFont = context.resources .getDimensionPixelSize(R.dimen.drag_shadow_font) paint.textSize = countFont.toFloat() val canvas = Canvas(bitmap) val strLength = paint.measureText(text).toInt() val x = bitmap.width / 2 - strLength // int y = s.titleOffset; val y = (bitmap.height - countFont) / 2 // drawText(canvas, x, y, title, labelWidth - s.leftMargin - x // - s.titleRightMargin, mTitlePaint); canvas.drawText(text, x.toFloat(), (y - paint.fontMetricsInt.ascent).toFloat(), paint) // canvas.drawText(text, bitmap.getWidth() / 2, bitmap.getHeight() / 2, paint); return BitmapDrawable(context.resources, bitmap) } fun getDragShadowBuilder(view: View, count: Int): CustomDragShadowBuilder { return CustomDragShadowBuilder(view, count) } inner class CustomDragShadowBuilder(view: View, count: Int) : View.DragShadowBuilder(view) { // The drag shadow image, defined as a drawable thing private val shadow: Drawable init { // Creates a draggable image that will fill the Canvas provided by the system. shadow = writeOnDrawable("" + count) } // Defines a callback that sends the drag shadow dimensions and touch point back to the // system. override fun onProvideShadowMetrics(size: Point, touch: Point) { // Defines local variables val width: Int = view.width / 6 val height: Int = view.height / 2 // The drag shadow is a ColorDrawable. This sets its dimensions to be the same as the // Canvas that the system will provide. As a result, the drag shadow will fill the // Canvas. shadow.setBounds(0, 0, width, height) // Sets the size parameter's width and height values. These get back to the system // through the size parameter. size.set(width, height) // Sets the touch point's position to be in the middle of the drag shadow touch.set(2 * width, height * 2) } // Defines a callback that draws the drag shadow in a Canvas that the system constructs // from the dimensions passed in onProvideShadowMetrics(). override fun onDrawShadow(canvas: Canvas) { // Draws the ColorDrawable in the Canvas passed in from the system. shadow.draw(canvas) } } fun showDragDialog(sourcePaths: ArrayList<FileInfo>, destinationDir: String?, dragDialogListener: DialogHelper.DragDialogListener) { Analytics.logger.dragDialogShown() DialogHelper.showDragDialog(context, sourcePaths, destinationDir, dragDialogListener) } inner class DragEventListener : View.OnDragListener { private var oldPos = -1 override fun onDrag(view: View, event: DragEvent): Boolean { when (event.action) { DragEvent.ACTION_DRAG_STARTED -> // Determines if this View can accept the dragged data return event.clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_INTENT) // Returns false. During the current drag and drop operation, this View will // not receive events again until ACTION_DRAG_ENDED is sent. DragEvent.ACTION_DRAG_ENTERED -> return true DragEvent.ACTION_DRAG_LOCATION -> { oldPos = filesList.onDragLocationEvent(event, oldPos) return true } DragEvent.ACTION_DRAG_EXITED -> return true DragEvent.ACTION_DROP -> { filesList.onDragDropEvent(event) return true } DragEvent.ACTION_DRAG_ENDED -> { filesList.onDragEnd(view, event) return true } // An unknown action type was received. else -> Log.d(TAG, "Unknown action type received by OnDragListener.") } return false } } }
4
Kotlin
5
2
68338f005f8365609f115390e7d770197b807763
5,989
AceExplorer
Apache License 2.0
src/main/kotlin/tokyo/aieuo/mineflow/trigger/event/BlockPlaceEventTrigger.kt
aieuo
364,472,156
false
null
package tokyo.aieuo.mineflow.trigger.event import cn.nukkit.entity.Entity import cn.nukkit.event.Event import cn.nukkit.event.block.BlockPlaceEvent import tokyo.aieuo.mineflow.utils.DummyVariableMap import tokyo.aieuo.mineflow.utils.VariableMap import tokyo.aieuo.mineflow.variable.DefaultVariables import tokyo.aieuo.mineflow.variable.DummyVariable class BlockPlaceEventTrigger(subKey: String = "") : EventTrigger(BlockPlaceEvent::class, subKey) { override fun getTargetEntity(event: Event): Entity? = getTargetEntity(event as BlockPlaceEvent) override fun getVariables(event: Event): VariableMap = getVariables(event as BlockPlaceEvent) fun getTargetEntity(event: BlockPlaceEvent): Entity? { return event.player } fun getVariables(event: BlockPlaceEvent): VariableMap { val target = event.player val block = event.block return DefaultVariables.getPlayerVariables(target) + DefaultVariables.getBlockVariables(block) } override fun getVariablesDummy(): DummyVariableMap { return mapOf( "target" to DummyVariable(DummyVariable.Type.PLAYER), "block" to DummyVariable(DummyVariable.Type.BLOCK), ) } }
0
Kotlin
0
0
9c2ef7133d84c5d9b6f4336463d9e1d56442924a
1,207
Mineflow-Kotlin
MIT License
features/forms/src/main/java/com/ramonpsatu/studyorganizer/features/forms/SubjectFormFragment.kt
ramonpsatu
678,104,957
false
null
package com.ramonpsatu.studyorganizer.features.forms import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.navigation.fragment.findNavController import com.ramonpsatu.studyorganizer.core.data.utils.toastMessageShort import com.ramonpsatu.studyorganizer.features.collections.utils.StateHolderObject import com.ramonpsatu.studyorganizer.features.collections.viewmodels.SubjectListViewModel import com.ramonpsatu.studyorganizer.features.forms.databinding.FragmentSubjectFormBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import java.util.UUID /** * @author Ramon Pedrosa. * A [Fragment] that displays a form of the subject. * @property backgroundColor sets a background color for the subject item. * @property daysOfWeek represents the days of the week the subjects were saved. * @property turnOn used to assist in the selection of textViews. * */ @AndroidEntryPoint class SubjectFormFragment : Fragment(), View.OnClickListener { private var _binding: FragmentSubjectFormBinding? = null private val binding get() = _binding!! private var turnOn: Array<Boolean> = arrayOf(true, true, true, true, true, true, true) private var backgroundColor: Int = 0 private var daysOfWeek: MutableList<Int> = mutableListOf() private lateinit var viewModel: SubjectListViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(this)[SubjectListViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSubjectFormBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setAllDays() changeTextByScreenEditOrNew() setOnClickListeners() reloadFieldsOfSubject() navigation() } override fun onClick(v: View) { switchBackgroundColorDaysOfWeek(v) switchBackgroundColorViews(v) } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun setAllDays() { binding.buttonAllDays.setOnClickListener { ifMondaySetDay() ifTuesdaySetDay() ifWednesdaySetDay() ifThursSetDay() ifFridaySetDay() ifSaturdaySetDay() ifSundaySetDay() } } private fun changeTextByScreenEditOrNew() { if (StateHolderObject.turn_flag_SaveOrUpdate) { binding.textViewSubjectWordExhibition.text = getString(com.ramonpsatu.studyorganizer.core.ui.R.string.text_new_subject_words) } else { binding.textViewSubjectWordExhibition.text = getString(com.ramonpsatu.studyorganizer.core.ui.R.string.text_edit_subject_words) binding.buttonNewSubjectSave.text = getString(com.ramonpsatu.studyorganizer.core.ui.R.string.contentDescription_save_button) } } /** * Used to reload the fields that existing in form screen. * * This list displays the colors in the int value: * 1- (-482566) represents LightPink color. * 2- (-342111) represents CreamOrange color. * 3- (-21589) represents RedPink color. * 4- (-4020486) represents LightPurple color. * 5- (-5974790) represents LightBlue color. * 6-(-4589919) represents LightGreen color. * 7-(-596352) represents LightYellow color. * *@author Ramon Pedrosa */ private fun reloadFieldsOfSubject() { if (!StateHolderObject.turn_flag_SaveOrUpdate) { binding.textInputLayoutTitle.setText(StateHolderObject.safeArgsSubjectItem().title) reloadTextsFieldsForUpdateSubject() val color = StateHolderObject.safeArgsSubjectItem().backgroundColor reloadBackgroundViewColorForUpdateSubject(color) } } private fun navigation() { binding.imageViewBack.setOnClickListener { findNavController().navigate(com.ramonpsatu.studyorganizer.core.ui.R.id.action_subjectFormFragment_to_subjectFragment) } binding.buttonNewSubjectSave.setOnClickListener { onSaveOrUpdate() } } /** * Handles saving or updating of the subject. */ private fun onSaveOrUpdate() { if (StateHolderObject.turn_flag_SaveOrUpdate) { if ((!binding.textInputLayoutTitle.text.isNullOrEmpty()) && (backgroundColor != 0) && (daysOfWeek.size > 0) ) { val id = UUID.randomUUID().toString() viewModel.viewModelScope.launch { viewModel.addSubject( id, binding.textInputLayoutTitle.text.toString(), 0, backgroundColor, daysOfWeek, 0, viewModel.getSubjectListSize()+1 ) findNavController().navigate(com.ramonpsatu.studyorganizer.core.ui.R.id.action_subjectFormFragment_to_subjectFragment) } StateHolderObject.turn_flag_SaveOrUpdate = false StateHolderObject.currentNavbarButton = 1 } else { noEmptyFieldsToast() } } else { if ((!binding.textInputLayoutTitle.text.isNullOrEmpty()) && (backgroundColor != 0) && (daysOfWeek.size > 0) ) { viewModel.viewModelScope.launch { viewModel.updateSubject( binding.textInputLayoutTitle.text.toString(), backgroundColor, daysOfWeek, StateHolderObject.safeArgsSubjectItem().id ) findNavController().navigate(com.ramonpsatu.studyorganizer.core.ui.R.id.action_subjectFormFragment_to_subjectFragment) } } else { noEmptyFieldsToast() } } } private fun noEmptyFieldsToast() { toastMessageShort( requireContext(), getString(com.ramonpsatu.studyorganizer.core.ui.R.string.text_title_toast_msg_fields_form) ) } private fun ifMondaySetDay() { if (turnOn[0]) { binding.textViewSubjectMonday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(1) turnOn[0] = false } else { binding.textViewSubjectMonday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(1) turnOn[0] = true } } private fun ifTuesdaySetDay() { if (turnOn[1]) { binding.textViewSubjectTuesday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(2) turnOn[1] = false } else { binding.textViewSubjectTuesday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(2) turnOn[1] = true } } private fun ifWednesdaySetDay() { if (turnOn[2]) { binding.textViewSubjectWednesday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(3) turnOn[2] = false } else { binding.textViewSubjectWednesday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(3) turnOn[2] = true } } private fun ifThursSetDay() { if (turnOn[3]) { binding.textViewSubjectThursday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(4) turnOn[3] = false } else { binding.textViewSubjectThursday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(4) turnOn[3] = true } } private fun ifFridaySetDay() { if (turnOn[4]) { binding.textViewSubjectFriday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(5) turnOn[4] = false } else { binding.textViewSubjectFriday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(5) turnOn[4] = true } } private fun ifSaturdaySetDay() { if (turnOn[5]) { binding.textViewSubjectSaturday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(6) turnOn[5] = false } else { binding.textViewSubjectSaturday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(6) turnOn[5] = true } } private fun ifSundaySetDay() { if (turnOn[6]) { binding.textViewSubjectSunday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.colorSecondary_default ) ) daysOfWeek.add(7) turnOn[6] = false } else { binding.textViewSubjectSunday.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.white ) ) daysOfWeek.remove(7) turnOn[6] = true } } /** * Returns an int value that represents the color in the database. */ private fun setBackgroundColor(v: View): Int { var backgroundColor = 0 when (v.id) { R.id.view_color_light_gray-> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray ) } R.id.view_color_lightPink -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_pink ) } R.id.view_color_creamOrange -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.cream_orange ) } R.id.view_color_redPink -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.red_pink ) } R.id.view_color_lightPurple -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_purple ) } R.id.view_color_lightBlue -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_blue ) } R.id.view_color_lightGreen -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_green ) } R.id.view_color_lightYellow -> { backgroundColor = ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_yellow ) } } return backgroundColor } private fun setOnClickListeners() { binding.textViewSubjectMonday.setOnClickListener(this) binding.textViewSubjectTuesday.setOnClickListener(this) binding.textViewSubjectWednesday.setOnClickListener(this) binding.textViewSubjectThursday.setOnClickListener(this) binding.textViewSubjectFriday.setOnClickListener(this) binding.textViewSubjectSaturday.setOnClickListener(this) binding.textViewSubjectSunday.setOnClickListener(this) binding.viewColorLightPink.setOnClickListener(this) binding.viewColorCreamOrange.setOnClickListener(this) binding.viewColorRedPink.setOnClickListener(this) binding.viewColorLightPurple.setOnClickListener(this) binding.viewColorLightBlue.setOnClickListener(this) binding.viewColorLightGreen.setOnClickListener(this) binding.viewColorLightYellow.setOnClickListener(this) binding.viewColorLightGray.setOnClickListener(this) } /** * Choose a color,switch between background colors. */ private fun switchBackgroundColorViews(v: View) { when (v.id) { R.id.view_color_light_gray -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_light_gray )) binding.viewColorLightPink.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink )) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_lightPink -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightPink.background.setTint(backgroundColor) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_creamOrange -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorCreamOrange.background.setTint( backgroundColor ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_redPink -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorRedPink.background.setTint( backgroundColor ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_lightPurple -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightPurple.background.setTint( backgroundColor ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_lightBlue -> { binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) this.backgroundColor = setBackgroundColor(v) binding.viewColorLightBlue.background.setTint( backgroundColor ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_lightGreen -> { binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGreen.background.setTint( backgroundColor ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } R.id.view_color_lightYellow -> { this.backgroundColor = setBackgroundColor(v) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightYellow.background.setTint( backgroundColor ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) } } } /** * Choose the days of the week,alternate between days of the week. */ private fun switchBackgroundColorDaysOfWeek(v: View) { when (v.id) { R.id.textView_subject_monday -> { ifMondaySetDay() } R.id.textView_subject_tuesday -> { ifTuesdaySetDay() } R.id.textView_subject_wednesday -> { ifWednesdaySetDay() } R.id.textView_subject_thursday -> { ifThursSetDay() } R.id.textView_subject_friday -> { ifFridaySetDay() } R.id.textView_subject_saturday -> { ifSaturdaySetDay() } R.id.textView_subject_sunday -> { ifSundaySetDay() } } } /** * Reload the days of the week that subjects were saved. */ private fun reloadTextsFieldsForUpdateSubject() { for (i in 0..StateHolderObject.safeArgsSubjectItem().daysOfWeek.size step 1) { for (e in StateHolderObject.safeArgsSubjectItem().daysOfWeek) { when (e) { 1 -> { if (turnOn[0]) { ifMondaySetDay() } } 2 -> { if (turnOn[1]) { ifTuesdaySetDay() } } 3 -> { if (turnOn[2]) { ifWednesdaySetDay() } } 4 -> { if (turnOn[3]) { ifThursSetDay() } } 5 -> { if (turnOn[4]) { ifFridaySetDay() } } 6 -> { if (turnOn[5]) { ifSaturdaySetDay() } } 7 -> { if (turnOn[6]) { ifSundaySetDay() } } } } } } private fun reloadBackgroundViewColorForUpdateSubject(color: Int) { when (color) { //LightGray -2500135 -> { this.backgroundColor = color binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_light_gray )) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //LightPink -482566 -> { this.backgroundColor = color binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightPink.background.setTint(backgroundColor) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //CreamOrange -342111 -> { this.backgroundColor = color binding.viewColorCreamOrange.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //RedPink -21589 -> { this.backgroundColor = color binding.viewColorRedPink.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //LightPurple -4020486 -> { this.backgroundColor = color binding.viewColorLightPurple.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //LightBlue -5974790 -> { this.backgroundColor = color binding.viewColorLightBlue.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //LightGreen -4589919 -> { this.backgroundColor = color binding.viewColorLightGreen.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) binding.viewColorLightYellow.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_yellow ) ) } //LightYellow -596352 -> { this.backgroundColor = color binding.viewColorLightYellow.background.setTint( backgroundColor ) binding.viewColorLightGray.background.setTint(ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.light_gray )) binding.viewColorLightGreen.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_green ) ) binding.viewColorLightBlue.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_blue ) ) binding.viewColorRedPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_red_pink ) ) binding.viewColorCreamOrange.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_orange ) ) binding.viewColorLightPink.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_pink ) ) binding.viewColorLightPurple.background.setTint( ContextCompat.getColor( requireContext(), com.ramonpsatu.studyorganizer.core.ui.R.color.bgColor_colorView_purple ) ) } } } }
0
Kotlin
0
0
b2f41b28aec9444c2970f32950fed5f2b78d79bc
52,805
Study-Organizer
MIT License
src/main/kotlin/com/rutilicus/uisetlist/UisetlistApplicationRunner.kt
rutilicus
231,705,129
false
null
package com.rutilicus.uisetlist import com.rutilicus.uisetlist.repository.ConfigRepository import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.stereotype.Component @Component class UisetlistApplicationRunner(val configRepository: ConfigRepository): ApplicationRunner { override fun run(args: ApplicationArguments?) { configRepository.findByKey(Constants.KEY_APP_NAME).let { Commons.appName = if (it.isEmpty()) { Constants.DEFAULT_APP_NAME } else { it.first().value } } configRepository.findByKey(Constants.KEY_TRANS_URL).let { if (!it.isEmpty()) { Commons.transUrl = it.first().value } } } }
4
Kotlin
1
1
d3a8e7ea33baaed77003448b1a10090f597e0a80
820
uisetlist
Apache License 2.0
engine/src/main/java/fr/jhelp/engine/animation/effect/ParticleNode.kt
jhelpgg
264,682,891
false
null
/* * <h1>License :</h1> <br/> * The following code is deliver as is. <br/> * You can use, modify, the code as your need for any usage.<br/> * But you can't do any action that avoid me or other person use, modify this code.<br/> * The code is free for usage and modification, you can't change that fact. */ package fr.jhelp.engine.animation.effect import fr.jhelp.animations.interpoolation.Interpolation import fr.jhelp.animations.interpoolation.LinearInterpolation import fr.jhelp.engine.scene.Color3D import fr.jhelp.engine.scene.GREY import fr.jhelp.engine.scene.Position3D import fr.jhelp.engine.scene.Texture import kotlin.math.max /** * Particle node emits one or several [Particle] * * [Particle]s can be emits on same time or one after other. * To regulate emission : * * *startEmissionFrame* : Number of frames to wait before launch the first [Particle] after [ParticleEffect] is launch * * *endEmissionFrame* : Number of frames to wait for stop emitting [Particle] after [ParticleEffect] is launch * So [Particle] are emits between *startEmissionFrame* and *endEmissionFrame* : * * If they are equals, all particles are emits in same time. * * Else, particles are emitting regularly during the laps time. * * Each [Particle] will have the given life time, they disappear after the defined number of frame. * * [Particle]s can start at same position or in position choose randomly inside a box, with [setPosition]. * If use the one coordinates version, all [Particle]s start at same position. * If use the two coordinates version, [Particle]s start position are chose randomly inside box defined by the two coordinates * * [Particle]s have a speed direction, this direction can be the same or chose inside a box, like position. With [setSpeedDirection] * * [Particle]s have an acceleration direction, this direction can be the same or chose inside a box, like position. With [setAccelerationDirection] * * [Particle]s rotation can change during animation [setAngle], [setSpeedRotation] and [setAccelerationRotation] regulate respectively the start angle, speed angle change and acceleration of angle. * * [Particle]s scale can change during animation [setScale], [setSpeedScale] and [setAccelerationScale] regulate respectively the start scale, speed cale direction and acceleration scale direction. * * [texture] defines the texture used by [Particle]s. If `null` no texture and only the diffuse color * * [Particle]s' diffuse color can change during animation and start/end can choose randomly depends on number arguments involved in [setDiffuseColor]. * The change color is not necessary linear, an interpolation method can be set with [diffuseInterpolation] * * [Particle]s' alpha value can change during animation [setAlpha] defines the start and the end value. * The way of the change can be choose with [alphaInterpolation] */ class ParticleNode(private val numberParticle: Int, private val lifeTimeInFrame: Float, private val startEmissionFrame: Float = 0f, private val stopEmissionFrame: Float = startEmissionFrame) { /**Texture used by [Particle]s*/ var texture: Texture? = null /**Way alpha evolve during animation*/ var alphaInterpolation: Interpolation = LinearInterpolation /**Way diffuse color evolve during animation*/ var diffuseInterpolation: Interpolation = LinearInterpolation private var position1 = Position3D() private var position2 = Position3D() private var speed1 = Position3D(scaleX = 0f, scaleY = 0f, scaleZ = 0f) private var speed2 = Position3D(scaleX = 0f, scaleY = 0f, scaleZ = 0f) private var acceleration1 = Position3D(scaleX = 0f, scaleY = 0f, scaleZ = 0f) private var acceleration2 = Position3D(scaleX = 0f, scaleY = 0f, scaleZ = 0f) private var alphaStart = 1.0f private var alphaEnd = 1.0f private var diffuseColorStart1 = GREY private var diffuseColorStart2 = GREY private var diffuseColorEnd1 = GREY private var diffuseColorEnd2 = GREY private var alreadyEmited: Int = 0 private var lastEmittedFrame: Float = 0f private val stepFrameEmission = (this.stopEmissionFrame - this.startEmissionFrame) / this.numberParticle /** * [Particle]s start position box definition. * * Note : * > If use one coordination version or same coordinates for both, the box is reduced to one point, so all [Particle] will starts at same point */ fun setPosition(x1: Float, y1: Float, z1: Float, x2: Float = x1, y2: Float = y1, z2: Float = z1) { this.position1.x = x1 this.position1.y = y1 this.position1.z = z1 this.position2.x = x2 this.position2.y = y2 this.position2.z = z2 } /** * [Particle]s start angle definition in degree. * * Note : * > If use one angle version or same angle value for both, all [Particle]s will start with the same angle */ fun setAngle(angle1: Float, angle2: Float = angle1) { this.position1.angleZ = angle1 this.position2.angleZ = angle2 } /** * [Particle]s start scale box definition. * * Note : * > If use one scale version or same scale values for both, the box is reduced to one point, so all [Particle] will starts with same scale */ fun setScale(scaleX1: Float, scaleY1: Float, scaleZ1: Float, scaleX2: Float = scaleX1, scaleY2: Float = scaleY1, scaleZ2: Float = scaleZ1) { this.position1.scaleX = scaleX1 this.position1.scaleY = scaleY1 this.position1.scaleZ = scaleZ1 this.position2.scaleX = scaleX2 this.position2.scaleY = scaleY2 this.position2.scaleZ = scaleZ2 } /** * [Particle]s start scale value * * Note : * > If use one scale version or same scale values for both, all [Particle] will starts with same scale */ fun setScale(scale1: Float, scale2: Float = scale1) { this.position1.scaleX = scale1 this.position1.scaleY = scale1 this.position1.scaleZ = scale1 this.position2.scaleX = scale2 this.position2.scaleY = scale2 this.position2.scaleZ = scale2 } /** * [Particle]s start speed direction box definition. * * Note : * > If use one coordination version or same coordinates for both, the box is reduced to one vector, so all [Particle] will starts with same speed */ fun setSpeedDirection(x1: Float, y1: Float, z1: Float, x2: Float = x1, y2: Float = y1, z2: Float = z1) { this.speed1.x = x1 this.speed1.y = y1 this.speed1.z = z1 this.speed2.x = x2 this.speed2.y = y2 this.speed2.z = z2 } /** * [Particle]s speed for rotation angle * * Note : * > If use one rotation angle value version or same rotation angle value for both, all [Particle] will have same speed for rotation angle */ fun setSpeedRotation(angle1: Float, angle2: Float = angle1) { this.speed1.angleZ = angle1 this.speed2.angleZ = angle2 } /** * [Particle]s start speed for scale direction box definition. * * Note : * > If use one coordination version or same coordinates for both, the box is reduced to one vector, so all [Particle] will starts with same speed for scale */ fun setSpeedScale(scaleX1: Float, scaleY1: Float, scaleZ1: Float, scaleX2: Float = scaleX1, scaleY2: Float = scaleY1, scaleZ2: Float = scaleZ1) { this.speed1.scaleX = scaleX1 this.speed1.scaleY = scaleY1 this.speed1.scaleZ = scaleZ1 this.speed2.scaleX = scaleX2 this.speed2.scaleY = scaleY2 this.speed2.scaleZ = scaleZ2 } /** * [Particle]s speed for scale in all direction * * Note : * > If use one scale value version or same scale value for both, all [Particle] will have same speed for scale */ fun setSpeedScale(scale1: Float, scale2: Float = scale1) { this.speed1.scaleX = scale1 this.speed1.scaleY = scale1 this.speed1.scaleZ = scale1 this.speed2.scaleX = scale2 this.speed2.scaleY = scale2 this.speed2.scaleZ = scale2 } /** * [Particle]s acceleration direction box definition. * * Note : * > If use one coordination version or same coordinates for both, the box is reduced to one vector, so all [Particle] will have same acceleration */ fun setAccelerationDirection(x1: Float, y1: Float, z1: Float, x2: Float = x1, y2: Float = y1, z2: Float = z1) { this.acceleration1.x = x1 this.acceleration1.y = y1 this.acceleration1.z = z1 this.acceleration2.x = x2 this.acceleration2.y = y2 this.acceleration2.z = z2 } /** * [Particle]s acceleration for rotation angle * * Note : * > If use one rotation angle value version or same rotation angle value for both, all [Particle] will have same acceleration for rotation angle */ fun setAccelerationRotation(angle1: Float, angle2: Float = angle1) { this.acceleration1.angleZ = angle1 this.acceleration2.angleZ = angle2 } /** * [Particle]s acceleration for scale direction box definition. * * Note : * > If use one coordination version or same coordinates for both, the box is reduced to one vector, so all [Particle] will have same acceleration for scale */ fun setAccelerationScale(scaleX1: Float, scaleY1: Float, scaleZ1: Float, scaleX2: Float = scaleX1, scaleY2: Float = scaleY1, scaleZ2: Float = scaleZ1) { this.acceleration1.scaleX = scaleX1 this.acceleration1.scaleY = scaleY1 this.acceleration1.scaleZ = scaleZ1 this.acceleration2.scaleX = scaleX2 this.acceleration2.scaleY = scaleY2 this.acceleration2.scaleZ = scaleZ2 } /** * [Particle]s acceleration for scale in all direction * * Note : * > If use one scale value version or same scale value for both, all [Particle] will have same acceleration for scale */ fun setAccelerationScale(scale1: Float, scale2: Float = scale1) { this.acceleration1.scaleX = scale1 this.acceleration1.scaleY = scale1 this.acceleration1.scaleZ = scale1 this.acceleration2.scaleX = scale2 this.acceleration2.scaleY = scale2 this.acceleration2.scaleZ = scale2 } /** * Define diffuse color for particle * * Diffuse color at start of animation is choose between *diffuseColorStart1* and *diffuseColorStart2*. * So if they are the same, all [Particle] will start with same color * * Diffuse color at end of animation is choose between *diffuseColorEnd1* and *diffuseColorEnd2*. * So if they are the same, all [Particle] will end with same color * * To regulate how change progress see [diffuseInterpolation] */ fun setDiffuseColor(diffuseColorStart1: Color3D, diffuseColorEnd1: Color3D = diffuseColorStart1, diffuseColorStart2: Color3D = diffuseColorStart1, diffuseColorEnd2: Color3D = diffuseColorEnd1) { this.diffuseColorStart1 = diffuseColorStart1 this.diffuseColorEnd1 = diffuseColorEnd1 this.diffuseColorStart2 = diffuseColorStart2 this.diffuseColorEnd2 = diffuseColorEnd2 } /** * Define alpha value. * * To regulate how change progress see [alphaInterpolation] * * @param alphaStart Value of alpha at animation start * @param alphaEnd Value of alpha at animation end */ fun setAlpha(alphaStart: Float, alphaEnd: Float = alphaStart) { this.alphaStart = alphaStart this.alphaEnd = alphaEnd } internal fun resetEmission() { this.alreadyEmited = 0 this.lastEmittedFrame = 0f } internal fun emitParticle(frame: Float, collector: (Particle) -> Unit): Boolean { if (this.lastEmittedFrame > this.stopEmissionFrame || this.alreadyEmited >= this.numberParticle) { this.lastEmittedFrame = frame return false } if (frame < this.startEmissionFrame) { this.lastEmittedFrame = frame return true } var emissionFrame = max(this.startEmissionFrame, this.lastEmittedFrame) if (emissionFrame >= this.stopEmissionFrame) { var particle: Particle for (number in this.alreadyEmited until this.numberParticle) { particle = Particle(this.stopEmissionFrame, randomPosition(), randomSpeed(), randomAcceleration(), this.lifeTimeInFrame) particle.material.texture = this.texture particle.alphaStart = this.alphaStart particle.alphaEnd = this.alphaEnd particle.alphaInterpolation = this.alphaInterpolation particle.diffuseStart = this.randomDiffuseColorStart() particle.diffuseEnd = this.randomDiffuseColorEnd() particle.diffuseInterpolation = this.diffuseInterpolation collector(particle) } this.alreadyEmited = this.numberParticle this.lastEmittedFrame = emissionFrame } else { while (emissionFrame <= frame && this.alreadyEmited < this.numberParticle) { collector(Particle(emissionFrame, randomPosition(), randomSpeed(), randomAcceleration(), this.lifeTimeInFrame)) this.alreadyEmited++ emissionFrame += this.stepFrameEmission this.lastEmittedFrame = emissionFrame } } return true } private fun randomPosition(): Position3D = this.random(this.position1, this.position2) private fun randomSpeed(): Position3D = this.random(this.speed1, this.speed2) private fun randomAcceleration(): Position3D = this.random(this.acceleration1, this.acceleration2) private fun random(position1: Position3D, position2: Position3D): Position3D = Position3D(fr.jhelp.utilities.random(position1.x, position2.x), fr.jhelp.utilities.random(position1.y, position2.y), fr.jhelp.utilities.random(position1.z, position2.z), fr.jhelp.utilities.random(position1.angleX, position2.angleX), fr.jhelp.utilities.random(position1.angleY, position2.angleY), fr.jhelp.utilities.random(position1.angleZ, position2.angleZ), fr.jhelp.utilities.random(position1.scaleX, position2.scaleX), fr.jhelp.utilities.random(position1.scaleY, position2.scaleY), fr.jhelp.utilities.random(position1.scaleZ, position2.scaleZ)) private fun randomDiffuseColorStart(): Color3D = this.randomColor(this.diffuseColorStart1, this.diffuseColorStart2) private fun randomDiffuseColorEnd(): Color3D = this.randomColor(this.diffuseColorEnd1, this.diffuseColorEnd2) private fun randomColor(color1: Color3D, color2: Color3D): Color3D = Color3D(fr.jhelp.utilities.random(color1.red, color2.red), fr.jhelp.utilities.random(color1.green, color2.green), fr.jhelp.utilities.random(color1.blue, color2.blue), fr.jhelp.utilities.random(color1.alpha, color2.alpha)) }
4
Kotlin
0
0
d912fedb330027216113f8af9f8974e8d2b1b7b6
16,010
AndroidEngine3D
Apache License 2.0
app/src/main/java/com/heig/yfitops/domain/models/Playlist.kt
Alessandro-AP
488,206,391
false
null
package com.heig.yfitops.domain.models import android.os.Parcelable import android.util.Log import com.google.firebase.firestore.DocumentSnapshot import com.heig.yfitops.utils.Constants.PLAYLIST_IMAGE_URL import com.heig.yfitops.utils.Constants.PLAYLIST_TITLE import kotlinx.parcelize.Parcelize /** * Playlist Entity. */ @Parcelize data class Playlist( val id: String, val title: String, val imageUrl: String ) : Parcelable { companion object { // create an Entity from Firebase data fun DocumentSnapshot.toPlaylist(): Playlist? { return try { Playlist( id, getString(PLAYLIST_TITLE)!!, getString(PLAYLIST_IMAGE_URL)!! ) } catch (e: Exception) { Log.e(TAG, "Error converting song", e) null } } private const val TAG = "Song" } }
0
Kotlin
0
2
15be1734b3f1e7f13c5ef015f74a1df81cef1695
947
Yfi-Tops
MIT License
base/scan/scan-kapt/src/main/java/com/spirytusz/booster/processor/scan/kapt/KmPropertyResolver.kt
spirytusz
392,160,927
false
null
package com.spirytusz.booster.processor.scan.kapt import com.google.gson.annotations.SerializedName import com.spirytusz.booster.processor.base.data.DeclarationScope import com.spirytusz.booster.processor.base.data.FieldInitializer import com.spirytusz.booster.processor.base.data.KtField import com.spirytusz.booster.processor.base.data.type.KtType import com.spirytusz.booster.processor.scan.kapt.data.KaptKtField import kotlinx.metadata.Flag import kotlinx.metadata.KmProperty import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.element.VariableElement class KmPropertyResolver( private val processingEnvironment: ProcessingEnvironment, private val belongingClass: TypeElement, private val aptVariableElement: VariableElement?, private val kmProperty: KmProperty ) { fun resolveKmProperty(): KtField { val fieldName = kmProperty.name val isFinal = !Flag.Property.IS_VAR(kmProperty.flags) val serializedNameAnnotation = aptVariableElement?.getAnnotation(SerializedName::class.java) val keys = if (serializedNameAnnotation != null) { val result = mutableListOf<String>() result.add(serializedNameAnnotation.value) result.addAll(serializedNameAnnotation.alternate) result.toList() } else { listOf(fieldName) } val initializer = if (Flag.Property.IS_DELEGATED(kmProperty.flags)) { FieldInitializer.DELEGATED } else { FieldInitializer.HAS_DEFAULT } val ktType = resolveKtType() return KaptKtField( isFinal = isFinal, fieldName = fieldName, keys = keys, ktType = ktType, initializer = initializer, transient = aptVariableElement?.modifiers?.contains(Modifier.TRANSIENT) == true, declarationScope = DeclarationScope.BODY, target = aptVariableElement ) } private fun resolveKtType(): KtType { return KmTypeResolver( processingEnvironment, aptVariableElement, kmProperty.returnType ).resolvedKtType } }
1
Kotlin
4
27
e2ede7bcece69832ae0267d1a34c4c6f2fdaac09
2,274
GsonBooster
MIT License
amazon/dynamodb/client/src/main/kotlin/org/http4k/connect/amazon/dynamodb/mapper/DynamoDbTableMapperExtensions.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.dynamodb.mapper fun <Document : Any, HashKey : Any, SortKey : Any> DynamoDbTableMapper<Document, HashKey, SortKey>.update( hashKey: HashKey, sortKey: SortKey? = null, updateFn: (Document) -> Document ): Document? { val original = get(hashKey, sortKey) ?: return null val updated = updateFn(original) save(updated) return updated } operator fun <Document : Any, HashKey : Any> DynamoDbTableMapper<Document, HashKey, *>.get( vararg keys: HashKey ): Sequence<Document> = batchGet(keys.map { it to null }) operator fun <Document : Any, HashKey : Any> DynamoDbTableMapper<Document, HashKey, *>.get( keys: Collection<HashKey> ): Sequence<Document> = batchGet(keys.map { it to null }) operator fun <Document : Any> DynamoDbTableMapper<Document, *, *>.plusAssign(documents: Collection<Document>) = batchSave(documents) operator fun <Document : Any> DynamoDbTableMapper<Document, *, *>.plusAssign(document: Document) = save(document) operator fun <Document : Any> DynamoDbTableMapper<Document, *, *>.minusAssign(document: Document) = delete(document) operator fun <Document : Any> DynamoDbTableMapper<Document, *, *>.minusAssign(documents: Collection<Document>) = batchDelete(documents) fun <HashKey : Any> DynamoDbTableMapper<*, HashKey, *>.batchDelete(vararg hashKeys: HashKey) = batchDelete(hashKeys.toList()) fun <HashKey : Any> DynamoDbTableMapper<*, HashKey, *>.batchDelete(hashKeys: Collection<HashKey>) = batchDelete(hashKeys.map { it to null })
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
1,548
http4k-connect
Apache License 2.0
app/src/main/java/com/example/android/architecture/blueprints/todoapp/domain/ActivateTasksUseCase.kt
tteukkeun
279,205,014
true
{"Kotlin": 237956}
package com.example.android.architecture.blueprints.todoapp.domain import com.example.android.architecture.blueprints.todoapp.domain.entity.Task import com.example.android.architecture.blueprints.todoapp.domain.repository.TasksRepository import com.example.android.architecture.blueprints.todoapp.presentation.util.wrapEspressoIdlingResource class ActivateTaskUseCase( private val tasksRepository: TasksRepository ) { //이름없이 호출되는 함수 suspend operator fun invoke(task: Task) { wrapEspressoIdlingResource { tasksRepository.activateTask(task) } } }
0
Kotlin
0
0
6afa7e892090ab494e99df706ce4c82a1d92964f
591
architecture-samples
Apache License 2.0
domain/src/main/java/com/afterroot/watchdone/domain/interactors/UpdateDiscover.kt
thesandipv
255,834,235
false
{"Kotlin": 558462, "Shell": 1180}
/* * Copyright (C) 2020-2024 <NAME> * 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.afterroot.watchdone.domain.interactors import app.tivi.data.util.fetch import app.tivi.domain.Interactor import app.tivi.util.Logger import app.tivi.util.parallelForEach import com.afterroot.watchdone.base.CoroutineDispatchers import com.afterroot.watchdone.data.daos.DiscoverDao import com.afterroot.watchdone.data.model.MediaType import com.afterroot.watchdone.discover.DiscoverStore import com.afterroot.watchdone.media.MediaStore import com.afterroot.watchdone.media.MediaStoreRequest import javax.inject.Inject import kotlinx.coroutines.withContext import app.moviebase.tmdb.discover.DiscoverCategory as TmdbDiscoverCategory class UpdateDiscover @Inject constructor( private val discoverStore: DiscoverStore, private val discoverDao: DiscoverDao, private val mediaStore: MediaStore, private val dispatchers: CoroutineDispatchers, private val logger: Logger, ) : Interactor<UpdateDiscover.Params, Unit>() { data class Params( val mediaType: MediaType, val page: Int, val category: TmdbDiscoverCategory, val forceRefresh: Boolean = false, ) object Page { const val NEXT_PAGE = -1 const val REFRESH = -2 } override suspend fun doWork(params: Params) { withContext(dispatchers.io) { val page = when { params.page >= 0 -> params.page params.page == Page.NEXT_PAGE -> { val lastPage = discoverDao.getLastPage() if (lastPage != null) lastPage + 1 else 0 } else -> 1 } logger.d { "APPEND: Fetching page $page" } discoverStore.build().fetch( DiscoverStore.DiscoverStoreKey( page = page, mediaType = params.mediaType, category = params.category, ), params.forceRefresh, ).parallelForEach { mediaStore.fetch(MediaStoreRequest(it.mediaId, MediaType.SHOW)) } } } }
8
Kotlin
1
6
6772bfcc2ae1325df2d45365664d2ae012710873
2,479
watchdone
Apache License 2.0
media/audio/src/main/java/com/google/android/horologist/audio/SystemAudioRepository.kt
google
451,563,714
false
{"Kotlin": 3151160, "Shell": 5169, "Java": 708, "Starlark": 361}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.audio import android.content.Context import android.media.MediaRoute2Info import android.media.MediaRouter2 import android.media.MediaRouter2.RoutingController import android.media.RouteDiscoveryPreference import android.media.RoutingSessionInfo import android.os.Build import android.os.Build.VERSION_CODES import androidx.annotation.RequiresApi import androidx.mediarouter.media.MediaControlIntent import androidx.mediarouter.media.MediaRouteSelector import androidx.mediarouter.media.MediaRouter import androidx.mediarouter.media.MediaRouter.RouteInfo import com.google.android.horologist.audio.BluetoothSettings.launchBluetoothSettings import com.google.android.horologist.audio.OutputSwitcher.launchSystemMediaOutputSwitcherUi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow /** * Audio Repository for identifying and controlling available audio devices in a simple manner. */ public class SystemAudioRepository( private val application: Context, private val mediaRouter: MediaRouter, selector: MediaRouteSelector = MediaRouteSelector.Builder().build(), ) : AudioOutputRepository, VolumeRepository { private val _available = MutableStateFlow(mediaRouter.devices) private val _output = MutableStateFlow(mediaRouter.output) private val _volume = MutableStateFlow(mediaRouter.volume) private val watchSpeakerSuitabilityChecker: WatchSpeakerSuitabilityChecker? override val volumeState: StateFlow<VolumeState> get() = _volume override fun increaseVolume() { mediaRouter.selectedRoute.requestUpdateVolume(1) } override fun decreaseVolume() { mediaRouter.selectedRoute.requestUpdateVolume(-1) } override fun setVolume(volume: Int) { mediaRouter.selectedRoute.requestSetVolume(volume) } override val audioOutput: StateFlow<AudioOutput> get() = _output override val available: StateFlow<List<AudioOutput>> get() = _available private val callback = object : MediaRouter.Callback() { override fun onRouteAdded(router: MediaRouter, route: RouteInfo) { update() } override fun onRouteRemoved(router: MediaRouter, route: RouteInfo) { update() } override fun onRouteSelected(router: MediaRouter, route: RouteInfo, reason: Int) { update() } override fun onRouteChanged(router: MediaRouter, route: RouteInfo) { update() } override fun onRouteVolumeChanged(router: MediaRouter, route: RouteInfo) { mediaRouter.fixInconsistency() _volume.value = mediaRouter.volume } } init { if (Build.VERSION.SDK_INT >= VERSION_CODES.VANILLA_ICE_CREAM) { watchSpeakerSuitabilityChecker = WatchSpeakerSuitabilityChecker() watchSpeakerSuitabilityChecker.registerControllerCallback() } else { watchSpeakerSuitabilityChecker = null } mediaRouter.addCallback( MediaRouteSelector.Builder() .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO) .addSelector(selector) .build(), callback, ) update() } private fun update() { mediaRouter.fixInconsistency() _available.value = mediaRouter.devices.map { setWatchSpeakerPlayability(it) } _output.value = setWatchSpeakerPlayability(mediaRouter.output) } private fun setWatchSpeakerPlayability(audioOutput: AudioOutput): AudioOutput { if (watchSpeakerSuitabilityChecker == null || audioOutput.type != AudioOutput.TYPE_WATCH) { return audioOutput } return when { Build.VERSION.SDK_INT < VERSION_CODES.VANILLA_ICE_CREAM -> audioOutput watchSpeakerSuitabilityChecker.isWatchSpeakerSelected() -> AudioOutput.WatchSpeaker(audioOutput.id, audioOutput.name, true) else -> AudioOutput.WatchSpeaker(audioOutput.id, audioOutput.name, false) } } override fun close() { mediaRouter.removeCallback(callback) _output.value = AudioOutput.None _available.value = listOf() if (Build.VERSION.SDK_INT >= VERSION_CODES.VANILLA_ICE_CREAM) { watchSpeakerSuitabilityChecker?.unRegisterControllerCallback() } } override fun launchOutputSelection(closeOnConnect: Boolean) { if (!application.launchSystemMediaOutputSwitcherUi()) { application.launchBluetoothSettings(closeOnConnect) } } public companion object { public fun fromContext(application: Context): SystemAudioRepository { return SystemAudioRepository( application, MediaRouter.getInstance(application), ) } } @RequiresApi(VERSION_CODES.VANILLA_ICE_CREAM) private inner class WatchSpeakerSuitabilityChecker { private val mediaRouter = MediaRouter2.getInstance(application) private var wasWatchSpeakerSelectedPreviously = isWatchSpeakerSelected() private val routeDiscoveryPreference = RouteDiscoveryPreference.Builder(emptyList(), false).build() private val routeCallback = object : MediaRouter2.RouteCallback() {} private val controllerCallback = object : MediaRouter2.ControllerCallback() { public override fun onControllerUpdated(controller: RoutingController) { val isWatchSpeakerSelectedCurrently = isWatchSpeakerSelected() if (wasWatchSpeakerSelectedPreviously != isWatchSpeakerSelectedCurrently) { wasWatchSpeakerSelectedPreviously = isWatchSpeakerSelectedCurrently update() } } } fun registerControllerCallback() { // It is important to register a RouteDiscoveryPreference before registering ControllerCallback. mediaRouter.registerRouteCallback(application.mainExecutor, routeCallback, routeDiscoveryPreference) mediaRouter.registerControllerCallback(application.mainExecutor, controllerCallback) } fun unRegisterControllerCallback() { mediaRouter.unregisterControllerCallback(controllerCallback) mediaRouter.unregisterRouteCallback(routeCallback) } fun isWatchSpeakerSelected(): Boolean { val isWatchSpeakerSelected = mediaRouter.systemController.selectedRoutes.firstOrNull { it.type == MediaRoute2Info.TYPE_BUILTIN_SPEAKER } != null val transferReason = mediaRouter.systemController.routingSessionInfo.transferReason val isWatchSpeakerSelectedManually = transferReason == RoutingSessionInfo.TRANSFER_REASON_SYSTEM_REQUEST || transferReason == RoutingSessionInfo.TRANSFER_REASON_APP return isWatchSpeakerSelected && isWatchSpeakerSelectedManually && mediaRouter.systemController.wasTransferInitiatedBySelf() } } } private fun MediaRouter.fixInconsistency() { if (selectedRoute !in routes) { selectRoute(defaultRoute) } } private inline val MediaRouter.volume: VolumeState get() { return selectedRoute.volumeState } private inline val MediaRouter.output: AudioOutput get() { return selectedRoute.device } private inline val MediaRouter.devices: List<AudioOutput> get() { return routes.map { it.device } } private inline val RouteInfo.volumeState: VolumeState get() { return VolumeState(current = volume, max = volumeMax) } private inline val RouteInfo.device: AudioOutput get() { return when { isBluetooth -> { AudioOutput.BluetoothHeadset(id, name) } isDeviceSpeaker -> { AudioOutput.WatchSpeaker(id, name) } else -> { AudioOutput.Unknown(id, name) } } }
16
Kotlin
93
565
bde87db14f63338904550fc1827d0141ebe24d9a
8,672
horologist
Apache License 2.0
src/main/kotlin/com/coder/gateway/models/TokenSource.kt
coder
490,848,198
false
{"Kotlin": 315951}
package com.coder.gateway.models /** * Describes where a token came from. */ enum class TokenSource { CONFIG, // Pulled from the Coder CLI config. USER, // Input by the user. QUERY, // From the Gateway link as a query parameter. LAST_USED, // Last used token, either from storage or current run. }
33
Kotlin
10
15
be860cca9d571888d6309b55b2af36fc6509f0dd
330
jetbrains-coder
MIT License
rubik/rubik_picker/src/main/java/com/rubik/pick/PickWhat.kt
baidu
504,447,693
false
{"Kotlin": 607049, "Java": 37304}
package com.rubik.pick import com.ktnail.gradle.DependencyType import com.rubik.context.extra.Context import com.rubik.context.publication.LibType class PickWhat( val where: PickWhere, val items: Array<What> = arrayOf(), val forFlavor: String? = null, val dev: Boolean? = null ) { override fun toString(): String = "[$where] - [${items.joinToString(",")}] - [flavor:${forFlavor}] - [dev:${dev}]" val itemsOnlyLib = null == items.find { what -> what is What.Component } } sealed class What( val dependencyType: String ) { open fun condition(context: Context) = true class Component( dependencyType: String = DependencyType.IMPLEMENTATION ) : What(dependencyType) { override fun toString() = "$dependencyType COMPONENT" } class Lib( dependencyType: String = DependencyType.IMPLEMENTATION, val type: String ) : What(dependencyType) { override fun condition(context: Context) = if (!context.enableProvideRoute) false else if (type == LibType.ORIGINAL_VALUE) context.source.publishOriginalValue else true override fun toString() = "$dependencyType LIB-${type}" } } fun shellPackingComponentWhat( forFlavor: String?, where: PickWhere ) = PickWhat( where, arrayOf(What.Component()), forFlavor = forFlavor ) fun shellPackingLibWhat() = PickWhat( ByAll(), arrayOf( What.Lib(type = LibType.CONTEXT), What.Lib(dependencyType = DependencyType.COMPILE_ONLY, type = LibType.ORIGINAL_VALUE) ) ) fun contextDependLibWhat( uri: String, dev: Boolean? ) = PickWhat( ByUri(uri), arrayOf( What.Lib(type = LibType.CONTEXT), What.Lib(dependencyType = DependencyType.COMPILE_ONLY, type = LibType.ORIGINAL_VALUE) ), dev = dev ) fun contextDependLibCompileOnlyWhat( uri: String, dev: Boolean? ) = PickWhat( ByUri(uri), arrayOf( What.Lib(dependencyType = DependencyType.COMPILE_ONLY, type = LibType.CONTEXT), What.Lib(dependencyType = DependencyType.COMPILE_ONLY, type = LibType.ORIGINAL_VALUE) ), dev = dev ) fun contextDependComponentWhat( uri: String, forFlavor: String? ) = PickWhat( ByUri(uri), arrayOf(What.Component()), forFlavor = forFlavor ) fun contextDependComponentCompileOnlyWhat( uri: String, forFlavor: String? ) = PickWhat( ByUri(uri), arrayOf(What.Component(dependencyType = DependencyType.COMPILE_ONLY)), forFlavor = forFlavor )
1
Kotlin
7
153
065ba8f4652b39ff558a5e3f18b9893e2cf9bd25
2,593
Rubik
Apache License 2.0
domain/src/main/java/com/flexcode/domain/utils/ResultWrapper.kt
Felix-Kariuki
755,941,258
false
{"Kotlin": 145949}
/** * * Copyright (c) 2024 <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 com.flexcode.githubgraphql.domain.utils /** * A generic class representing the state of an operation with optional data, error, and loading indicators. * @property data The data result of the operation. * @property errorMessage The error that occurred during the operation. */ sealed class ResultWrapper<T>(val data: T? = null, val errorMessage: String? = null) { /** * Creates a success state with the specified data. * @param data The data result. * @return A Resource instance representing the success state with data. */ class Success<T>(data: T) : ResultWrapper<T>(data) /** * Creates an error state with the specified error. * @param error The error that occurred. * @return A Resource instance representing the error state with the error and null data */ class Error<T>(error: String, data: T? = null) : ResultWrapper<T>(data, error) /** * Creates a loading state. * @return A Resource instance representing the loading state. */ class Loading<T>(data: T? = null) : ResultWrapper<T>(data) } data class ErrorResponse( val message: String, )
1
Kotlin
0
3
bc204d751626d21520f98f7b64886200735b2ef1
2,267
GraphQlGithub
MIT License
adaptive-lib-auto/src/jvmTest/kotlin/fun/adaptive/auto/integration/AutoTestService.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2231374, "Java": 23999, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
package `fun`.adaptive.auto.integration import `fun`.adaptive.adat.toArray import `fun`.adaptive.auto.api.originFile import `fun`.adaptive.auto.api.originFolder import `fun`.adaptive.auto.api.originInstance import `fun`.adaptive.auto.api.originList import `fun`.adaptive.auto.api.originListPoly import `fun`.adaptive.auto.backend.AutoWorker import `fun`.adaptive.auto.backend.TestData import `fun`.adaptive.auto.internal.backend.BackendContext import `fun`.adaptive.auto.internal.backend.PropertyBackend import `fun`.adaptive.auto.internal.frontend.AdatClassFrontend import `fun`.adaptive.auto.model.AutoConnectInfo import `fun`.adaptive.auto.model.AutoHandle import `fun`.adaptive.auto.model.LamportTimestamp import `fun`.adaptive.backend.builtin.ServiceImpl import `fun`.adaptive.backend.builtin.worker import `fun`.adaptive.log.getLogger import `fun`.adaptive.utility.UUID import `fun`.adaptive.utility.testPath import `fun`.adaptive.wireformat.api.Json import `fun`.adaptive.wireformat.api.Proto import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem import kotlin.getValue class AutoTestService : AutoTestApi, ServiceImpl<AutoTestService> { val worker by worker<AutoWorker>() override suspend fun manual(): AutoConnectInfo { val logger = getLogger("logger") val context = BackendContext( AutoHandle(UUID(), 1), worker.scope, logger, Proto, TestData.adatMetadata, TestData.adatWireFormat, LamportTimestamp(1, 1) ) val originBackend = PropertyBackend( context, LamportTimestamp(1, 1), null, TestData(12, "a").toArray() ) val originFrontend = AdatClassFrontend( originBackend, TestData.adatWireFormat, TestData(12, "a"), null, null, null ) originBackend.frontEnd = originFrontend worker.register(originBackend) return AutoConnectInfo( context.handle, context.time, AutoHandle(context.handle.globalId, 2), ) } override suspend fun instance(): AutoConnectInfo { val origin = originInstance(worker, TestData(12, "a"), serviceContext) return origin.connectInfo() } override suspend fun list(): AutoConnectInfo { return originList(worker, TestData, serviceContext).connectInfo() } override suspend fun polyList(): AutoConnectInfo { return originListPoly(worker, TestData, serviceContext).connectInfo() } override suspend fun file(): AutoConnectInfo { val path = Path(testPath, "AutoTestService.testInstanceWithFile.json") SystemFileSystem.delete(path, mustExist = false) return originFile(worker, TestData, path, TestData(12, "a"), Json, serviceContext).connectInfo() } override suspend fun folder(folderName : String): AutoConnectInfo { val path = Path(testPath, folderName) return originFolder( worker, TestData, Json, path, { itemId,_ -> "${itemId.peerId}.${itemId.timestamp}.json" }, serviceContext ).connectInfo() } }
28
Kotlin
0
3
c0fd95c9654bee332c20f8f9373f1dae9132cf6b
3,261
adaptive
Apache License 2.0
samples/stopwatch-compose/src/main/java/com/instacart/formula/compose/stopwatch/StopwatchActivity.kt
instacart
171,923,573
false
{"Kotlin": 565903, "Shell": 1203, "Ruby": 256}
package com.instacart.formula.compose.stopwatch import android.os.Bundle import com.instacart.formula.android.FormulaAppCompatActivity import com.instacart.formula.android.FormulaFragment class StopwatchActivity : FormulaAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.stopwatch_activity) if (savedInstanceState == null) { val key = StopwatchKey() supportFragmentManager.beginTransaction() .add(R.id.activity_content, FormulaFragment.newInstance(key), key.tag) .commit() } } }
7
Kotlin
14
151
26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff
661
formula
BSD 3-Clause Clear License
app/src/main/java/com/example/boombox/data/network/VideosApi.kt
rajatsangrame
521,908,183
false
null
package com.example.boombox.data.network import com.example.boombox.data.model.TrackResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface VideosApi { @GET("search") suspend fun searchVideos( @Query("query") query: String, @Query("per_page") page: Int ): Response<TrackResponse> }
0
Kotlin
0
0
f68761888cbac8df0d5d4a585daf528443425121
342
boombox
Apache License 2.0
app/src/main/java/eu/caraus/appsflastfm/services/youtube/busevents/service/PlayingUpdate.kt
alexandrucaraus
144,028,779
false
{"Kotlin": 202701}
package eu.caraus.appsflastfm.services.youtube.busevents.service import eu.caraus.appsflastfm.common.bus.events.service.ServiceEvent import eu.caraus.appsflastfm.services.youtube.model.youtube.YouTubeVideo class PlayingUpdate(val youTubeVideo: YouTubeVideo) : ServiceEvent()
0
Kotlin
0
0
fb9b4a218fa4c09b23b253eb75ee62456b4b47ff
276
ShowCase-AppsFactoryLastFmMvp
MIT License
data/src/main/java/com/goms/data/datasource/outing/OutingDataSource.kt
team-haribo
614,646,527
false
{"Kotlin": 195760}
package com.goms.data.datasource.outing import com.goms.data.model.outing.OutingCountResponse import com.goms.data.model.user.UserResponse import kotlinx.coroutines.flow.Flow import retrofit2.Response import java.util.UUID interface OutingDataSource { suspend fun outing(outingUUID: UUID): Flow<Response<Unit>> suspend fun getOutingList(): Flow<List<UserResponse>> suspend fun getOutingCount(): Flow<OutingCountResponse> }
4
Kotlin
0
7
c2593172e93f1732d39e4c3d850d68b6e14df0f7
438
GOMS-Android
MIT License
Matcheap/app/src/main/java/com/sandy/seoul_matcheap/util/helper/DataHelper.kt
SANDY-9
677,761,441
false
null
package com.sandy.seoul_matcheap.util.helper import android.content.Context import java.text.SimpleDateFormat import java.time.Duration import java.time.LocalDate import java.time.LocalTime import java.time.format.DateTimeFormatter import java.time.format.TextStyle import java.util.* import java.util.regex.Pattern import kotlin.math.* /** * @author SANDY * @email <EMAIL> * @created 2023-04-05 * @desc */ object DataHelper { fun downloadStoreData(context: Context) = context.resources.assets .open("store.txt") .bufferedReader() .readLines() fun downloadPolygonData(context: Context) = context.resources.assets .open("polygon.txt") .bufferedReader() .readLines() private val r = 6372.8 * 1000 fun calculateDistance(curLat: Double, curLng: Double, lat: Double, lng : Double) : Double { val a = 2 * asin( sqrt( sin(Math.toRadians(lat - curLat) / 2).pow(2.0) + sin(Math.toRadians(lng - curLng) / 2).pow(2.0) * cos(Math.toRadians(curLat)) * cos(Math.toRadians(lat)) ) ) return r * a / 1000 } private val timeFormat = SimpleDateFormat("yyyyMMdd-HHmm") private val halfTimeFormat = SimpleDateFormat("yyyyMMdd-HH30") private const val ONE_HOUR = 3600000 fun getBaseTime() = run { val time = LocalTime.now() val currentTime = System.currentTimeMillis() if(time.minute < 30) halfTimeFormat.format(currentTime - ONE_HOUR).split("-") else timeFormat.format(currentTime).split("-") } private val dateFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd ") fun getDate() : String { val date = LocalDate.now() return date.format(dateFormatter) + date.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.KOREA) } private val formatter = DateTimeFormatter.ofPattern("yyyy.M.d.") private val convertFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd") fun convertDateFormat(date: String) : String { return try { val localDate = LocalDate.parse(date.replace(" ", ""), formatter) localDate.format(convertFormatter) } catch (e: Exception) { date } } private const val DEGRAD = Math.PI / 180.0// 지구 반경(km) private const val GRID = 5.0 // 격자 간격(km) private const val RE = 6371.00877 / GRID private const val SLAT1 = 30.0 * DEGRAD// 투영 위도1(degree) private const val SLAT2 = 60.0 * DEGRAD// 투영 위도2(degree) private const val OLON = 126.0 * DEGRAD // 기준점 경도(degree) private const val OLAT = 38.0 * DEGRAD // 기준점 위도(degree) private const val XO = 43.0 // 기준점 X좌표(GRID) private const val YO = 136.0 // 기1준점 Y좌표 private val sn = ln(cos(SLAT1) / cos(SLAT2)) / ln( tan(Math.PI * 0.25 + SLAT2 * 0.5) / tan(Math.PI * 0.25 + SLAT1 * 0.5) ) private val sf = (tan(Math.PI * 0.25 + SLAT1 * 0.5)).pow(sn) * cos(SLAT1) / sn private val ro = RE * sf / (tan(Math.PI * 0.25 + OLAT * 0.5)).pow(sn) fun convertToGrid(lat: Double, lng: Double) = run { val ra = RE * sf / (tan(Math.PI * 0.25 + lat * DEGRAD * 0.5)).pow(sn) var theta = lng * DEGRAD - OLON if (theta > Math.PI) theta -= 2.0 * Math.PI if (theta < -Math.PI) theta += 2.0 * Math.PI theta *= sn val nx = floor(ra * sin(theta) + XO + 0.5).toInt() val ny = floor(ro - ra * cos(theta) + YO + 0.5).toInt() nx to ny } fun calculateSensoryTemperature(t: Double, v: Double) = if(v <= 0) t else round((13.12 + 0.6215 * t - 11.37 * v.pow(0.16) + 0.3965 * v.pow(0.16) * t) * 10) / 10 private const val TIME_24 = 86400 fun calculateDuration(hour: Int, min: Int): Long { val duration = Duration.between( LocalTime.now(), LocalTime.of(hour, min, 0) ).seconds return if(duration < 0) duration + TIME_24 else duration } //!-- Autocomplete settings fun removeSpace(str: String) = str.trim().replace(" ", "").trim() fun getStartIndex( input: String, auto: String, removedSpaceInput: String, removedSpaceAuto: String ) = auto.run { when { contains(input) -> indexOf(input) contains(removedSpaceInput) -> indexOf(removedSpaceInput) else -> getOriginalIndex( auto, removedSpaceAuto, removedSpaceAuto.indexOf(removedSpaceInput) ) } } fun getEndIndex( input: String, auto: String, removedSpaceInput: String, removedSpaceAuto: String, startIndex: Int ) = auto.run { when { contains(input) -> startIndex + input.length contains(removedSpaceInput) -> startIndex + removedSpaceInput.length else -> getOriginalIndex( auto, removedSpaceAuto, removedSpaceAuto.indexOf(removedSpaceInput) + removedSpaceInput.length - 1 ) + 1 } } private fun getOriginalIndex(auto: String, removedSpaceAuto: String, index: Int): Int { val targetChar = removedSpaceAuto[index] val count = auto.count { it == targetChar } // if multiple targetChar exist, original index is the smallest index among them that is more than index. // because length of targetChar is 1, have used Pattern, Matcher Class(Regular Expression). val originalIndex = if(count > 1) { val matcher = Pattern.compile(targetChar.toString()).matcher(auto) mutableListOf<Int>().apply { while (matcher.find()) { if(matcher.start() > index) { add(matcher.start()) break } } }.first() } else auto.indexOf(targetChar) val spaceCount = auto.substring(0, originalIndex).count { it.isWhitespace() } return index + spaceCount } }
0
Kotlin
0
0
6ff61f56e481a5fce9ef10ecafbc5132bdc2991c
6,097
Project_SeoulMatcheap2.0
Apache License 2.0
valuedef-common/src/main/java/com/bennyhuo/kotlin/valuedef/common/error/ErrorKeys.kt
bennyhuo
439,819,685
false
null
package com.bennyhuo.kotlin.valuedef.common.error /** * Created by benny at 2022/1/16 8:43 AM. */ object ErrorKeys { const val KEY_VALUE_MISMATCH = "inspection.valuedef.error.value.mismatch" const val KEY_TYPE_CONFLICTS = "inspection.valuedef.error.type.conflicts" const val KEY_DEF_CONFLICTS = "inspection.valuedef.error.def.conflicts" const val KEY_TYPE_MISMATCH = "inspection.valuedef.error.type.mismatch" }
0
Kotlin
0
4
5b5ebfe900e25372d3c076b24dfb175945866a38
429
KotlinValueDef
MIT License
valuedef-common/src/main/java/com/bennyhuo/kotlin/valuedef/common/error/ErrorKeys.kt
bennyhuo
439,819,685
false
null
package com.bennyhuo.kotlin.valuedef.common.error /** * Created by benny at 2022/1/16 8:43 AM. */ object ErrorKeys { const val KEY_VALUE_MISMATCH = "inspection.valuedef.error.value.mismatch" const val KEY_TYPE_CONFLICTS = "inspection.valuedef.error.type.conflicts" const val KEY_DEF_CONFLICTS = "inspection.valuedef.error.def.conflicts" const val KEY_TYPE_MISMATCH = "inspection.valuedef.error.type.mismatch" }
0
Kotlin
0
4
5b5ebfe900e25372d3c076b24dfb175945866a38
429
KotlinValueDef
MIT License
toll-device-app/wallet/app/src/main/java/org/drdgvhbh/android/wallet/SetAllowanceViewModelFactory.kt
Azure-Samples
181,102,598
false
null
package org.drdgvhbh.android.wallet import android.app.Activity import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentActivity import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.web3j.crypto.Credentials import org.web3j.protocol.Web3j import java.math.BigInteger class SetAllowanceViewModelFactory( private val activity: FragmentActivity, private val allowanceRequestor: String, private val credentials: Credentials, private val web3j: Web3j, private val requestAmount: BigInteger, private val contractAddress: String) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(SetAllowanceViewModel::class.java)) { return SetAllowanceViewModel( activity = activity, allowanceRequestor = allowanceRequestor, credentials = credentials, web3j = web3j, requestAmountBI = requestAmount, contractAddress = contractAddress ) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
3
JavaScript
31
15
bf3e044ad72b9fc58514f0c210f2484d55f83e03
1,326
bc-community-samples
MIT License
browser-kotlin/src/jsMain/kotlin/web/media/key/MediaKeySession.events.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.media.key import web.events.Event import web.events.EventInstance /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaKeySession/keystatuseschange_event) */ inline val <C : MediaKeySession> C.keyStatusesChangeEvent: EventInstance<Event, C, C> get() = EventInstance(this, Event.KEY_STATUSES_CHANGE) /** * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaKeySession/message_event) */ inline val <C : MediaKeySession> C.messageEvent: EventInstance<MediaKeyMessageEvent, C, C> get() = EventInstance(this, MediaKeyMessageEvent.MESSAGE)
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
636
types-kotlin
Apache License 2.0
src/main/kotlin/nl/chimpgamer/networkmanager/extensions/autoban/configuration/Settings.kt
ChimpGamer
189,884,562
false
{"Kotlin": 7784}
package nl.chimpgamer.networkmanager.extensions.autoban.configuration import dev.dejvokep.boostedyaml.YamlDocument import dev.dejvokep.boostedyaml.settings.dumper.DumperSettings import dev.dejvokep.boostedyaml.settings.general.GeneralSettings import dev.dejvokep.boostedyaml.settings.loader.LoaderSettings import dev.dejvokep.boostedyaml.settings.updater.UpdaterSettings import nl.chimpgamer.networkmanager.api.models.punishments.Punishment import nl.chimpgamer.networkmanager.api.utils.TimeUtils import nl.chimpgamer.networkmanager.api.values.Message import nl.chimpgamer.networkmanager.extensions.autoban.AutoBan import nl.chimpgamer.networkmanager.extensions.autoban.models.PunishmentAction import java.io.IOException import java.util.logging.Level class Settings(private val autoBan: AutoBan) { private val config: YamlDocument val punishmentActions = HashSet<PunishmentAction>() init { val file = autoBan.dataFolder.resolve("settings.yml") val inputStream = autoBan.getResource("settings.yml") val generalSettings = GeneralSettings.builder().setUseDefaults(false).build() val loaderSettings = LoaderSettings.builder().setAutoUpdate(false).build() config = if (inputStream != null) { YamlDocument.create(file, inputStream, generalSettings, loaderSettings, DumperSettings.DEFAULT, UpdaterSettings.DEFAULT) } else { YamlDocument.create(file, generalSettings, loaderSettings, DumperSettings.DEFAULT, UpdaterSettings.DEFAULT) } } fun load() { val actionsSection = config.getSection("actions") for (onActionTypeStr in actionsSection.getRoutesAsStrings(false)) { val onActionType = try { Punishment.Type.valueOf(onActionTypeStr) } catch (ex: IllegalArgumentException) { autoBan.logger.log(Level.WARNING, "Action $onActionTypeStr has invalid onActionType: $onActionTypeStr", ex) continue } val actionSection = actionsSection.getSection(onActionTypeStr) for (countKey in actionSection.getRoutesAsStrings(false)) { val count = try { countKey.toInt() } catch (ex: NumberFormatException) { autoBan.logger.warning("Action $onActionTypeStr has invalid count: $countKey") continue } val action = actionSection.getString("$countKey.action") if (action == null) { autoBan.logger.warning("Action $onActionTypeStr.$countKey has no action.") continue } val punishmentType = try { Punishment.Type.valueOf(action) } catch (ex: IllegalArgumentException) { autoBan.logger.log(Level.WARNING, "Action $onActionTypeStr.$countKey has invalid actionType: $action", ex) continue } var duration = -1L val durationStr = actionSection.getString("$countKey.duration") val reason = actionSection.getString("$countKey.reason", autoBan.networkManager.getMessage(Message.PUNISHMENT_NO_REASON)) if (durationStr != null && punishmentType.isTemp) { try { duration = TimeUtils.toMilliSec(durationStr) } catch (ex: IllegalArgumentException) { autoBan.logger.log(Level.WARNING, "Action $onActionTypeStr.$countKey has invalid duration: $duration", ex) continue } } punishmentActions.add(PunishmentAction(onActionType, count, punishmentType, duration, reason)) } } } fun reload() { try { config.reload() punishmentActions.clear() load() } catch (ex: IOException) { autoBan.logger.log(Level.SEVERE, "Something went wrong trying to reload the settings.yml configuration file", ex) } } }
0
Kotlin
0
2
bae39cebb4bc054dacdce90b211d0bbee1144faa
4,108
AutoBan-Extension
Apache License 2.0
Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCExportImpl.kt
juliuskunze
116,136,849
true
{"Kotlin": 4056983, "C++": 754448, "C": 134581, "Groovy": 56615, "Objective-C++": 36230, "JavaScript": 7772, "Shell": 6465, "Batchfile": 6254, "Python": 4775, "Objective-C": 2079, "Pascal": 1698, "Java": 782, "HTML": 185}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlinx.cinterop import konan.internal.ExportForCppRuntime // TODO: it it actually not related to cinterop. @ExportTypeInfo("theNSArrayListTypeInfo") internal class NSArrayList : AbstractList<Any?> { // FIXME: override methods of Any. @konan.internal.ExportForCppRuntime("Kotlin_NSArrayList_constructor") constructor() : super() override val size: Int get() = getSize() @SymbolName("Kotlin_NSArrayList_getSize") private external fun getSize(): Int @SymbolName("Kotlin_NSArrayList_getElement") external override fun get(index: Int): Any? } @ExportForCppRuntime private fun Kotlin_List_get(list: List<*>, index: Int): Any? = list.get(index) @ExportForCppRuntime private fun Kotlin_List_getSize(list: List<*>): Int = list.size
0
Kotlin
0
1
2e07b3f52f99b51d353a8c0e53bdf9fff86988e0
1,375
kotlin-native
Apache License 2.0
data/src/commonMain/kotlin/com/inkapplications/data/transformer/StringTransformations.kt
InkApplications
276,733,654
false
{"Kotlin": 126744}
package com.inkapplications.data.transformer object StringTransformations { val StringToInt: DataTransformer<String, Int> = SimpleTransformer( transformer = String::toInt, reverseTransformer = Int::toString, ) val StringToLong: DataTransformer<String, Long> = SimpleTransformer( transformer = String::toLong, reverseTransformer = Long::toString, ) val StringToFloat: DataTransformer<String, Float> = SimpleTransformer( transformer = String::toFloat, reverseTransformer = { it.toString().let { if ('.' !in it) { "$it.0" } else it } } ) val StringToDouble: DataTransformer<String, Double> = SimpleTransformer( transformer = String::toDouble, reverseTransformer = { it.toString().let { if ('.' !in it) { "$it.0" } else it } }, ) val StringToBoolean: DataTransformer<String, Boolean> = SimpleTransformer( transformer = String::toBoolean, reverseTransformer = Boolean::toString, ) val Trimming: DataTransformer<String, String> = SimpleTransformer( transformer = String::trim, reverseTransformer = String::trim, ) val EmptyStringToNull: DataTransformer<String, String?> = SimpleTransformer( transformer = { it.ifEmpty { null } }, reverseTransformer = { it ?: "" }, ) val None: DataTransformer<String, String> = NoTransformation() }
0
Kotlin
2
1
e4b4a171334256c1f90d56e66ab15094d8781cd3
1,406
Watermelon
MIT License
web-front/src/main/kotlin/com/isystk/sample/web/front/service/PasswordResetService.kt
isystk
328,037,305
false
{"Kotlin": 462354, "TypeScript": 88591, "HTML": 77276, "SCSS": 24557, "FreeMarker": 21801, "JavaScript": 5293, "Shell": 3607, "Dockerfile": 1581, "CSS": 942}
package com.isystk.sample.web.front.service import com.google.common.collect.Maps import com.isystk.sample.common.dto.mail.MailEntryRegistTemporary import com.isystk.sample.common.exception.NoDataFoundException import com.isystk.sample.common.helper.SendMailHelper import com.isystk.sample.common.service.BaseTransactionalService import com.isystk.sample.common.util.DateUtils import com.isystk.sample.common.values.MailTemplateDiv import com.isystk.sample.domain.dao.PasswordResetDao import com.isystk.sample.domain.dto.PasswordResetCriteria import com.isystk.sample.domain.dto.UserCriteria import com.isystk.sample.domain.entity.PasswordReset import com.isystk.sample.domain.entity.User import com.isystk.sample.domain.repository.MailTemplateRepository import com.isystk.sample.domain.repository.UserRepository import org.apache.commons.lang3.RandomStringUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service @Service class PasswordResetService : BaseTransactionalService() { @Value("\${spring.mail.properties.mail.from}") var fromAddress: String? = null @Value("\${server.address}") var domain: String? = null @Autowired var passwordResetDao: PasswordResetDao? = null @Autowired var mailTemplateRepository: MailTemplateRepository? = null @Autowired var userRepository: UserRepository? = null @Autowired var sendMailHelper: SendMailHelper? = null /** * パスワード変更ワンタイムパス登録 * * @param email */ fun registOnetimePass(email: String?) { // ユーザー情報を取得する val criteria = UserCriteria() criteria.emailEq = email criteria.deleteFlgFalse = true val user: User = userRepository!!.findOne(criteria) ?: throw NoDataFoundException("email=$email のデータが見つかりません。") // パスワード変更ワンタイムパスを登録する(Delete→Insert) run { val passwordResetCriteria = PasswordResetCriteria() passwordResetCriteria.emailEq = user.email val passwordReset = passwordResetDao!!.findOne(passwordResetCriteria) if (passwordReset !== null) { passwordResetDao!!.delete(passwordReset) } } val passwordReset = PasswordReset() passwordReset.email = user.email val onetimeKey = generateOnetimeKey() passwordReset.token = onetimeKey passwordReset.createdAt = DateUtils.now passwordReset.updatedAt = DateUtils.now passwordReset.deleteFlg = false passwordResetDao!!.insert(passwordReset) // 新パスワード設定画面のお知らせメールを送信する val mailTemplate = mailTemplateRepository!!.getMailTemplate(MailTemplateDiv.ENTRY_REMIND) val subject = mailTemplate.title val templateBody = mailTemplate.text val dto = MailEntryRegistTemporary() dto.userName = user.name dto.domain = domain dto.onetimeKey = onetimeKey val objects: MutableMap<String, Any> = Maps.newHashMap() objects["dto"] = dto val body = sendMailHelper!!.getMailBody(templateBody, objects) sendMailHelper!!.sendMail(fromAddress, user.email, subject, body) } /** * パスワード変更 * * @param onetimeKey * @param password */ fun changePassword(onetimeKey: String, password: String?) { // ワンタイムキーからユーザーIDを取得する val criteria = PasswordResetCriteria() criteria.tokenEq = onetimeKey val passwordReset = passwordResetDao!!.findOne(criteria) ?: throw NoDataFoundException("指定されたワンタイムキーが見つかりません。[onetimeKey=$onetimeKey]") // 承認期限オーバー if (DateUtils.beforeNow(DateUtils.addMinutes(passwordReset.createdAt!!, 60))) { throw NoDataFoundException("指定されたワンタイムキーは期限を過ぎています。[onetimeKey=$onetimeKey]") } // ユーザー情報を取得する val userCriteria = UserCriteria() userCriteria.emailEq = passwordReset.email val user: User = userRepository!!.findOne(userCriteria) ?: throw NoDataFoundException("email=" + passwordReset.email + " のデータが見つかりません。") // パスワードを変更する user.password = <PASSWORD> userRepository!!.update(user) // ワンタイムキーを削除 passwordResetDao!!.delete(passwordReset) } /** * ワンタイムキー生成 * * @return 生成されたワンタイムキー */ private fun generateOnetimeKey(): String { // ランダムな文字列を生成する。 return RandomStringUtils.randomAlphanumeric(32) } }
0
Kotlin
0
2
2e4e0c62af22c05403e5d3452ba08eb09c05a7f1
4,512
kotlin-springboot-boilerplate
MIT License
presentation/src/commonMain/kotlin/com/chrynan/chat/resources/DrawableIDs.kt
chRyNaN
206,982,352
false
null
package com.chrynan.chat.resources interface DrawableIDs { val bgAttachmentBadge: ResourceID val bgLauncher: ResourceID val icBadgeRemove: ResourceID val icBottomNavbarConversation: ResourceID val icBottomNavbarFeed: ResourceID val icBottomNavbarSettings: ResourceID val icMessageEditorSend: ResourceID val icReply: ResourceID val icSent: ResourceID val icToolbarBack: ResourceID val icUserCircle: ResourceID }
0
Kotlin
0
3
8269e4bcecad6ba4ef10e211ca4cb52e1cdff4b8
466
Chat
Apache License 2.0
tests/src/main/kotlin/se/ansman/kotshi/TestFactory.kt
ansman
95,685,398
false
{"Kotlin": 392472, "Shell": 246}
package se.ansman.kotshi import com.squareup.moshi.JsonAdapter @OptIn(ExperimentalStdlibApi::class) @KotshiJsonAdapterFactory object TestFactory : JsonAdapter.Factory by KotshiTestFactory
4
Kotlin
43
759
524311f039c15a4ca7b08bfcb27dbde1b2c2b6a0
189
kotshi
Apache License 2.0
wireframe-test/src/main/java/ru/nsu/e/shelbogashev/wireframe/bsplineeditor/BSpline.kt
EricShelbogashev
745,928,535
false
{"Kotlin": 101898, "Java": 224}
package ru.nsu.e.shelbogashev.wireframe.bsplineeditor import ru.nsu.e.shelbogashev.wireframe.utils.Matrix import ru.nsu.e.shelbogashev.wireframe.utils.Point2D import ru.nsu.e.shelbogashev.wireframe.utils.Settings /** * Класс для работы с B-сплайнами. */ class BSpline { private val splineMatrix = Matrix( arrayOf( doubleArrayOf(-1.0 / 6, 3.0 / 6, -3.0 / 6, 1.0 / 6), doubleArrayOf(3.0 / 6, -6.0 / 6, 3.0 / 6, 0.0), doubleArrayOf(-3.0 / 6, 0.0, 3.0 / 6, 0.0), doubleArrayOf(1.0 / 6, 4.0 / 6, 1.0 / 6, 0.0) ) ) /** * Точки, которые будут использоваться для приближения B-сплайна. */ private val anchorPoints: MutableList<Point2D> = ArrayList() /** * Точки, которые будут аппроксимировать часть B-сплайна. */ var splinePoints: ArrayList<Point2D>? = null private set /** * Добавляет якорную точку для аппроксимации B-сплайна. * * @param point Точка, которую необходимо добавить в качестве якорной точки. */ fun addAnchorPoint(point: Point2D) { anchorPoints.add(point) createBSpline() } /** * Удаляет последнюю добавленную якорную точку. */ fun deleteAnchorPoint() { if (anchorPoints.isNotEmpty()) { anchorPoints.removeAt(anchorPoints.size - 1) createBSpline() } } /** * Создает B-сплайн на основе заданных якорных точек. */ fun createBSpline() { splinePoints = ArrayList() // каждый раз создаем новый массив точек val anchorPointsNum = anchorPoints.size val step = 1.0 / Settings.segmentsNum // шаг между каждой частью сегмента [0, 1] var x: Double var y: Double if (anchorPointsNum < 4) return for (i in 1 until anchorPointsNum - 2) { val xCoords = doubleArrayOf( anchorPoints[i - 1].x, anchorPoints[i].x, anchorPoints[i + 1].x, anchorPoints[i + 2].x ) val yCoords = doubleArrayOf( anchorPoints[i - 1].y, anchorPoints[i].y, anchorPoints[i + 1].y, anchorPoints[i + 2].y ) val xVector = splineMatrix.multiplyMatrixVector(xCoords) val yVector = splineMatrix.multiplyMatrixVector(yCoords) var t: Double for (k in 0..Settings.segmentsNum) { t = k * step x = t * t * t * xVector[0] + t * t * xVector[1] + t * xVector[2] + xVector[3] y = t * t * t * yVector[0] + t * t * yVector[1] + t * yVector[2] + yVector[3] splinePoints!!.add(Point2D(x, y)) } } } /** * Возвращает список якорных точек. * * @return Список якорных точек. */ fun getAnchorPoints(): List<Point2D> { return this.anchorPoints } }
0
Kotlin
0
0
6881eb773624fa420425983e2a4b73cb76ce5f17
2,954
engineering-computer-graphics
MIT License
app/src/main/java/io/github/takusan23/akaridroid/ui/bottomsheet/data/BottomSheetResultData.kt
takusan23
584,131,815
false
null
package io.github.takusan23.akaridroid.ui.bottomsheet.data import io.github.takusan23.akaridroid.data.AudioAssetData import io.github.takusan23.akaridroid.data.CanvasElementData import io.github.takusan23.akaridroid.ui.bottomsheet.VideoEditMenuBottomSheetMenu /** [BottomSheetState]で返す値 */ sealed class BottomSheetResultData { /** 要素の編集画面から戻ってきた際に呼ばれる */ data class CanvasElementResult(val canvasElementData: CanvasElementData) : BottomSheetResultData() /** 要素を削除してほしい際に呼ばれる */ data class CanvasElementDeleteResult(val deleteElementData: CanvasElementData) : BottomSheetResultData() /** 動画編集画面のメニュー選択時 */ data class VideoEditMenuResult(val menu: VideoEditMenuBottomSheetMenu) : BottomSheetResultData() /** 音声素材の編集画面から戻ってきた際に呼ばれる */ data class AudioAssetResult(val audioAssetData: AudioAssetData) : BottomSheetResultData() /** 音声素材を削除してほしい際に呼ばれる */ data class AudioAssetDeleteResult(val audioAssetData: AudioAssetData) : BottomSheetResultData() }
0
Kotlin
0
0
8cf425ee3d739dd8be05033b020867c195569c78
992
AkariDroid
Apache License 2.0
src/main/kotlin/br/com/alura/bytebank/main.kt
GiovanniMoratto
396,122,536
false
null
package br.com.alura.bytebank import br.com.alura.bytebank.modelo.Cliente import br.com.alura.bytebank.modelo.ContaPoupanca import br.com.alura.bytebank.modelo.Endereco import br.com.alura.bytebank.teste.testaHOF /** *@Author giovanni.moratto */ fun main() { testaHOF() } fun testaRun() { val taxaAnual = 0.05 val taxaMensal = taxaAnual / 12 println("taxa mensal $taxaMensal") val contaPoupanca = ContaPoupanca(Cliente(nome = "Alex", cpf = "111.111.111-11", senha = <PASSWORD>), 1000) contaPoupanca.run { deposita(1000.0) saldo * taxaMensal }.let { rendimentoMensal -> println("rendimento mensal $rendimentoMensal") } val rendimentoAnual = run { var saldo = contaPoupanca.saldo repeat(12) { saldo += saldo * taxaMensal } saldo } println("simulação rendimento anual $rendimentoAnual") } fun testaWith() { with(Endereco()) { logradouro = "rua vergueiro" numero = 3185 bairro = "<NAME>" cidade = "São Paulo" estado = "SP" cep = "02310-063" complemento = "Apartamento" completo() }.let { enderecoCompleto: String -> println(enderecoCompleto) } }
0
Kotlin
0
0
d406d46965c253f65035d45bc2119f72a33057a9
1,247
kotlin-paradigma-funcional
MIT License
backend/api/src/main/kotlin/io/tolgee/hateoas/machineTranslation/StreamedSuggestionItem.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.hateoas.machineTranslation import io.tolgee.constants.Message import io.tolgee.constants.MtServiceType class StreamedSuggestionItem( val serviceType: MtServiceType, val result: TranslationItemModel?, val errorMessage: Message? = null, val errorParams: List<Any?>? = null, val errorException: String? = null, )
170
TypeScript
188
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
340
tolgee-platform
Apache License 2.0
module/feature/home/src/commonMain/kotlin/org.starter.project.feature/home/component/article/ArticleListItem.kt
s-iwasaki-b
868,326,943
false
{"Kotlin": 58799, "Swift": 1058}
package org.starter.project.feature.home.component.article import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil3.compose.AsyncImage import org.starter.project.base.data.model.zenn.Article import org.starter.project.ui.design.system.theme.DesignSystemTheme @Composable fun ArticleListItem( article: Article ) { Row( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(DesignSystemTheme.colors.background) .border( width = 1.dp, color = DesignSystemTheme.colors.onSurface.copy(alpha = 0.12f), shape = RoundedCornerShape(8.dp) ) .padding(vertical = 8.dp, horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp) ) { Text( style = DesignSystemTheme.typography.h4, text = article.emoji, ) Column( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text( style = DesignSystemTheme.typography.subtitle2, text = article.title, maxLines = 2, overflow = TextOverflow.Ellipsis ) Row( modifier = Modifier.align(Alignment.End), verticalAlignment = Alignment.CenterVertically ) { Image( painter = rememberVectorPainter(image = Icons.Default.FavoriteBorder), contentDescription = null, modifier = Modifier.size(12.dp) ) Spacer(modifier = Modifier.width(4.dp)) Text( style = DesignSystemTheme.typography.caption, color = Color.DarkGray, text = article.likedCount.toString() ) Spacer(modifier = Modifier.width(12.dp)) AsyncImage( model = article.user.avatarSmallUrl, contentDescription = null, modifier = Modifier.size(12.dp) ) Spacer(modifier = Modifier.width(4.dp)) Text( style = DesignSystemTheme.typography.caption, color = Color.DarkGray, text = article.user.name, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } } }
0
Kotlin
0
0
a38261d166296755c205e77ddcab2222f8c832ac
3,633
Compose-Multiplatform-Starter-Template
Apache License 2.0
app/src/main/java/com/xavier/wagner/todolist/uai/CreateTaskActivity.kt
wagnerxavierp
402,940,216
false
null
package com.xavier.wagner.todolist.uai import android.app.AlertDialog import android.content.DialogInterface import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.google.android.material.datepicker.MaterialDatePicker import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat import com.xavier.wagner.todolist.databinding.ActivityCreateTaskBinding import com.xavier.wagner.todolist.datasource.TaskDataSource import com.xavier.wagner.todolist.extensions.format import com.xavier.wagner.todolist.extensions.formatHour import com.xavier.wagner.todolist.model.Task import java.util.* class CreateTaskActivity : AppCompatActivity() { private lateinit var binding: ActivityCreateTaskBinding private var task: Task = Task(0, "","","") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCreateTaskBinding.inflate(layoutInflater) setContentView(binding.root) addListeners() setValuesDefault() val extras = intent.extras extras?.let { val taskId = it.getInt(TaskDataSource.TASK_ID) TaskDataSource.findById(taskId)?.let { binding.editTitle.setText(it.title) binding.textDate.text = it.date binding.textHour.text = it.hour } } } private fun setValuesDefault() { val date = Date() binding.textDate.text = date.format() binding.textHour.text = date.formatHour() } private fun addListeners() { binding.textDate.setOnClickListener { val datePiker = MaterialDatePicker.Builder.datePicker().build() datePiker.addOnPositiveButtonClickListener { val timeZone = TimeZone.getDefault() val offset = timeZone.getOffset(Date().time) * -1 binding.textDate.text = Date(it + offset).format() } datePiker.show(supportFragmentManager, "DATE_PIKER_TAG") } binding.textHour.setOnClickListener { val timePiker = MaterialTimePicker.Builder() .setTimeFormat(TimeFormat.CLOCK_24H) .build() timePiker.addOnPositiveButtonClickListener { val hour = if(timePiker.hour in 0..9) "0${timePiker.hour}" else timePiker.hour val minute = if(timePiker.minute in 0..9) "0${timePiker.minute}" else timePiker.minute binding.textHour.text = "${hour}:${minute}" } timePiker.show(supportFragmentManager, "DATE_PIKER_TAG") } binding.imgCancel.setOnClickListener { dialogAlertDescartTask() } binding.imgSave.setOnClickListener { val task = Task( title = binding.editTitle.text.toString(), date = binding.textDate.text.toString(), hour = binding.textHour.text.toString(), id = intent.getIntExtra(TaskDataSource.TASK_ID, 0) ) TaskDataSource.insertTask(task) Toast.makeText(this, "Tarefa criada!", Toast.LENGTH_LONG).show() setResult(RESULT_OK) finish() } } fun dialogAlertDescartTask(){ val dialog = AlertDialog.Builder(this) .setMessage("Descartar tarefa?") // Specifying a listener allows you to take an action before dismissing the dialog. .setPositiveButton("Manter"){_, _ -> } .setNeutralButton("Descartar"){_, _ -> finish() } .show() dialog.getButton(DialogInterface.BUTTON_POSITIVE).isAllCaps = false dialog.getButton(DialogInterface.BUTTON_NEUTRAL).isAllCaps = false } }
0
Kotlin
0
0
ec3fbebc9a044a4005fa6b938f70895f35e740d6
3,875
To_do_list_android
MIT License
theme-contract/src/main/java/com/orange/ouds/theme/tokens/semantic/OudsGridTokens.kt
Orange-OpenSource
817,725,638
false
{"Kotlin": 122970, "HTML": 14555, "CSS": 1404, "JavaScript": 197}
/* * Software Name: OUDS Android * SPDX-FileCopyrightText: Copyright (c) Orange SA * SPDX-License-Identifier: MIT * * This software is distributed under the MIT license, * the text of which is available at https://opensource.org/license/MIT/ * or see the "LICENSE" file for more details. * * Software description: Android library of reusable graphical components */ package com.orange.ouds.theme.tokens.semantic import androidx.compose.runtime.Stable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.orange.ouds.theme.OudsAdaptiveTokenValue import com.orange.ouds.theme.OudsAdaptiveWindowType import com.orange.ouds.tokens.global.raw.GridRawTokens data class OudsGridTokens( val minWidth: OudsAdaptiveTokenValue = OudsAdaptiveTokenValue( GridRawTokens.gridMinWidthExtraCompact.dp, GridRawTokens.gridMinWidthCompact.dp, GridRawTokens.gridMinWidthMedium.dp ), val maxWidth: OudsAdaptiveTokenValue = OudsAdaptiveTokenValue( GridRawTokens.gridMaxWidthExtraCompact.dp, GridRawTokens.gridMaxWidthCompact.dp, GridRawTokens.gridMaxWidthMedium.dp ), val margin: OudsAdaptiveTokenValue = OudsAdaptiveTokenValue( GridRawTokens.gridMargin100.dp, GridRawTokens.gridMargin300.dp, GridRawTokens.gridMargin500.dp ), val columnGap: OudsAdaptiveTokenValue = OudsAdaptiveTokenValue( GridRawTokens.gridColumnGap100.dp, GridRawTokens.gridColumnGap200.dp, GridRawTokens.gridColumnGap400.dp ), ) enum class OudsGridKeyToken { MinWidth, MaxWidth, ColumnGap, Margin, } @Stable fun OudsGridTokens.fromToken(token: OudsGridKeyToken, adaptiveWindowType: OudsAdaptiveWindowType): Dp { val gridToken = when (token) { OudsGridKeyToken.MinWidth -> minWidth OudsGridKeyToken.MaxWidth -> maxWidth OudsGridKeyToken.ColumnGap -> columnGap OudsGridKeyToken.Margin -> margin } return when (adaptiveWindowType) { OudsAdaptiveWindowType.EXTRA_COMPACT -> gridToken.extraCompact OudsAdaptiveWindowType.COMPACT -> gridToken.compact OudsAdaptiveWindowType.MEDIUM -> gridToken.medium } }
10
Kotlin
1
6
28e063d49eab2202570ac8897b3c40b0bed64b4d
2,206
ouds-android
MIT License
nextgen-middleware/src/main/java/com/nextgenbroadcast/mobile/middleware/rpc/eventStream/EventStreamImpl.kt
jjustman
418,004,011
false
null
package com.nextgenbroadcast.mobile.middleware.rpc.eventStream import com.nextgenbroadcast.mobile.middleware.rpc.RpcResponse class EventStreamImpl : IEventStream { override fun eventStreamSubscribe(schemeIdUri: String, value: String?): RpcResponse { return RpcResponse() } override fun eventStreamUnsubscribe(schemeIdUri: String, value: String?): RpcResponse { return RpcResponse() } }
0
Kotlin
0
5
f0d91240d7c68c57c7ebfd0739148c86a38ffa58
420
libatsc3-middleware-sample-app
MIT License
src/main/kotlin/org/toml/lang/TomlFileTypeFactory.kt
stuartcarnie
48,140,365
false
null
package org.toml.lang import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher import com.intellij.openapi.fileTypes.FileTypeConsumer import com.intellij.openapi.fileTypes.FileTypeFactory public class TomlFileTypeFactory : FileTypeFactory() { override fun createFileTypes(consumer: FileTypeConsumer) { consumer.consume(TomlFileType, ExtensionFileNameMatcher(TomlFileType.DEFAULTS.EXTENSION)) } }
0
Kotlin
1
5
06b6f29e3d1de53a61ac121e9cd6c067275e3acb
436
toml-plugin
MIT License
solar/src/main/java/com/chiksmedina/solar/boldduotone/money/Banknote2.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.money import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.boldduotone.MoneyGroup val MoneyGroup.Banknote2: ImageVector get() { if (_banknote2 != null) { return _banknote2!! } _banknote2 = Builder( name = "Banknote2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(8.5057f, 10.7144f) curveTo(8.5057f, 9.7939f, 9.2609f, 9.0477f, 10.1924f, 9.0477f) curveTo(11.124f, 9.0477f, 11.8792f, 9.7939f, 11.8792f, 10.7144f) curveTo(11.8792f, 11.6349f, 11.124f, 12.3811f, 10.1924f, 12.3811f) curveTo(9.2609f, 12.3811f, 8.5057f, 11.6349f, 8.5057f, 10.7144f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(2.0f, 10.7143f) curveTo(2.0f, 8.0206f, 2.0f, 6.6737f, 2.8469f, 5.8368f) curveTo(3.6938f, 5.0f, 5.0569f, 5.0f, 7.783f, 5.0f) horizontalLineTo(12.6022f) curveTo(15.3284f, 5.0f, 16.6914f, 5.0f, 17.5384f, 5.8368f) curveTo(18.3853f, 6.6737f, 18.3853f, 8.0206f, 18.3853f, 10.7143f) curveTo(18.3853f, 13.4081f, 18.3853f, 14.755f, 17.5384f, 15.5918f) curveTo(16.6914f, 16.4287f, 15.3284f, 16.4287f, 12.6022f, 16.4287f) horizontalLineTo(7.783f) curveTo(5.0569f, 16.4287f, 3.6938f, 16.4287f, 2.8469f, 15.5918f) curveTo(2.0f, 14.755f, 2.0f, 13.4081f, 2.0f, 10.7143f) close() moveTo(7.06f, 10.7144f) curveTo(7.06f, 9.0049f, 8.4624f, 7.6191f, 10.1924f, 7.6191f) curveTo(11.9225f, 7.6191f, 13.3249f, 9.0049f, 13.3249f, 10.7144f) curveTo(13.3249f, 12.4239f, 11.9225f, 13.8097f, 10.1924f, 13.8097f) curveTo(8.4624f, 13.8097f, 7.06f, 12.4239f, 7.06f, 10.7144f) close() moveTo(4.1685f, 12.6192f) curveTo(4.1685f, 13.0137f, 4.4921f, 13.3335f, 4.8913f, 13.3335f) curveTo(5.2906f, 13.3335f, 5.6142f, 13.0137f, 5.6142f, 12.6192f) lineTo(5.6142f, 8.8096f) curveTo(5.6142f, 8.4151f, 5.2906f, 8.0953f, 4.8913f, 8.0953f) curveTo(4.4921f, 8.0953f, 4.1685f, 8.4151f, 4.1685f, 8.8096f) lineTo(4.1685f, 12.6192f) close() moveTo(15.4936f, 13.3335f) curveTo(15.0943f, 13.3335f, 14.7707f, 13.0137f, 14.7707f, 12.6192f) verticalLineTo(8.8096f) curveTo(14.7707f, 8.4151f, 15.0943f, 8.0953f, 15.4936f, 8.0953f) curveTo(15.8928f, 8.0953f, 16.2164f, 8.4151f, 16.2164f, 8.8096f) verticalLineTo(12.6192f) curveTo(16.2164f, 13.0137f, 15.8928f, 13.3335f, 15.4936f, 13.3335f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(4.0652f, 16.225f) curveTo(4.0782f, 16.3759f, 4.0939f, 16.5205f, 4.1127f, 16.6587f) curveTo(4.2293f, 17.516f, 4.4789f, 18.2378f, 5.059f, 18.811f) curveTo(5.1416f, 18.8926f, 5.2273f, 18.9676f, 5.3159f, 19.0366f) curveTo(5.8813f, 19.5505f, 6.5817f, 19.7785f, 7.4058f, 19.888f) curveTo(8.2415f, 19.999f, 9.3039f, 19.999f, 10.622f, 19.999f) horizontalLineTo(15.547f) curveTo(16.8651f, 19.999f, 17.9276f, 19.999f, 18.7632f, 19.888f) curveTo(19.6308f, 19.7727f, 20.3613f, 19.5262f, 20.9414f, 18.9529f) curveTo(21.5216f, 18.3796f, 21.7711f, 17.6579f, 21.8877f, 16.8006f) curveTo(22.0001f, 15.9749f, 22.0001f, 14.9251f, 22.0f, 13.6226f) verticalLineTo(13.5181f) curveTo(22.0001f, 12.2156f, 22.0001f, 11.1658f, 21.8877f, 10.3401f) curveTo(21.7711f, 9.4828f, 21.5216f, 8.761f, 20.9414f, 8.1878f) curveTo(20.8588f, 8.1062f, 20.7732f, 8.0312f, 20.6845f, 7.9622f) curveTo(20.1192f, 7.4483f, 19.4187f, 7.2203f, 18.5946f, 7.1108f) curveTo(18.4638f, 7.0934f, 18.3275f, 7.0788f, 18.1854f, 7.0664f) curveTo(18.3852f, 7.8998f, 18.3852f, 9.0499f, 18.3852f, 10.7142f) curveTo(18.3852f, 13.4079f, 18.3852f, 14.7548f, 17.5382f, 15.5916f) curveTo(16.6913f, 16.4285f, 15.3283f, 16.4285f, 12.6021f, 16.4285f) horizontalLineTo(7.7829f) curveTo(6.0812f, 16.4285f, 4.9106f, 16.4285f, 4.0652f, 16.225f) close() } } .build() return _banknote2!! } private var _banknote2: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
6,046
SolarIconSetAndroid
MIT License
tv/src/main/java/com/aastudio/sarollahi/moviebox/KoinModule.kt
sarollahi
327,908,585
false
{"Kotlin": 450483}
/* * Copyright (C) 2021 Seyed Ahmad Sarollahi * All rights reserved. */ package com.aastudio.sarollahi.moviebox import com.aastudio.sarollahi.moviebox.views.fragments.RootMovieViewModel import org.koin.android.ext.koin.androidApplication import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelsModule = module { viewModel { RootMovieViewModel(androidApplication()) } }
0
Kotlin
0
0
17acb53f4ab51e40126fa3136f851eb8895074c2
413
MovieBox-Kotlin
Apache License 2.0
common/libs/logger/src/commonMain/kotlin/io/chefbook/libs/logger/Logger.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.libs.logger expect object Logger { fun v(message: String?, vararg args: Any?) fun v(t: Throwable?, message: String?, vararg args: Any?) fun v(t: Throwable?) fun d(message: String?, vararg args: Any?) fun d(t: Throwable?, message: String?, vararg args: Any?) fun d(t: Throwable?) fun i(message: String?, vararg args: Any?) fun i(t: Throwable?, message: String?, vararg args: Any?) fun i(t: Throwable?) fun w(message: String?, vararg args: Any?) fun w(t: Throwable?, message: String?, vararg args: Any?) fun w(t: Throwable?) fun e(message: String?, vararg args: Any?) fun e(t: Throwable?, message: String?, vararg args: Any?) fun e(t: Throwable?) }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
713
chefbook-mobile
Apache License 2.0
app/src/main/kotlin/com/releaseit/cryptoprices/repository/CryptoRepository.kt
JurajBegovac
121,294,794
false
null
package com.releaseit.cryptoprices.repository import io.reactivex.Single /** * Created by jurajbegovac on 12/02/2018. */ interface CryptoRepository { fun getCryptos(currency: Currency, limit: String): Single<List<Crypto>> fun getCrypto(id: String, currency: Currency): Single<Crypto> companion object { // hardcoded limit const val LIMIT = 100 } } data class Crypto(val id: String, val name: String, val rank: String, val symbol: String, val price: String, val _24hVolume: String, val priceBtc: String, val percentChange1h: String, val percentChange24h: String, val percentChange7d: String, val availableSupply: String, val totalSupply: String, val currency: Currency, val marketCap: String) enum class Currency { USD, EUR, CNY }
0
Kotlin
0
0
19d2881d8365f1284331b79024c3b430a11cd141
991
CryptoPrices
MIT License
ee/backend/tests/src/test/kotlin/io/tolgee/ee/EeTolgeeTranslatorControllerTest.kt
tolgee
303,766,501
false
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
package io.tolgee.ee import io.tolgee.ProjectAuthControllerTest import io.tolgee.api.SubscriptionStatus import io.tolgee.component.machineTranslation.MtValueProvider import io.tolgee.component.machineTranslation.providers.tolgee.TolgeeTranslateParams import io.tolgee.constants.Feature import io.tolgee.development.testDataBuilder.data.SuggestionTestData import io.tolgee.ee.component.contentDelivery.EeTolgeeTranslateApiServiceImpl import io.tolgee.ee.model.EeSubscription import io.tolgee.ee.repository.EeSubscriptionRepository import io.tolgee.fixtures.andAssertThatJson import io.tolgee.fixtures.andIsOk import io.tolgee.fixtures.andPrettyPrint import io.tolgee.fixtures.node import io.tolgee.testing.annotations.ProjectJWTAuthTestMethod import io.tolgee.testing.assert import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean import java.util.* class EeTolgeeTranslatorControllerTest : ProjectAuthControllerTest("/v2/projects/") { private lateinit var testData: SuggestionTestData @Autowired @MockBean private lateinit var eeTolgeeTranslateApiService: EeTolgeeTranslateApiServiceImpl @Autowired private lateinit var eeSubscriptionRepository: EeSubscriptionRepository private fun saveTestData() { testData = SuggestionTestData() testDataService.saveTestData(testData.root) userAccount = testData.user projectSupplier = { testData.projectBuilder.self } } private fun prepareSubscription() { eeSubscriptionRepository.save( EeSubscription().apply { licenseKey = "mock" name = "Plaaan" status = SubscriptionStatus.ACTIVE currentPeriodEnd = Date() cancelAtPeriodEnd = false enabledFeatures = Feature.values() lastValidCheck = Date() }, ) } @AfterEach fun after() { internalProperties.fakeMtProviders = true } @Test @ProjectJWTAuthTestMethod fun `it translates`() { saveTestData() prepareSubscription() internalProperties.fakeMtProviders = false whenever( eeTolgeeTranslateApiService.translate(any()), ).thenAnswer { MtValueProvider.MtResult( "Translated with Tolgee Translator", ((it.arguments[0] as? TolgeeTranslateParams)?.text?.length ?: 0) * 100, "OMG!", ) } performProjectAuthPost( "suggest/machine-translations", mapOf("baseText" to "Yupee", "targetLanguageId" to testData.germanLanguage.id), ).andIsOk.andPrettyPrint.andAssertThatJson { node("result") { node("TOLGEE") { node("output").isEqualTo("Translated with Tolgee Translator") } } Mockito.mockingDetails(eeTolgeeTranslateApiService).invocations.assert.hasSize(1) } } }
170
TypeScript
188
1,837
6e01eec3a19c151a6e0aca49e187e2d0deef3082
2,935
tolgee-platform
Apache License 2.0
atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/DerivableKey.kt
input-output-hk
564,174,099
false
{"Kotlin": 534787, "Gherkin": 1987, "ANTLR": 1440, "JavaScript": 375}
package io.iohk.atala.prism.walletsdk.domain.models.keyManagement import io.iohk.atala.prism.apollo.derivation.DerivationPath interface DerivableKey { fun derive(derivationPath: DerivationPath): PrivateKey }
1
Kotlin
0
5
0549258251a69eebc3f032466263575966dbad21
214
atala-prism-wallet-sdk-kmm
Apache License 2.0
android/src/main/java/com/companycamvibecheck/CompanycamVibeCheckModule.kt
CompanyCam
719,714,006
false
{"YAML": 5, "JSON with Comments": 1, "Ruby": 3, "JSON": 9, "JavaScript": 12, "Markdown": 4, "Text": 1, "Ignore List": 1, "Git Attributes": 1, "EditorConfig": 1, "TSX": 3, "CODEOWNERS": 1, "INI": 4, "Gradle": 4, "Shell": 6, "Batchfile": 2, "XML": 10, "Kotlin": 2, "Java Properties": 1, "Java": 4, "Dotenv": 1, "C": 1, "Swift": 2, "OpenStep Property List": 3, "Objective-C": 4, "Objective-C++": 2}
package com.companycamvibecheck import android.app.ActivityManager import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.Promise import android.content.Context import android.os.Build import android.os.PowerManager class CompanycamVibeCheckModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { val powerManager = reactContext.getSystemService(Context.POWER_SERVICE) as PowerManager val activityManager = reactContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager override fun getName(): String { return NAME } fun normalizeAndroidThermalState(thermalState: Int): String { return when (thermalState) { 0, 1 -> "nominal" 2 -> "fair" 3 -> "serious" 4, 5, 6 -> "critical" else -> "unknown" } } @ReactMethod fun getMemoryInfo(promise: Promise) { val memoryInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memoryInfo) val availMem = memoryInfo.totalMem - memoryInfo.availMem; promise.resolve(availMem.toString()) } @ReactMethod fun getThermalState(promise: Promise) { if (Build.VERSION.SDK_INT >= 29) { promise.resolve(normalizeAndroidThermalState(powerManager.currentThermalStatus)); } promise.resolve(normalizeAndroidThermalState(-1)) } companion object { const val NAME = "CompanycamVibeCheck" } }
9
Java
0
2
ced9e693c62df1c780d8d025cfeaefd71bf016b8
1,526
companycam-vibe-check
MIT License
cache/src/main/kotlin/com/impassive/cache/core/CustomCacheBuilder.kt
yangbiny
548,708,667
false
{"Gradle": 22, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 2, "Git Attributes": 1, "Markdown": 4, "Java": 134, "INI": 2, "Kotlin": 38, "Scala": 8}
package com.impassive.cache.core import com.impassive.cache.config.CustomCacheCommonCfg import com.impassive.cache.core.decorator.AsyncWriteDecorator import com.impassive.cache.core.decorator.TailDecorator import com.impassive.cache.impl.lettuce.CustomLettuceCache import com.impassive.cache.impl.lettuce.CustomLettuceConnConfig import java.time.Duration import java.util.concurrent.ThreadPoolExecutor /** * @author impassive */ class CustomCacheBuilder<K, V> constructor( private val expireAfterWrite: Duration = Duration.ofMinutes(15), private val lettuceConnCfg: CustomLettuceConnConfig<K, V>, private val asyncWriteExecutor: ThreadPoolExecutor? = null ) : Validatable { fun build(): CustomCache<K, V> { validate() var cache: CustomCache<K, V> = CustomLettuceCache( lettuceConnConfig = lettuceConnCfg, customCacheCommonCfg = CustomCacheCommonCfg(expireAfterWrite) ) cache = asyncWriteExecutor?.run { AsyncWriteDecorator(cache, this) } ?: run { cache } return TailDecorator(cache) } }
0
Java
0
2
743c268d6c05c3e74a90586f618f79143fedb3b8
1,117
learning
Apache License 2.0
src/main/kotlin/chapter12/mvc/BeatBar.kt
antop-dev
485,700,651
false
{"Java": 114489, "Kotlin": 83077}
package chapter12.mvc import java.awt.BorderLayout import javax.swing.JLabel import javax.swing.JProgressBar import javax.swing.border.EmptyBorder import kotlin.concurrent.thread class BeatBar : JProgressBar(0, 100) { private val progressLabel: JLabel = JLabel("offline").apply { horizontalAlignment = JLabel.CENTER verticalAlignment = JLabel.CENTER border = EmptyBorder(5, 5, 5, 5) } var text: String get() = progressLabel.text set(value) { progressLabel.text = value } init { value = 0 layout = BorderLayout(5, 5) add(progressLabel) // 값이 100이 됐을 떄 75로 만들어줌으로써 비트가 치는 것 처럼 보이게 한다. thread { while (true) { if (value == 100) { Thread.sleep(20) val v = (value.toDouble() * 0.75).toInt() value = v repaint() } Thread.sleep(30) } } } }
1
null
1
1
ebabc19d6a742884873ff58e0449cc8cb8c39421
1,018
head-first-design-patterns
MIT License
app/src/main/java/com/example/thingsfortrip/data/models/Category.kt
maks099
692,361,020
false
{"Kotlin": 71351}
package com.example.thingsfortrip.data.models data class Category(val name: String = "", val code: Int = 0)
5
Kotlin
0
0
f11db0bcbc2011ec0955b277bc8c36c05920d2a9
109
ThingsForTrip
Apache License 2.0
examples/src/test/kotlin/ch/icken/model/ExamplesTest.kt
Thijsiez
699,910,580
false
{"Kotlin": 85947}
/* * Copyright 2024 <NAME> * * 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 ch.icken.model import ch.icken.* import ch.icken.query.PanacheSingleResult import io.quarkus.test.junit.QuarkusTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertInstanceOf import org.junit.jupiter.api.Test import java.time.LocalDate @QuarkusTest class ExamplesTest { @Test fun runAllExamples() { // Given // When val john = findJohn() val numberOfNotMen = countNotMen() val bornBeforeEpoch = bornBefore(LocalDate.EPOCH) val sons = findAllSons() val averageSalary = averageOfVerySpecificSalaryRanges() // Then assertInstanceOf(PanacheSingleResult.Result::class.java, john) assertEquals(4, numberOfNotMen) assertEquals(2, bornBeforeEpoch.size) assertEquals(2, sons.size) assertEquals(67_500.0, averageSalary) } }
0
Kotlin
0
1
730c2fd001db3cb85967cefe7886d4cdce095d7e
1,486
panache-kotlin-dsl
Apache License 2.0
common/src/androidMain/kotlin/com/artemchep/keyguard/android/PendingIntents.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.android import com.artemchep.keyguard.android.downloader.NotificationIdPool object PendingIntents { val autofill = NotificationIdPool.sequential(0) val credential = NotificationIdPool.sequential( start = 100000, endExclusive = 200000, ) }
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
300
keyguard-app
Linux Kernel Variant of OpenIB.org license
epubify/src/test/java/org/nextstack/epubify/ParserTest.kt
Nextstack-LLC
786,416,395
false
{"Kotlin": 78307, "JavaScript": 2163, "HTML": 1164}
package org.nextstack.epubify import org.nextstack.epubify.parser.EpubParser import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertNotNull import junit.framework.TestCase.assertNull import kotlinx.coroutines.test.runTest import org.apache.commons.text.StringEscapeUtils import org.junit.Test import org.junit.runner.RunWith import org.nextstack.epubify.model.ParseOptions import org.robolectric.RobolectricTestRunner import java.io.File import java.io.FileNotFoundException @RunWith(RobolectricTestRunner::class) class ParserTest { @Test fun testParseEpub() = runTest { val file = getFileFromPath(this@ParserTest, "test2.epub") val epub = EpubParser.parse(file, ParseOptions()) assertEquals("Accessible EPUB 3", epub.title) assertEquals("Matt Garrish", epub.author) assertNotNull(epub.cover?.path) // Chapters include the cover pages as well assertEquals(10, epub.chapters.size) assertEquals("Accessible EPUB 3", epub.chapters[3].title) } @Test fun testParseEpubInputStream() = runTest { val file = getFileFromPath(this@ParserTest, "test1.epub") val epub = EpubParser.parse(file.inputStream(), ParseOptions()) assertEquals("Sample .epub Book", epub.title) assertEquals("Thomas Hansen", epub.author) assertNull(epub.cover?.path) assertEquals(4, epub.chapters.size) assertEquals("Chapter 1", epub.chapters[1].title) } @Test fun testNotExistingFile() = runTest { val file = getFileFromPath(this@ParserTest, "not_existing.epub") runCatching { EpubParser.parse(file, ParseOptions()) }.onFailure { assertEquals(FileNotFoundException::class, it::class) }.onSuccess { assert(false) } } private fun getFileFromPath(obj: Any, fileName: String): File { val classLoader = obj.javaClass.getClassLoader() val resource = classLoader?.getResource(fileName) return File(resource?.path ?: "") } }
0
Kotlin
0
1
bcec7a41996bfdfa8c84523973b6117901c4d963
2,085
epubify
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Closing.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: Closing * * Full name: System`Closing * * Closing[image, ker] gives the morphological closing of image with respect to the structuring element ker. * Closing[image, r] gives the closing with respect to a range-r square. * Usage: Closing[data, …] applies closing to an array of data. * * Options: None * * HoldRest * Protected * Attributes: ReadProtected * * local: paclet:ref/Closing * Documentation: web: http://reference.wolfram.com/language/ref/Closing.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun closing(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("Closing", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,201
mathemagika
Apache License 2.0
Mitori-Satori/src/main/kotlin/xyz/xasmc/mitori/satori/router/ReactionApiRouter.kt
XAS-Dev
832,216,378
false
{"Kotlin": 71553, "Java": 179}
package xyz.xasmc.mitori.satori.router import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import xyz.xasmc.mitori.satori.api.ReactionApiHandler import xyz.xasmc.mitori.satori.datatype.api.reaction.ReactionClear import xyz.xasmc.mitori.satori.datatype.api.reaction.ReactionCreate import xyz.xasmc.mitori.satori.datatype.api.reaction.ReactionDelete import xyz.xasmc.mitori.satori.datatype.api.reaction.ReactionList fun Route.reactionApiRouter(handler: ReactionApiHandler) { post("reaction.create") { val data = call.receive<ReactionCreate>() handler.reactionCreate(data.channel_id, data.message_id, data.emoji) call.respond(HttpStatusCode.OK) } post("reaction.delete") { val data = call.receive<ReactionDelete>() handler.reactionDelete(data.channel_id, data.message_id, data.emoji, data.user_id) call.respond(HttpStatusCode.OK) } post("reaction.create") { val data = call.receive<ReactionClear>() handler.reactionClear(data.channel_id, data.message_id, data.emoji) call.respond(HttpStatusCode.OK) } post("reaction.list") { val data = call.receive<ReactionList>() val result = handler.reactionList(data.channel_id, data.message_id, data.emoji, data.next) call.respond(HttpStatusCode.OK, result) } }
0
Kotlin
0
1
ba84efef3d336ead22ddcb266063fc682ccdd925
1,429
Mitori
MIT License
src/main/kotlin/com/terraformation/backend/report/event/ReportSubmittedEvent.kt
terraware
323,722,525
false
{"Kotlin": 3741923, "HTML": 88820, "Python": 46278, "FreeMarker": 16407, "PLpgSQL": 3305, "Makefile": 746, "Dockerfile": 674}
package com.terraformation.backend.report.event import com.terraformation.backend.db.default_schema.ReportId import com.terraformation.backend.report.model.LatestReportBodyModel /** Published when an organization admin submits a report. */ data class ReportSubmittedEvent(val reportId: ReportId, val body: LatestReportBodyModel)
3
Kotlin
1
9
4b567755b38c1021a76d677f22d865c45d4099b1
331
terraware-server
Apache License 2.0
NatSample/app/src/androidTest/java/com/baobomb/nlautouitestsample/MoreViews.kt
MarcusCwl
187,816,492
false
null
package com.baobomb.nlautouitestsample import android.support.test.espresso.Espresso import android.support.test.espresso.action.ViewActions import android.support.test.espresso.matcher.RootMatchers import android.support.test.espresso.matcher.ViewMatchers import android.support.test.espresso.matcher.ViewMatchers.withId import com.baobomb.nlautouitest.BaseView import com.baobomb.nlautouitest.ReflectionHelper import com.baobomb.nlautouitest.Views class MoreViews : Views() { @ReflectionHelper.TestView("測試列表", "main list view") class MainScrollView : BaseView(R.id.rv_sample) @ReflectionHelper.TestView("主頁面ViewPager", "main view pager") class MainViewPager : BaseView(R.id.vp_sample) @ReflectionHelper.TestView("請求權限按鈕", "BtnRequestPermission") class RequestPermissionBtn : BaseView(R.id.bt_request_permission) { override fun click() { Espresso.onView(withId(id)).perform(ViewActions.click()) } } }
0
Kotlin
0
0
e6b94bccc4b2ed2b65b99a7f68b2409f2bfe4e43
963
Nat
Apache License 2.0
src/main/kotlin/org/lnwza007/relay/service/nip01/EventValidator.kt
rushmi0
800,389,073
false
{"Kotlin": 50472}
//package org.lnwza007.relay.service.nip01 // //import org.lnwza007.relay.modules.Event //import org.lnwza007.relay.service.nip01.Transform.toEvent //import org.lnwza007.relay.service.nip13.ProofOfWork //import org.lnwza007.util.Schnorr //import org.lnwza007.util.ShiftTo.fromHex //import org.lnwza007.util.ShiftTo.toJsonElementMap //import org.lnwza007.util.ShiftTo.toJsonString //import org.lnwza007.util.ShiftTo.toSha256 // //object EventValidator { // // /** // * ตรวจสอบว่าขนาดของ ID, Public Key และ Signature ถูกต้องหรือไม่ // */ // private fun isSizeValid(event: Event): Boolean { // return event.id?.fromHex()?.size == 32 && event.pubkey?.fromHex()?.size == 32&& event.signature?.fromHex()?.size == 64 // } // // /** // * ตรวจสอบ Proof of Work ของ event ว่าถูกต้องตามที่กำหนดหรือไม่ // */ // private fun isProofOfWorkValid(event: Event): Boolean { // val nonceTag = event.tags?.find { it[0] == "nonce" } ?: return true // val difficulty = nonceTag[2].toIntOrNull() ?: return false // return ProofOfWork.checkProofOfWork(event.id!!, difficulty.toLong()) // } // // /** // * ตรวจสอบว่าลายเซ็นของ event ถูกต้องหรือไม่ // */ // private fun isSignatureValid(event: Event): Boolean { // val draftField: String = arrayListOf( // 0, // event.pubkey, // event.createAt, // event.kind, // event.tags, // event.content // ).toJsonString() // // val eventHash = draftField.toSha256() // return Schnorr.verify(eventHash, event.pubkey!!, event.signature!!) // } // // /** // * ฟังก์ชันตรวจสอบ event ทั้งหมด // */ // fun validateEvent(event: Event): Boolean { // if (!isSizeValid(event)) return false // if (!isProofOfWorkValid(event)) return false // if (!isSignatureValid(event)) return false // return true // } //} // //fun main() { // val eventString = """ // { // "id":"0000005b0fc51e70b66db99ba1708b1a1b008c30db35d19d35146b3e09756029", // "pubkey":"161498ed3277aa583c301288de5aafda4f317d2bf1ad0a880198a9dede37a6aa", // "created_at":1716617176, // "kind":1, // "tags":[ // ["nonce","19735841","23"] // ], // "content":"My custom content", // "sig":"954c662c9ee29ccad8a1f30d22b9a5cefcea774f72428ec7344b65e4f31fff24fc4dd0b7874a4d10a1a4c012de013df19a7c33018dda5f1207280f9a28193498" // } // """.trimIndent() // // val d = """ // { // "created_at": 1716448321, // "kind": 0, // "tags": [["alt", "User profile for lnwza007"]], // "content": "{\"name\":\"lnwza007\",\"gender\":\"\",\"area\":\"\",\"picture\":\"https://image.nostr.build/552b5424ebd3c66be6f588e08c2f427e04423f11e80514414215b5ae00877b28.gif\",\"lud16\":\"<EMAIL>\",\"website\":\"https://github.com/rushmi0\",\"display_name\":\"lnwza007\",\"banner\":\"\",\"about\":\"แดดกรุงเทพที่ร้อนจ้า ยังแพ้ตัวข้าที่ร้อน sat\"}", // "pubkey": "e4b2c64f0e4e54abb34d5624cd040e05ecc77f0c467cc46e2cc4d5be98abe3e3", // "id": "<KEY>", // "sig": "6a7898997ceb936fb6f660848baf8185f84ab22ff45aa3fc36eabad577bb4fae739bfdcd3d428d52146c6feaf9264bbc8f82121ddb8eeb85ce242ff79a1b0948" // } // """.trimIndent() // // val event = d.toJsonElementMap().toEvent() // if (event != null) { // val isValid = EventValidator.validateEvent(event) // println("Event is valid: $isValid") // } else { // println("Invalid event data") // } //}
0
Kotlin
0
0
139ca7958b203ccc2ce55543f22f16709438eb8e
3,575
lnwza007
MIT License
app/src/androidTest/java/com/example/mymovies/AddHowIMetYourMotherToFavoritesThenDelete.kt
robdeputter
217,722,349
false
null
package com.example.mymovies import android.view.View import android.view.ViewGroup import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withClassName import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.espresso.matcher.ViewMatchers.withContentDescription import androidx.test.filters.LargeTest import androidx.test.rule.ActivityTestRule import androidx.test.runner.AndroidJUnit4 import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.allOf import org.hamcrest.TypeSafeMatcher import org.hamcrest.core.IsInstanceOf import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class AddHowIMetYourMotherToFavoritesThenDelete { @Rule @JvmField var mActivityTestRule = ActivityTestRule(MainActivity::class.java) @Test fun addHowIMetYourMotherToFavoritesThenDelete() { val materialCardView = onView( allOf( withId(R.id.searchCardView), childAtPosition( childAtPosition( withId(R.id.nav_host_fragment), 0 ), 0 ), isDisplayed() ) ) materialCardView.perform(click()) val textInputEditText = onView( allOf( withId(R.id.searchEditText), childAtPosition( childAtPosition( withId(R.id.nav_host_fragment), 0 ), 0 ), isDisplayed() ) ) textInputEditText.perform(replaceText("how i met your mother"), closeSoftKeyboard()) Thread.sleep(7000) val materialCardView2 = onView( allOf( childAtPosition( allOf( withId(R.id.movies_series_list), childAtPosition( withClassName(`is`("androidx.constraintlayout.widget.ConstraintLayout")), 1 ) ), 0 ), isDisplayed() ) ) materialCardView2.perform(click()) Thread.sleep(5000) val appCompatButton = onView( allOf( withId(R.id.addFavorit), childAtPosition( childAtPosition( withClassName(`is`("androidx.core.widget.NestedScrollView")), 0 ), 2 ), isDisplayed() ) ) appCompatButton.perform(click()) Thread.sleep(3000) val appCompatButton2 = onView( allOf( withId(R.id.addButton), withText("Add"), childAtPosition( childAtPosition( withId(android.R.id.custom), 0 ), 1 ), isDisplayed() ) ) appCompatButton2.perform(click()) Thread.sleep(3000) val appCompatImageButton = onView( allOf( withContentDescription("Navigate up"), childAtPosition( allOf( withId(R.id.action_bar), childAtPosition( withId(R.id.action_bar_container), 0 ) ), 1 ), isDisplayed() ) ) appCompatImageButton.perform(click()) val appCompatImageButton2 = onView( allOf( withContentDescription("Navigate up"), childAtPosition( allOf( withId(R.id.action_bar), childAtPosition( withId(R.id.action_bar_container), 0 ) ), 1 ), isDisplayed() ) ) appCompatImageButton2.perform(click()) val materialCardView3 = onView( allOf( withId(R.id.favoritesCardView), childAtPosition( childAtPosition( withId(R.id.nav_host_fragment), 0 ), 1 ), isDisplayed() ) ) materialCardView3.perform(click()) Thread.sleep(3000) val textView = onView( allOf( withId(R.id.title), withText("How I Met Your Mother"), childAtPosition( childAtPosition( IsInstanceOf.instanceOf(android.widget.FrameLayout::class.java), 0 ), 1 ), isDisplayed() ) ) textView.check(matches(withText("How I Met Your Mother"))) val appCompatImageView = onView( allOf( childAtPosition( childAtPosition( withClassName(`is`("com.google.android.material.card.MaterialCardView")), 0 ), 2 ), isDisplayed() ) ) appCompatImageView.perform(click()) } private fun childAtPosition( parentMatcher: Matcher<View>, position: Int ): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("Child at position $position in parent ") parentMatcher.describeTo(description) } public override fun matchesSafely(view: View): Boolean { val parent = view.parent return parent is ViewGroup && parentMatcher.matches(parent) && view == parent.getChildAt(position) } } } }
0
Kotlin
0
1
08f2afc6240ee8d9c450358ccf70fca85b772c63
6,847
MyMovies_Android
MIT License
app/src/main/java/com/swensun/func/room/database/RoomEntity.kt
xjr0401
272,895,639
true
{"Kotlin": 318083, "Java": 106595}
package com.swensun.func.room.database import androidx.room.Entity import androidx.room.PrimaryKey @Entity class RoomEntity { @PrimaryKey var id = 0 var title: String = "" }
0
null
0
0
d7a708f1a5b08c837bc87f28167da98e32a74d75
192
Potato
Apache License 2.0
src/main/kotlin/com/alcosi/nft/apigateway/config/serialization/SerializationConfig.kt
alcosi
713,491,219
false
{"Kotlin": 334013, "Java": 39800, "HTML": 4727, "PLpgSQL": 1275, "JavaScript": 1127, "CSS": 824}
/* * Copyright (c) 2023 Alcosi Group Ltd. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alcosi.nft.apigateway.config.serialization import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.module.SimpleModule import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpMethod @ConditionalOnClass(ObjectMapper::class) @ConditionalOnProperty( prefix = "common-lib.object-mapper", name = ["disabled"], matchIfMissing = true, havingValue = "false", ) @Configuration class SerializationConfig() { @Bean fun getHttpSerializerModule(): SimpleModule { val module = SimpleModule() module.addDeserializer(HttpMethod::class.java, HttpMethodDeSerializer()) module.addSerializer(HttpMethod::class.java, HttpMethodSerializer()) return module } }
0
Kotlin
0
0
bdeb7b6511d0ffd0b5a8d332ff5490353d38dbae
1,611
alcosi_blockchain_api_gateway
Apache License 2.0
app/src/main/java/com/ieeevit/enigma8/view/privacy/PrivacyActivity.kt
IEEE-VIT
403,345,348
false
{"Kotlin": 288926}
package com.ieeevit.enigma8.view.privacy import android.content.Intent import android.graphics.LinearGradient import android.graphics.Shader import android.os.Bundle import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.ieeevit.enigma8.R import com.ieeevit.enigma8.view.instruction.InstructionActivity import com.ieeevit.enigma8.view.notification.NotificationActivity import com.ieeevit.enigma8.view.profile.Profdashboard import com.ieeevit.enigma8.view.rooms.RoomsActvity class PrivacyActivity:AppCompatActivity() { private lateinit var back: ImageView private lateinit var instruction: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.privacy_policy) val heading : TextView = findViewById<EditText>(R.id.privacy_policy) val shader1 : Shader= LinearGradient(0f, 0f,0f,heading.lineHeight.toFloat(), intArrayOf(this.getColor(R.color.light_yellow), this.getColor(R.color.dark_yellow)), floatArrayOf(0.3f,0.7f),Shader.TileMode.REPEAT) heading.paint.shader = shader1 back = findViewById(R.id.back_btn) instruction = findViewById(R.id.instruction) back.setOnClickListener { val intent = Intent(this, Profdashboard::class.java) startActivity(intent) } instruction.setOnClickListener { val intent = Intent(this, InstructionActivity::class.java) startActivity(intent) } } }
0
Kotlin
1
8
fbb071f350e22ea6346b8e6773c5c83cfd7b0971
1,592
enigma8-android
MIT License
app/src/main/java/com/ieeevit/enigma8/view/privacy/PrivacyActivity.kt
IEEE-VIT
403,345,348
false
{"Kotlin": 288926}
package com.ieeevit.enigma8.view.privacy import android.content.Intent import android.graphics.LinearGradient import android.graphics.Shader import android.os.Bundle import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.ieeevit.enigma8.R import com.ieeevit.enigma8.view.instruction.InstructionActivity import com.ieeevit.enigma8.view.notification.NotificationActivity import com.ieeevit.enigma8.view.profile.Profdashboard import com.ieeevit.enigma8.view.rooms.RoomsActvity class PrivacyActivity:AppCompatActivity() { private lateinit var back: ImageView private lateinit var instruction: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.privacy_policy) val heading : TextView = findViewById<EditText>(R.id.privacy_policy) val shader1 : Shader= LinearGradient(0f, 0f,0f,heading.lineHeight.toFloat(), intArrayOf(this.getColor(R.color.light_yellow), this.getColor(R.color.dark_yellow)), floatArrayOf(0.3f,0.7f),Shader.TileMode.REPEAT) heading.paint.shader = shader1 back = findViewById(R.id.back_btn) instruction = findViewById(R.id.instruction) back.setOnClickListener { val intent = Intent(this, Profdashboard::class.java) startActivity(intent) } instruction.setOnClickListener { val intent = Intent(this, InstructionActivity::class.java) startActivity(intent) } } }
0
Kotlin
1
8
fbb071f350e22ea6346b8e6773c5c83cfd7b0971
1,592
enigma8-android
MIT License
codegen/src/main/java/com/levinzonr/saferoute/codegen/models/RouteData.kt
levinzonr
372,225,040
false
null
package com.levinzonr.saferoute.codegen.models import com.levinzonr.saferoute.codegen.constants.ClassNames import com.levinzonr.saferoute.codegen.constants.Constants import com.levinzonr.saferoute.codegen.core.Source import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName data class RouteData( val name: String, val arguments: List<ArgumentData>, val packageName: String, val deeplinks: List<DeeplinkData>, val routeTransitionType: Any?, private val routeTransitionClassName: String?, val contentName: String, val params: List<String>, val navGraphName: String, val start: Boolean, val source: Source ) { val routeTransitionClass get() = routeTransitionClassName?.let { ClassName( packageName = it.split(".").dropLast(1).joinToString("."), simpleNames = listOf(it.split(".").last()) ) } val argsPackageName = packageName + "." + Constants.FILE_ARGS_DIR val specName: String get() = "${name.capitalize()}Route" val specClassName = ClassName(packageName, specName) val argumentsName: String get() = "${name.capitalize()}${Constants.FILE_ARGS_POSTFIX}" val argumentsClassName = ClassName(argsPackageName, argumentsName) val argsFactoryClassName = if (arguments.isEmpty()) ClassNames.EmptyArgsFactory else ClassName(argsPackageName, getArgsFactoryName()) val argsTypeClassName = if (arguments.isEmpty()) ClassName("kotlin", "Unit") else ClassName( argsPackageName, argumentsName ) val contentClassName = ClassName(packageName, contentName) val routeClassName = ClassName( packageName, "${name.capitalize()}Route" ) val routeSpecClassName: TypeName get() { return ClassNames.RouteSpec.parameterizedBy(argsTypeClassName) } val argumentsConstructor: String get() = "$argumentsName(${arguments.joinToString { it.name }})" val builderName: String = "${name.decapitalize()}" fun getArgsFactoryName(): String { return "$argumentsName${Constants.FILE_ROUTE_ARG_FACTORY}" } }
4
Kotlin
0
59
8d65e08c2aa5dbe3d0f829e605887e42f36dcd85
2,244
compose-safe-routing
Apache License 2.0
app/src/main/java/com/wang/kotlindemo/mdoel/TextModel.kt
kingwang666
93,376,609
false
null
package com.wang.kotlindemo.mdoel /** * Created on 2017/5/27. * Author: wang */ data class TextMode(var clazz: Class<out Any>, var name: String = "test"){ }
0
Kotlin
0
0
68b14e50db49d942693ba1beab5c8307f24b3f81
162
KotlinLearn
Apache License 2.0
app/src/main/java/br/com/renancsdev/avenuecodeeventos/extension/String.kt
RenanCostaSilva
775,714,533
false
{"Kotlin": 27190}
package br.com.renancsdev.avenuecodeeventos.extension import android.content.Context import android.util.Log import android.widget.Toast import java.text.SimpleDateFormat import java.util.Date fun String.toastCurto(context: Context) { return Toast.makeText(context , this, Toast.LENGTH_SHORT).show() } fun String.toastLongo(context: Context) { return Toast.makeText(context , this , Toast.LENGTH_LONG).show() } fun String.loeE(metodo: String): Int{ return Log.e(metodo , this) }
1
Kotlin
0
0
fd9c60d148485dc4385ce35e81cab3b9881abe10
499
AvenueCodeEvento
Apache License 2.0
plugins/network/ktor-no-op/src/main/kotlin/ir/amirab/debugboard/plugin/network/ktor/KtorToDebugBoard.kt
amir1376
606,913,822
false
null
package ir.amirab.debugboard.plugin.network.ktor import io.ktor.client.* import io.ktor.client.plugins.* import io.ktor.util.* import ir.amirab.debugboard.core.DebugBoard class KtorDebugBoard private constructor() { companion object : HttpClientPlugin<Config, KtorDebugBoard> { override val key: AttributeKey<KtorDebugBoard> = AttributeKey("DebugBoard") override fun prepare(block: Config.() -> Unit): KtorDebugBoard { return KtorDebugBoard() } override fun install(plugin: KtorDebugBoard, scope: HttpClient) {} } } @KtorDsl class Config internal constructor() { var debugBoard: DebugBoard = DebugBoard.Default }
0
Kotlin
1
17
26928c50831f6cdcc884e5bbf2d725abc06bff9e
673
debugboard
Apache License 2.0
platform/src/main/kotlin/com/samsung/healthcare/platform/adapter/persistence/project/healthdata/HeightRepository.kt
S-HealthStack
520,365,362
false
{"Kotlin": 894766, "Dockerfile": 1358, "ANTLR": 1066}
package com.samsung.healthcare.platform.adapter.persistence.project.healthdata import com.samsung.healthcare.platform.adapter.persistence.entity.project.healthdata.HeightEntity interface HeightRepository : SampleDataRepository<HeightEntity>
2
Kotlin
7
28
b7e7d0b4cc8d1f1123c9f3bd08fa5cc66fbc9920
243
backend-system
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/MugHotAlt.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.MugHotAlt: ImageVector get() { if (_mugHotAlt != null) { return _mugHotAlt!! } _mugHotAlt = Builder(name = "MugHotAlt", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.025f, 3.0f) lineTo(13.025f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f) lineTo(15.025f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, true, 13.025f, 3.0f) close() moveTo(10.025f, 4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f) lineTo(11.025f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -2.0f, 0.0f) lineTo(9.025f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, false, 10.025f, 4.0f) close() moveTo(6.025f, 4.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f) lineTo(7.025f, 1.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -2.0f, 0.0f) lineTo(5.025f, 3.0f) arcTo(1.0f, 1.0f, 0.0f, false, false, 6.025f, 4.0f) close() moveTo(24.0f, 13.143f) arcTo(3.983f, 3.983f, 0.0f, false, true, 20.0f, 17.0f) lineTo(17.525f, 17.0f) arcToRelative(6.875f, 6.875f, 0.0f, false, true, -5.742f, 3.0f) lineTo(8.216f, 20.0f) arcToRelative(6.877f, 6.877f, 0.0f, false, true, -5.808f, -3.088f) curveTo(0.992f, 14.653f, -2.453f, 6.371f, 3.0f, 6.0f) lineTo(17.0f, 6.0f) arcToRelative(3.1f, 3.1f, 0.0f, false, true, 2.882f, 4.0f) curveTo(22.353f, 10.0f, 24.0f, 11.205f, 24.0f, 13.143f) close() moveTo(22.0f, 13.143f) curveToRelative(0.088f, -0.927f, -1.25f, -1.224f, -2.458f, -1.143f) arcToRelative(16.82f, 16.82f, 0.0f, false, true, -0.954f, 3.0f) lineTo(20.0f, 15.0f) arcTo(1.984f, 1.984f, 0.0f, false, false, 22.0f, 13.143f) close() moveTo(19.0f, 22.0f) lineTo(1.0f, 22.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f) lineTo(19.0f, 24.0f) arcTo(1.0f, 1.0f, 0.0f, false, false, 19.0f, 22.0f) close() } } .build() return _mugHotAlt!! } private var _mugHotAlt: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,444
icons
MIT License
particleview/core/src/main/java/com/oscarliang/particleview/core/ParticleSystem.kt
iamoscarliang
809,386,777
false
{"Kotlin": 28821}
package com.oscarliang.particleview.core import android.graphics.Canvas import com.oscarliang.particleview.core.model.FloatOffset import com.oscarliang.particleview.core.model.IntOffset import kotlin.random.Random class ParticleSystem( val images: List<ParticleImage>, val startX: FloatOffset, val startY: FloatOffset, val speed: FloatOffset, val accelX: FloatOffset, val accelY: FloatOffset, val angle: IntOffset, val rotation: IntOffset, val rotationSpeed: FloatOffset, val particleDuration: Long, val particleFadeOutDuration: Long, val particlePerSecond: Int, val duration: Long, val density: Float ) { var width: Int = 0 var height: Int = 0 private val particles = mutableListOf<Particle>() private val particlesPool = mutableListOf<Particle>() private val particlesToRemove = mutableListOf<Particle>() private var current = 0L fun update(currentMillis: Long, elapsedMillis: Long) { val durationPerParticle = particleDuration + particleFadeOutDuration if (currentMillis < duration - durationPerParticle) { val millisPerParticle = 1000 / particlePerSecond current += elapsedMillis if (current >= millisPerParticle) { particles.add(getOneParticle()) current = 0 } } particles.forEach { particle -> particle.update(elapsedMillis) } // Remove the particle after updating // to prevent index out of bounds, and // recycle the particles being removed particles.removeAll(particlesToRemove) particlesPool.addAll(particlesToRemove) particlesToRemove.clear() } fun draw(canvas: Canvas) { particles.forEach { particle -> particle.draw(canvas) } } fun release() { particles.clear() particlesPool.clear() particlesToRemove.clear() } fun getParticleAt(x: Float, y: Float): Particle? { particles.forEach { particle -> if (particle.isInBound(x, y)) { return particle } } return null } private fun getOneParticle() = if (particlesPool.isNotEmpty()) { val particle = particlesPool.removeAt(0) particle.reset() particle } else { Particle( image = images[Random.nextInt(images.size)], startXMin = startX.startValue * width, startXMax = startX.endValue * width, startYMin = startY.startValue * height, startYMax = startY.endValue * height, speedMin = speed.startValue, speedMax = speed.endValue, accelXMin = accelX.startValue, accelXMax = accelX.endValue, accelYMin = accelY.startValue, accelYMax = accelY.endValue, angleMin = angle.startValue, angleMax = angle.endValue, rotationMin = rotation.startValue, rotationMax = rotation.endValue, rotationSpeedMin = rotationSpeed.startValue, rotationSpeedMax = rotationSpeed.endValue, duration = particleDuration, fadeOutDuration = particleFadeOutDuration, onParticleEnd = { particlesToRemove.add(it) }, density = density ) } }
0
Kotlin
0
3
d2eaeca0fc27d5c76c1aacef172dc05080a768ef
3,499
particleview
MIT License
kazuki-ksp/src/main/kotlin/com/anaplan/engineering/kazuki/ksp/SequenceType.kt
anaplan-engineering
715,012,365
false
{"Kotlin": 160848, "Shell": 827}
package com.anaplan.engineering.kazuki.ksp import com.anaplan.engineering.kazuki.core.* import com.anaplan.engineering.kazuki.core.internal._KSequence import com.google.devtools.ksp.KspExperimental import com.google.devtools.ksp.isAbstract import com.google.devtools.ksp.isAnnotationPresent import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.ksp.toClassName import com.squareup.kotlinpoet.ksp.toTypeName import com.squareup.kotlinpoet.ksp.toTypeParameterResolver import com.squareup.kotlinpoet.ksp.toTypeVariableName internal fun TypeSpec.Builder.addSeqType( interfaceClassDcl: KSClassDeclaration, processingState: KazukiSymbolProcessor.ProcessingState, ) = addSequenceType(interfaceClassDcl, processingState, false) internal fun TypeSpec.Builder.addSeq1Type( interfaceClassDcl: KSClassDeclaration, processingState: KazukiSymbolProcessor.ProcessingState, ) = addSequenceType(interfaceClassDcl, processingState, true) @OptIn(KspExperimental::class) private fun TypeSpec.Builder.addSequenceType( interfaceClassDcl: KSClassDeclaration, processingState: KazukiSymbolProcessor.ProcessingState, requiresNonEmpty: Boolean ) { val interfaceName = interfaceClassDcl.simpleName.asString() val interfaceTypeArguments = interfaceClassDcl.typeParameters.map { it.toTypeVariableName() } val interfaceTypeName = if (interfaceTypeArguments.isEmpty()) { interfaceClassDcl.toClassName() } else { interfaceClassDcl.toClassName().parameterizedBy(interfaceTypeArguments) } val interfaceTypeParameterResolver = interfaceClassDcl.typeParameters.toTypeParameterResolver() val properties = interfaceClassDcl.declarations.filterIsInstance<KSPropertyDeclaration>() val functionProviderProperties = properties.filter { it.isAnnotationPresent(FunctionProvider::class) } if ((properties - functionProviderProperties).filter { it.isAbstract() }.firstOrNull() != null) { val propertyNames = properties.map { it.simpleName.asString() }.toList() processingState.errors.add("Sequence type $interfaceTypeName may not have properties: $propertyNames") } val superInterface = if (requiresNonEmpty) Sequence1::class else Sequence::class val seqType = interfaceClassDcl.allSuperTypes().single { it.resolve().declaration.qualifiedName?.asString() == superInterface.qualifiedName } .resolve() val elementType = seqType.arguments.single().type!!.resolve() val elementTypeName = elementType.toTypeName(interfaceTypeParameterResolver) val elementsPropertyName = "elements" val enforceInvariantParameterName = "enforceInvariant" val superListTypeName = List::class.asClassName().parameterizedBy(elementTypeName) val suffix = if (requiresNonEmpty) "Seq1" else "Seq" val implClassName = "${interfaceName}_$suffix" val implTypeSpec = TypeSpec.classBuilder(implClassName).apply { if (interfaceTypeArguments.isNotEmpty()) { addTypeVariables(interfaceTypeArguments) } addModifiers(KModifier.PRIVATE) addSuperinterface(interfaceTypeName) addSuperinterface(_KSequence::class.asClassName().parameterizedBy(elementTypeName, interfaceTypeName)) addSuperinterface(superListTypeName, CodeBlock.of(elementsPropertyName)) addSuperclassConstructorParameter(elementsPropertyName) primaryConstructor(FunSpec.constructorBuilder() .addParameter(elementsPropertyName, superListTypeName) .addParameter(ParameterSpec.builder(enforceInvariantParameterName, Boolean::class).defaultValue("true") .build()) .build() ) addProperty( PropertySpec.builder(elementsPropertyName, superListTypeName, KModifier.OPEN, KModifier.OVERRIDE) .initializer(elementsPropertyName).build() ) val lenPropertyName = "len" addProperty(PropertySpec.builder(lenPropertyName, nat::class.asTypeName()).addModifiers(KModifier.OVERRIDE) .delegate("$elementsPropertyName::size").build()) val correspondingSetInterface = if (requiresNonEmpty) Set1::class else Set::class val correspondingSetConstructor = if (requiresNonEmpty) InbuiltNames.asSet1 else InbuiltNames.asSet addProperty(PropertySpec.builder("elems", correspondingSetInterface.asClassName().parameterizedBy(elementTypeName)) .addModifiers( KModifier.OVERRIDE) .lazy("%M(%N)", correspondingSetConstructor, elementsPropertyName).build()) addProperty(PropertySpec.builder("inds", correspondingSetInterface.asClassName().parameterizedBy(nat1::class.asClassName())) .addModifiers( KModifier.OVERRIDE) .lazy("%M(1 .. len)", correspondingSetConstructor).build()) addFunctionProviders(functionProviderProperties, interfaceTypeParameterResolver) // N.B. it is important to have properties before init block // TODO -- should we get this from super interface -- Sequence1.atLeastOneElement() val additionalInvariantParts = if (requiresNonEmpty) listOf("len > 0") else emptyList() addInvariantFrom(interfaceClassDcl, false, enforceInvariantParameterName, processingState, additionalInvariantParts) addFunction( FunSpec.builder("construct").apply { addModifiers(KModifier.OVERRIDE) addParameter(elementsPropertyName, superListTypeName) returns(interfaceTypeName) addStatement("return %N(%N)", implClassName, elementsPropertyName) }.build() ) addFunction( FunSpec.builder("get").apply { val indexParameterName = "index" addModifiers(KModifier.OVERRIDE, KModifier.OPERATOR) addParameter(ParameterSpec.builder(indexParameterName, nat1::class.asTypeName()).build()) returns(elementTypeName) addCode(CodeBlock.builder().apply { beginControlFlow("if (%N < 1 || %N > %N)", indexParameterName, indexParameterName, lenPropertyName) addStatement("throw %T()", PreconditionFailure::class) endControlFlow() addStatement("return %N.get(%N - 1)", elementsPropertyName, indexParameterName) }.build()) }.build() ) addFunction( FunSpec.builder("indexOf").apply { val elementParameterName = "element" addModifiers(KModifier.OVERRIDE) addParameter(ParameterSpec.builder(elementParameterName, elementTypeName).build()) returns(nat1::class.asTypeName()) addCode(CodeBlock.builder().apply { beginControlFlow("if (%N !in %N)", elementParameterName, elementsPropertyName) addStatement("throw %T()", PreconditionFailure::class) endControlFlow() addStatement("return %N.indexOf(%N) + 1", elementsPropertyName, elementParameterName) }.build()) }.build() ) addFunction( FunSpec.builder("lastIndexOf").apply { val elementParameterName = "element" addModifiers(KModifier.OVERRIDE) addParameter(ParameterSpec.builder(elementParameterName, elementTypeName).build()) returns(nat1::class.asTypeName()) addCode(CodeBlock.builder().apply { beginControlFlow("if (%N !in %N)", elementParameterName, elementsPropertyName) addStatement("throw %T()", PreconditionFailure::class) endControlFlow() addStatement("return %N.lastIndexOf(%N) + 1", elementsPropertyName, elementParameterName) }.build()) }.build() ) addFunction(FunSpec.builder("toString").addModifiers(KModifier.OVERRIDE) .returns(String::class) .addStatement("return \"%N\$%N\"", interfaceName, elementsPropertyName) .build()) addFunction(FunSpec.builder("hashCode").addModifiers(KModifier.OVERRIDE) .returns(Int::class).addStatement("return %N.hashCode()", elementsPropertyName).build()) val equalsParameterName = "other" addFunction(FunSpec.builder("equals").addModifiers(KModifier.OVERRIDE) .addParameter(ParameterSpec.builder(equalsParameterName, Any::class.asTypeName().copy(nullable = true)) .build()) .returns(Boolean::class).addCode(CodeBlock.builder().apply { beginControlFlow("if (this === %N)", equalsParameterName) addStatement("return true") endControlFlow() beginControlFlow("if (%N !is %T)", equalsParameterName, superInterface.asTypeName().parameterizedBy( STAR)) addStatement("return false") endControlFlow() addStatement("return %N == %N", elementsPropertyName, equalsParameterName) }.build()).build()) }.build() addType(implTypeSpec) addFunction( FunSpec.builder("mk_$interfaceName").apply { if (interfaceTypeArguments.isNotEmpty()) { addTypeVariables(interfaceTypeArguments) } addParameter(elementsPropertyName, superListTypeName) returns(interfaceTypeName) addStatement("return %N(%N)", implTypeSpec, elementsPropertyName) }.build() ) addFunction( FunSpec.builder("mk_$interfaceName").apply { if (interfaceTypeArguments.isNotEmpty()) { addTypeVariables(interfaceTypeArguments) } addParameter(elementsPropertyName, elementTypeName, KModifier.VARARG) returns(interfaceTypeName) addStatement("return %N(%N.toList())", implTypeSpec, elementsPropertyName) }.build() ) addFunction( FunSpec.builder("is_$interfaceName").apply { if (interfaceTypeArguments.isNotEmpty()) { addTypeVariables(interfaceTypeArguments) } addParameter(elementsPropertyName, superListTypeName) returns(Boolean::class) addStatement("return %N(%N, false).%N()", implClassName, elementsPropertyName, validityFunctionName) }.build() ) addFunction( FunSpec.builder("as_$interfaceName").apply { if (interfaceTypeArguments.isNotEmpty()) { addTypeVariables(interfaceTypeArguments) } addParameter(elementsPropertyName, superListTypeName) returns(interfaceTypeName) addStatement("return %N(%N)", "mk_$interfaceName", elementsPropertyName) }.build() ) }
0
Kotlin
0
0
1853cc4d36f47d143d27624fa9d9e3e17fce4ddb
11,136
kazuki
MIT License
app/src/main/java/com/swayy/musicpark/domain/use_cases/GetGenreUseCase.kt
gideonrotich
557,405,183
false
{"Kotlin": 274873}
package com.swayy.musicpark.domain.use_cases import com.swayy.musicpark.domain.models.Genre import com.swayy.musicpark.domain.repository.GenreRepository import com.swayy.musicpark.util.Resource import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetGenreUseCase @Inject constructor( private val repository: GenreRepository ) { operator fun invoke():Flow<Resource<List<Genre>>>{ return repository.getGenre() } }
0
Kotlin
6
58
aa7ce4d7d4481a76b28de61a82d27958f92192d0
449
MusicPark
MIT License
app/src/main/java/com/jirawat/bddexample/BddExampleApplication.kt
tententen2
137,557,700
false
{"Kotlin": 36736}
package com.jirawat.bddexample import android.app.Application import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication open class BddExampleApplication:Application(){ // override fun applicationInjector(): AndroidInjector<out DaggerApplication> = DaggerAppComponent.builder().create(this) }
2
Kotlin
1
1
039cb7f4f6dda3c059ba6bc6a87bb12a585d5c5f
326
BDDExample
MIT License
app/src/main/java/com/dreamsoftware/inquize/di/PreferencesModule.kt
sergio11
189,729,405
false
{"Kotlin": 288983}
package com.dreamsoftware.inquize.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStore import com.dreamsoftware.inquize.data.local.preferences.datasource.IPreferencesDataSource import com.dreamsoftware.inquize.data.local.preferences.datasource.impl.PreferencesDataSourceImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class PreferencesModule { private companion object { @JvmStatic val DATA_STORE_NAME = "DATA_STORE" } /** * Provide Data Store * @param context */ @Singleton @Provides fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> = preferencesDataStore(name = DATA_STORE_NAME).getValue(context, String::javaClass) /** * Provide Preference DataSource * @param dataStore * @param dispatcher */ @Singleton @Provides fun providePreferenceDataSource( dataStore: DataStore<Preferences>, @IoDispatcher dispatcher: CoroutineDispatcher ): IPreferencesDataSource = PreferencesDataSourceImpl(dataStore, dispatcher) }
0
Kotlin
0
1
062ac9c8a942148d0008d2043d02db62ff964841
1,469
inquize_android
The Unlicense
app/src/main/java/com/example/myapplication/global/AppApplication.kt
techtamper
350,005,912
false
null
package com.example.myapplication.global import android.app.Application import android.content.res.Resources import com.example.myapplication.global.koin.appModule import com.example.myapplication.global.koin.repoModule import com.example.myapplication.global.koin.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.module.Module class AppApplication : Application() { companion object { lateinit var res: Resources } override fun onCreate() { super.onCreate() res = resources // context = this startKoin { androidLogger() androidContext(this@AppApplication) modules(getModule()) } } private fun getModule(): List<Module> { return listOf( appModule, viewModelModule, repoModule ) } }
0
Kotlin
0
0
74a89ee05f6ea02d20f12c1de481934cfccca48b
968
ProjectWithFlavor
Apache License 2.0
android-buddy-plugin/src/test/java/com/likethesalad/android/common/utils/android/AndroidVariantDataProviderTest.kt
LikeTheSalad
289,290,234
false
null
package com.likethesalad.android.common.utils.android import com.android.build.gradle.AppExtension import com.android.build.gradle.api.ApplicationVariant import com.android.builder.model.BuildType import com.android.builder.model.ProductFlavor import com.google.common.truth.Truth import com.likethesalad.android.common.utils.Logger import com.likethesalad.android.testutils.BaseMockable import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.verify import org.gradle.api.DomainObjectSet import org.gradle.api.tasks.TaskProvider import org.gradle.api.tasks.compile.JavaCompile import org.junit.Before import org.junit.Test class AndroidVariantDataProviderTest : BaseMockable() { @MockK lateinit var androidAppExtension: AppExtension @MockK lateinit var androidExtensionDataProvider: AndroidExtensionDataProvider @MockK lateinit var androidVariantPathResolverFactory: AndroidVariantPathResolverFactory @MockK lateinit var logger: Logger private val variantName = "someVariantName" private lateinit var androidVariantDataProvider: AndroidVariantDataProvider @Before fun setUp() { androidVariantDataProvider = AndroidVariantDataProvider( androidExtensionDataProvider, androidVariantPathResolverFactory, logger, variantName ) } @Test fun `Get variant java target compatibility version`() { createAndSetMainVariantMock() val javaCompileProvider = mockk<TaskProvider<JavaCompile>>() val javaCompile = mockk<JavaCompile>() val targetCompatibility = "1.7" val variant = createAndSetMainVariantMock("otherName") every { javaCompileProvider.hint(JavaCompile::class).get() }.returns(javaCompile) every { javaCompile.targetCompatibility }.returns(targetCompatibility) every { variant.javaCompileProvider }.returns(javaCompileProvider) val result = androidVariantDataProvider.getJavaTargetCompatibilityVersion() Truth.assertThat(result).isEqualTo(7) verify { logger.info("Using java target version {}", 7) } } @Test fun `Get variant path`() { val variant = createAndSetMainVariantMock() val flavorName = "someFlavorName" val androidVariantPathResolver = mockk<AndroidVariantPathResolver>() val buildType = mockk<BuildType>() val buildTypeName = "someBuildTypeName" val flavor1 = mockk<ProductFlavor>() val flavor2 = mockk<ProductFlavor>() val flavorName1 = "someFlavor" val flavorName2 = "anotherFlavor" val flavors = listOf(flavor1, flavor2) val expectedPath = listOf("some", "path") every { flavor1.name }.returns(flavorName1) every { flavor2.name }.returns(flavorName2) every { variant.flavorName }.returns(flavorName) every { variant.buildType }.returns(buildType) every { buildType.name }.returns(buildTypeName) every { variant.productFlavors }.returns(flavors) every { androidVariantPathResolverFactory.create( variantName, flavorName, buildTypeName, listOf(flavorName1, flavorName2) ) }.returns(androidVariantPathResolver) every { androidVariantPathResolver.getTopBottomPath() }.returns(expectedPath) val result = androidVariantDataProvider.getVariantPath() Truth.assertThat(result).isEqualTo(expectedPath) } private fun getVariantsIterator( chosen: ApplicationVariant?, vararg variantNames: String ): MutableIterator<ApplicationVariant> { val list = mutableListOf<ApplicationVariant>() if (chosen != null) { list.add(chosen) } val others = variantNames.map { createApplicationVariantMock(it) } list.addAll(others) return list.listIterator() } private fun createApplicationVariantMock(name: String): ApplicationVariant { val mock = mockk<ApplicationVariant>() every { mock.name }.returns(name) return mock } private fun createAndSetMainVariantMock(vararg otherVariantNames: String): ApplicationVariant { val appVariants = mockk<DomainObjectSet<ApplicationVariant>>() val variant = createApplicationVariantMock(variantName) every { androidExtensionDataProvider.getVariantByName(variantName) }.returns(variant) every { androidAppExtension.applicationVariants }.returns(appVariants) every { appVariants.iterator() }.returns(getVariantsIterator(variant, *otherVariantNames)) return variant } }
0
Kotlin
6
43
1089f89e1f8ad5fb9fdfb9195592cc8a7d04e299
4,730
android-buddy
MIT License
kmm_decompose_sample/shared/src/commonMain/kotlin/com/decompose/components/document_list/DocumentList.kt
vladlen2010
444,197,061
false
{"Kotlin": 144652, "Swift": 43044, "Ruby": 3488}
package com.decompose.components.document_list import com.arkivanov.decompose.value.Value interface DocumentList { val model: Value<Model> fun onItemClicked(itemId: String) data class Model( val documents: List<Document> = emptyList() ) } data class Document( //TODO: transfer to domain layer val id: String, val title: String )
0
Kotlin
0
0
c081daab714d85e73f639b46286e2b587d77aed8
367
kmm-samples
Apache License 2.0
compiler/src/main/java/lang/taxi/query/TaxiQlQuery.kt
taxilang
601,101,781
false
{"Kotlin": 1691489, "ANTLR": 66160, "TypeScript": 12542, "JavaScript": 4324, "Shell": 1468, "Java": 1454, "MDX": 425}
package lang.taxi.query import lang.taxi.accessors.ProjectionFunctionScope import lang.taxi.mutations.Mutation import lang.taxi.types.Annotatable import lang.taxi.types.Annotation import lang.taxi.types.ArrayType import lang.taxi.types.Arrays import lang.taxi.types.CompilationUnit import lang.taxi.types.Compiled import lang.taxi.types.Documented import lang.taxi.types.ObjectType import lang.taxi.types.QualifiedName import lang.taxi.types.Type data class TaxiQlQuery( val name: QualifiedName, val facts: List<Parameter>, val queryMode: QueryMode, val parameters: List<Parameter>, val typesToFind: List<DiscoveryType>, val projectedType: Type?, val projectionScopeVars: List<ProjectionFunctionScope>, val mutation: Mutation?, override val typeDoc: String?, override val annotations: List<Annotation>, override val compilationUnits: List<CompilationUnit> ) : Documented, Annotatable, Compiled { val source:TaxiQLQueryString = compilationUnits.joinToString("\n") { it.source.content } /** * If the return type is a collection, returns * the member type. Otherwise the actual return type is returned. */ val unwrappedReturnType: Type get() { return Arrays.unwrapPossibleArrayType(returnType) } val returnType: Type get() { return when { mutation != null -> mutation.operation.returnType projectedObjectType != null -> projectedObjectType!! else -> { typesToFind.singleOrNull()?.anonymousType ?: typesToFind.singleOrNull()?.type ?: error("Could not infer return type of query.") } } } val projectedObjectType: ObjectType? get() { return when (projectedType) { null -> null is ArrayType -> projectedType.type as ObjectType is ObjectType -> projectedType else -> { error("Cannot cast ${projectedType::class.simpleName} to ObjectType") } } } }
8
Kotlin
5
74
345f97596db7ef871cf0c28997f4effe9da0bccf
2,063
taxilang
Apache License 2.0