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
universities/src/main/java/com/mowael/universities/presentation/UniversitiesViewModel.kt
MohamedWael
795,798,784
false
{"Kotlin": 33243}
package com.mowael.universities.presentation import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mowael.universities.domain.UniversitiesUseCase import kotlinx.coroutines.launch import javax.inject.Inject class UniversitiesViewModel @Inject constructor( private val useCase: UniversitiesUseCase ) : ViewModel() { private val _universitiesLiveData = MutableLiveData<UniversitiesState>() val universitiesLiveData: LiveData<UniversitiesState> = _universitiesLiveData init { getUniversities() } fun getUniversities() = viewModelScope.launch { _universitiesLiveData.value = UniversitiesState.Loading try { _universitiesLiveData.value = UniversitiesState.Success(useCase.getUniversities()) } catch (e: Throwable) { _universitiesLiveData.value = UniversitiesState.Error(e) } } }
0
Kotlin
0
0
bf44605ef07dd175d200eea59af85472fc45e610
982
UAE-Universties
MIT License
NaturalExpress/app/src/main/java/com/naturalexpress/ui/requests/RequestsViewModel.kt
glrmeslp
452,785,559
false
null
package com.naturalexpress.ui.requests import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class RequestsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is dashboard Fragment" } val text: LiveData<String> = _text }
0
Kotlin
1
0
fae757f98eb4c2cbffe12546becb5c31921b8d5c
344
NaturalExpressAndroid
MIT License
src/main/kotlin/biz/lermitage/sub/service/checker/impl/Adoptium11LinuxChecker.kt
jonathanlermitage
262,889,547
false
{"Kotlin": 65831, "Shell": 1357, "Batchfile": 1172}
package biz.lermitage.sub.service.checker.impl import biz.lermitage.sub.service.checker.Checker import org.springframework.stereotype.Service @Service class Adoptium11LinuxChecker : AdoptiumChecker(11, "linux", "jdk", "x64"), Checker
0
Kotlin
3
5
f9c32684cd268a09c554348df45d6bdb9dc43073
236
software-updates-bot
MIT License
app/src/main/java/nodomain/freeyourgadget/fossilnotify/activity/MainActivity.kt
alexbilevskiy
622,469,193
false
null
package nodomain.freeyourgadget.fossilnotify.activity import android.Manifest import android.content.ComponentName import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.provider.Settings import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging import nodomain.freeyourgadget.fossilnotify.service.* import nodomain.freeyourgadget.fossilnotify.service.NLService.Companion.INTENT_FILTER_ACTION import nodomain.freeyourgadget.fossilnotify.service.NLService.Companion.INTENT_FILTER_GB import nodomain.freeyourgadget.fossilnotify.ui.screens.MainScreen import nodomain.freeyourgadget.fossilnotify.ui.theme.NotificationListenerExampleTheme import nodomain.freeyourgadget.fossilnotify.ui.view_model.ViewModel class MainActivity : ComponentActivity() { companion object { const val TAG = "MainActivity" } private val viewModel = ViewModel() private lateinit var nService: NotificationService private lateinit var iService: GBService private lateinit var nReceiver: NotificationReceiver private lateinit var iReceiver: GBReceiver private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { Toast.makeText(applicationContext,"App is allowed to show notifications",Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext,"App is NOT allowed to show notifications!",Toast.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) nService = NotificationService(applicationContext) iService = GBService(applicationContext) nReceiver = NotificationReceiver(viewModel) iReceiver = GBReceiver(viewModel, iService) val filterN = IntentFilter(INTENT_FILTER_ACTION) val filterG = IntentFilter(INTENT_FILTER_GB) registerReceiver(nReceiver, filterN) registerReceiver(iReceiver, filterG) askPermission() askNotificationPermission() fcnToken() setContent { NotificationListenerExampleTheme { MainScreen( text = viewModel.text, onClickClearAll = { viewModel.clearAllNotifications(this) }, onClickCreateNotify = { nService.showNotification() }, onClickList = { viewModel.listNotifications(this) }, onClickCount = { viewModel.countNotifications(this) } ) } } } override fun onDestroy() { super.onDestroy() unregisterReceiver(nReceiver) } private fun askPermission() { val cn = ComponentName(applicationContext, NLService::class.java) val flat: String = Settings.Secure.getString(contentResolver, "enabled_notification_listeners") val enabled = flat.contains(cn.flattenToString()) if (!enabled) { val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS") startActivity(intent) } } private fun askNotificationPermission() { // This is only necessary for API level >= 33 (TIRAMISU) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED ) { // FCM SDK (and your app) can post notifications. } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) { // TODO: display an educational UI explaining to the user the features that will be enabled // by them granting the POST_NOTIFICATION permission. This UI should provide the user // "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission. // If the user selects "No thanks," allow the user to continue without notifications. requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) // temp } else { // Directly ask for the permission requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } } } private fun fcnToken() { FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // Get new FCM registration token val token = task.result Log.d(TAG, "FCM Token: $token") }) } }
0
Kotlin
0
0
b7e48066e8251dafb516ef15062c36cadae6ba04
5,409
fossilnotify
Apache License 2.0
src/main/kotlin/org/jetbrains/plugins/bsp/protocol/connection/BspConnectionDetailsGenerator.kt
JetBrains
521,228,542
false
null
package org.jetbrains.plugins.bsp.protocol.connection import com.intellij.idea.LoggerFactory import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.vfs.VirtualFile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.plugins.bsp.flow.open.wizard.ConnectionFileOrNewConnection import org.jetbrains.plugins.bsp.flow.open.wizard.ImportProjectWizardStep import org.jetbrains.plugins.bsp.services.BspCoroutineService import org.jetbrains.plugins.bsp.utils.withRealEnvs import java.io.OutputStream import java.nio.file.Path public interface BspConnectionDetailsGenerator { public fun executeAndWait(command: List<String>, projectPath: VirtualFile, outputStream: OutputStream, log: Logger) { // TODO - consider verbosing what command is being executed val builder = ProcessBuilder(command) .directory(projectPath.toNioPath().toFile()) .withRealEnvs() .redirectError(ProcessBuilder.Redirect.PIPE) val consoleProcess = builder.start() consoleProcess.inputStream.transferTo(outputStream) consoleProcess.logErrorOutputs(log) consoleProcess.waitFor() if (consoleProcess.exitValue() != 0) { error( """An error has occurred when running the command: ${command.joinToString(" ")} |Refer to "${LoggerFactory.getLogFilePath()}" for more information """.trimMargin() ) } } public fun getChild(root: VirtualFile?, path: List<String>): VirtualFile? { val found: VirtualFile? = path.fold(root) { vf: VirtualFile?, child: String -> vf?.refresh(false, false) vf?.findChild(child) } found?.refresh(false, false) return found } public fun id(): String public fun displayName(): String public fun canGenerateBspConnectionDetailsFile(projectPath: VirtualFile): Boolean public fun calculateImportWizardSteps( projectBasePath: Path, connectionFileOrNewConnectionProperty: ObservableMutableProperty<ConnectionFileOrNewConnection> ): List<ImportProjectWizardStep> = emptyList() public fun generateBspConnectionDetailsFile(projectPath: VirtualFile, outputStream: OutputStream): VirtualFile } public class BspConnectionDetailsGeneratorProvider( private val projectPath: VirtualFile, bspConnectionDetailsGenerators: List<BspConnectionDetailsGenerator>, ) { public val availableBspConnectionDetailsGenerators: List<BspConnectionDetailsGenerator> by lazy { bspConnectionDetailsGenerators.filter { it.canGenerateBspConnectionDetailsFile(projectPath) } } public fun canGenerateAnyBspConnectionDetailsFile(): Boolean = availableBspConnectionDetailsGenerators.isNotEmpty() public fun availableGeneratorsNames(): List<String> = availableBspConnectionDetailsGenerators.map { it.id() } public fun calculateWizardSteps( generatorId: String, connectionFileOrNewConnectionProperty: ObservableMutableProperty<ConnectionFileOrNewConnection> ): List<ImportProjectWizardStep> = availableBspConnectionDetailsGenerators .find { it.id() == generatorId } ?.calculateImportWizardSteps(projectPath.toNioPath(), connectionFileOrNewConnectionProperty) .orEmpty() public fun generateBspConnectionDetailFileForGeneratorWithName( generatorId: String, outputStream: OutputStream ): VirtualFile? = availableBspConnectionDetailsGenerators .find { it.id() == generatorId } ?.generateBspConnectionDetailsFile(projectPath, outputStream) } public fun Process.logErrorOutputs(log: Logger) { @Suppress("DeferredResultUnused") BspCoroutineService.getInstance().startAsync { val bufferedReader = this.errorReader() withContext(Dispatchers.IO) { bufferedReader.forEachLine { log.debug(it) } } } }
1
Kotlin
1
6
9205f41486af6062c2efbcb29f2d6d313a53c148
3,833
intellij-bsp
Apache License 2.0
task-domain/src/main/kotlin/cz/kotox/task/domain/api/usecase/GetOneTaskUseCase.kt
kotoMJ
575,403,398
false
null
package cz.kotox.task.domain.api.usecase import cz.kotox.task.data.api.respository.TaskRepository import cz.kotox.task.domain.api.model.Task import cz.kotox.task.domain.api.factory.toTask import javax.inject.Inject class GetOneTaskUseCase @Inject constructor( private val taskRepository: TaskRepository ) { suspend fun execute(taskId: String): Task = taskRepository .getOne(taskId) .toTask() }
0
Kotlin
0
0
c8d2cd3a66c2faea2f5356883aec3ff1690d11eb
438
kotox-android
MIT License
test/src/commonTest/kotlin/com/github/ajalt/clikt/parameters/types/ULongTest.kt
ajalt
128,975,548
false
{"Kotlin": 619429, "Shell": 1858, "Batchfile": 662}
package com.github.ajalt.clikt.parameters.types import com.github.ajalt.clikt.core.BadParameterValue import com.github.ajalt.clikt.core.NoSuchOption import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.testing.TestCommand import com.github.ajalt.clikt.testing.formattedMessage import com.github.ajalt.clikt.testing.parse import io.kotest.assertions.throwables.shouldThrow import io.kotest.data.blocking.forAll import io.kotest.data.row import io.kotest.matchers.shouldBe import kotlin.js.JsName import kotlin.test.Test class ULongTest { @Test @JsName("ulong_option") fun `ulong option`() = forAll( row("", null), row("-x0", 0uL), row("-${ULong.MAX_VALUE}", ULong.MAX_VALUE), ) { argv, expected -> class C : TestCommand() { val x: ULong? by option("-x").ulong(acceptsValueWithoutName = true) override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("ulong_option_error") fun `ulong option error`() { class C : TestCommand(called = false) { @Suppress("unused") val foo by option().ulong() } shouldThrow<BadParameterValue> { C().parse("--foo bar") } .formattedMessage shouldBe "invalid value for --foo: bar is not a valid integer" shouldThrow<NoSuchOption> { C().parse("-2") } shouldThrow<BadParameterValue> { C().parse("--foo=-1") } } @Test @JsName("ulong_option_with_default") fun `ulong option with default`() = forAll( row("", 111uL), row("--xx=4", 4uL), row("-x5", 5uL) ) { argv, expected -> class C : TestCommand() { val x: ULong by option("-x", "--xx").ulong().default(111uL) override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("int_option_with_default") fun `int option with default`() = forAll( row("", 111), row("--xx=4", 4), row("-x5", 5) ) { argv, expected -> class C : TestCommand() { val x: Int by option("-x", "--xx").int().default(111) override fun run_() { x shouldBe expected } } C().parse(argv) } @Test @JsName("ulong_argument") fun `ulong argument`() { class C : TestCommand(treatUnknownOptionsAsArgs = true) { val a by argument().ulong() } C().parse("2").a shouldBe 2uL shouldThrow<BadParameterValue> { C().parse("-1") } } }
9
Kotlin
120
2,520
5593cd0b3645a2862b45ea574b1ae0dcb2e5db91
2,762
clikt
Apache License 2.0
src/main/java/com/protectednet/utilizr/encryption/EncryptionUtils.kt
chicobel
359,753,582
false
{"Kotlin": 97125}
package com.protectednet.utilizr.encryption import android.util.Base64 import android.util.Log import java.io.UnsupportedEncodingException import java.math.BigInteger import java.security.MessageDigest import java.security.NoSuchAlgorithmException import kotlin.experimental.and object EncryptionUtils { fun toSHA1(input: String): String { return try { val md = MessageDigest.getInstance("SHA-1") val messageDigest = md.digest(input.toByteArray()) val no = BigInteger(1, messageDigest) var hashtext = no.toString(16) while (hashtext.length < 32) { hashtext = "0$hashtext" } hashtext } catch (e: NoSuchAlgorithmException) { throw RuntimeException(e) } } fun toSHA256(input: String): String { return try { val md = MessageDigest.getInstance("SHA-256") val messageDigest = md.digest(input.toByteArray()) val no = BigInteger(1, messageDigest) var hashtext = no.toString(16) while (hashtext.length < 32) { hashtext = "0$hashtext" } hashtext } catch (e: NoSuchAlgorithmException) { throw RuntimeException(e) } } fun toSHA512(input: String): String { return try { val md = MessageDigest.getInstance("SHA-512") val messageDigest = md.digest(input.toByteArray()) val no = BigInteger(1, messageDigest) var hashtext = no.toString(16) while (hashtext.length < 32) { hashtext = "0$hashtext" } hashtext } catch (e: NoSuchAlgorithmException) { throw RuntimeException(e) } } fun decodeJwt(jwt: String): String { val result = StringBuilder() val parts = jwt.split(".") try { var index = 0 for (part in parts) { if (index >= 2) break index++ val decodedBytes: ByteArray = Base64.decode(part.toByteArray(charset("UTF-8")), Base64.URL_SAFE) if(index == 1) continue //only interested in the payload bit result.append(String(decodedBytes, charset("UTF-8"))) } } catch (e: Exception) { Log.e("Utils","Couldn't decode jwt", e) } return result.toString() } }
0
Kotlin
0
1
57929f57a1b9d7e3f1bb9c92a85c5d7a62796cc0
2,477
android-kotlin-utilizr
MIT License
app/src/main/java/com/anyandroid/room/Post.kt
dmc0001
601,309,358
false
null
package com.anyandroid.room import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "posts_table") data class Post( val user: User, var title: String, var body: String ) { @PrimaryKey(autoGenerate = true) var id: Int = 0 }
0
Kotlin
0
0
0ee7fe9455b2bf24ee42cd4b831f8746eb0481d8
270
working-with-room
MIT License
projects/mercury-data-extractor/src/main/kotlin/uk/gov/justice/digital/hmpps/mercurydataextractor/controller/SQSController.kt
ministryofjustice
649,658,401
false
null
package uk.gov.justice.digital.hmpps.mercurydataextractor.controller import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.mercurydataextractor.model.upload.UploadNotificationMessage import uk.gov.justice.digital.hmpps.mercurydataextractor.service.SQSService /** * A Rest Controller Class designed to provide a user direct access to the SQS Implementation built into * the SQSService Class * @param sqsService The Service handling interaction with AWS S3 * @param objectMapper A Jackson Object Mapper for Serialization/Deserialization */ @RestController @RequestMapping("/api/v1/sqs") class SQSController( private val sqsService: SQSService, private val objectMapper: ObjectMapper, ) { @GetMapping("/{messageCount}") fun getMessages(@PathVariable messageCount: Int): ResponseEntity<List<String>?> = ResponseEntity.ok( sqsService.receiveMessages(messageCount)?.map { it.body() }, ) @PostMapping fun getS3VariableFile(@RequestBody messageBody: String): ResponseEntity<String> = ResponseEntity.ok(objectMapper.writeValueAsString(sqsService.pushToSqs(messageBody).toBuilder())) @PostMapping("/type") fun pushTypeToS3(@RequestBody uploadNotificationMessage: UploadNotificationMessage): ResponseEntity<String> = ResponseEntity.ok(objectMapper.writeValueAsString(sqsService.pushToSqs(uploadNotificationMessage).toBuilder())) @PostMapping("/delete/{deleteCount}") fun deleteXMessages(@PathVariable deleteCount: Int): ResponseEntity<List<String>> = ResponseEntity.ok( sqsService.deleteXMessages(deleteCount), ) }
1
Kotlin
0
1
fd7e870737f47ecd4b5d7d444cb94936ab5fcc87
2,013
hmpps-mercury-data-monorepo
MIT License
app/src/main/java/namnh/clean/github/GithubApp.kt
namnh-0652
247,247,289
true
null
package namnh.clean.github import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import namnh.clean.github.di.DaggerAppComponent class GithubApp : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> { return DaggerAppComponent.builder().application(this).build() } }
0
null
0
0
d69bdc56e0e032dcb242a1f92e85a1c513ccf799
362
CleanAndroid
Apache License 2.0
src/main/kotlin/training/Lists.kt
CMIRA0906
422,648,545
false
null
package training fun main() { val names= listOf("Cristian","Camilo","Eliecer") println("The firts name is ${names.get(0)}") println("The firts name is ${names[0]}") var subNames = names.subList(1,3) println(subNames) var items = mutableListOf(2,4,6,8,10,10,10,10,14) items[0]=1 items.add(12) items.removeAt(3) items.remove(99) println(items) println("There are ${items.size} items") println("The firts items is ${items.first()} ") }
0
Kotlin
0
0
74185780f9afa65ecaae30ba1e122366d11c569a
488
kotlin_project
Apache License 2.0
cutlass-analyzers/src/test/kotlin/io/strlght/cutlass/analyzers/ToStringAnalyzerTest.kt
strlght
365,810,651
false
null
package io.strlght.cutlass.analyzers import io.strlght.cutlass.test.AnalyzerRule import io.strlght.cutlass.test.assert import org.junit.Rule import org.junit.Test class ToStringAnalyzerTest { @get:Rule val analyzerRule = AnalyzerRule(ToStringAnalyzer::class.java) @Test fun basic() { analyzerRule.analyzer.assert( """ .class public final LToStringBasicTest; .super Ljava/lang/Object; .source "ToStringBasicTest.kt" # instance fields .field private final a:F .field private final b:F # direct methods .method public toString()Ljava/lang/String; .locals 3 new-instance v0, Ljava/lang/StringBuilder; invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V const-string v1, "ToStringBasicTest(coordX=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget v1, p0, LToStringBasicTest;->a:F invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder; const-string v1, ", coordY=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget v1, p0, LToStringBasicTest;->b:F invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder; const-string v1, ")" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v0 return-object v0 .end method """.trimIndent(), mapping = """ ToStringBasicTest -> ToStringBasicTest: float a -> coordX float b -> coordY """.trimIndent() ) } @Test fun className() { analyzerRule.analyzer.assert( """ .class public final La; .super Ljava/lang/Object; # instance fields .field private final a:F .field private final b:F # direct methods .method public toString()Ljava/lang/String; .locals 3 new-instance v0, Ljava/lang/StringBuilder; invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V const-string v1, "ToStringClassName(coordX=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget v1, p0, La;->a:F invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder; const-string v1, ", coordY=" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; iget v1, p0, La;->b:F invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder; const-string v1, ")" invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v0 return-object v0 .end method """.trimIndent(), mapping = """ a -> ToStringClassName: float a -> coordX float b -> coordY """.trimIndent() ) } @Test fun dummyToStringBody() { analyzerRule.analyzer.assert( """ .class public final LToStringEmpty; .super Ljava/lang/Object; .source "ToStringEmpty.kt" # instance fields .field private final a:F .field private final b:F # direct methods .method public toString()Ljava/lang/String; .locals 1 const-string v0, "ToStringEmpty(fake=" return-object v0 .end method """.trimIndent(), mapping = "" ) } }
1
Kotlin
0
4
7658df7b6cb659a760be6883fbf87c531e500627
4,375
cutlass
Apache License 2.0
src/main/kotlin/crdu/demo/events/GenerateTodosActivityReport.kt
CristianDuta
342,874,564
false
null
package crdu.demo.events import org.http4k.events.Event data class GenerateTodosActivityReport( val userId: Int ) : Event
0
Kotlin
0
2
cd3d409aa816e468c770a705c11fd59d4d861519
127
demo-using-fakes
MIT License
shared/presentation/src/commonMain/kotlin/home/HomeComposables.kt
Dragoonov
653,808,838
false
null
package home import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.SnackbarDuration import androidx.compose.material.SnackbarHostState import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.kamel.image.KamelImage import io.kamel.image.asyncPainterResource import kotlinx.coroutines.launch @Composable fun HomeLayout() { MainList() } @Composable fun MainList() { val list = remember { mutableStateListOf( GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), GameListItem( "GTA V", "https://i.wpimg.pl/O/615x346/d.wpimg.pl/544065856--405976119/grand-theft-auto-v-gta-v.jpg" ), ) } LazyColumn { items(list) { ListItem(it) } } } @Composable fun ListItem(item: GameListItem) { val coroutineScope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { KamelImage( modifier = Modifier.width(100.dp).height(100.dp).padding(start = 10.dp), resource = asyncPainterResource(data = item.imageUrl), contentDescription = "Profile", onLoading = { progress -> CircularProgressIndicator(progress) }, onFailure = { exception -> coroutineScope.launch { snackbarHostState.showSnackbar( message = exception.message.toString(), actionLabel = "Hide", duration = SnackbarDuration.Short ) } } ) Text(text = item.title, modifier = Modifier.padding(end = 10.dp)) } }
0
Kotlin
0
0
ee20a5fa999669c280470131f169ffde0a7f994a
4,149
RigPlay
Apache License 2.0
app/src/main/java/com/cactusteam/money/ui/widget/period/ThisYearReportPeriod.kt
miserenkov
184,610,310
false
null
package com.cactusteam.money.ui.widget.period import android.content.Context import com.cactusteam.money.R import com.cactusteam.money.data.period.Period /** * @author vpotapenko */ class ThisYearReportPeriod(context: Context) : BaseReportPeriod(context) { override fun calculatePeriod() { val period = Period.getThisYearPeriod() _startDate = period.first _endDate = period.second } override fun getTitle(): String { return context.getString(R.string.this_year) } }
0
Kotlin
2
0
8350f7e932e0d57496cf9ae2636c6fb8993f9aba
520
moneyapp-android-1
Apache License 2.0
jetbrains-core/src/software/aws/toolkits/jetbrains/utils/execution/steps/Context.kt
Takuya-Miyazaki
332,524,185
true
{"Kotlin": 3225387, "C#": 98047, "Java": 15092, "Dockerfile": 1580}
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.utils.execution.steps import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import software.aws.toolkits.core.utils.AttributeBag import software.aws.toolkits.core.utils.AttributeBagKey import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean /** * Cross step context that exists for the life of a step workflow execution. Keeps track of the global execution state and allows passing data between steps. */ class Context(val project: Project) { val workflowToken = UUID.randomUUID().toString() private val attributeMap = AttributeBag() private val isCancelled: AtomicBoolean = AtomicBoolean(false) fun cancel() { isCancelled.set(true) } fun isCancelled() = isCancelled.get() fun throwIfCancelled() { if (isCancelled()) { throw ProcessCanceledException() } } fun <T : Any> getAttribute(key: AttributeBagKey<T>): T? = attributeMap.get(key) fun <T : Any> getRequiredAttribute(key: AttributeBagKey<T>): T = attributeMap.getOrThrow(key) fun <T : Any> putAttribute(key: AttributeBagKey<T>, data: T) { attributeMap.putData(key, data) } }
7
null
0
0
a1914e27adba3b983feb8b6d8220308ed7602f55
1,353
aws-toolkit-jetbrains
Apache License 2.0
test/src/me/anno/tests/ui/MaterialInSubUI.kt
AntonioNoack
456,513,348
false
{"Kotlin": 9663067, "C": 236481, "GLSL": 9454, "Java": 7586, "Lua": 4315}
package me.anno.tests.ui import me.anno.config.DefaultConfig.style import me.anno.ecs.components.mesh.Material import me.anno.ecs.components.mesh.MeshComponent import me.anno.engine.ECSRegistry import me.anno.engine.GameEngineProject import me.anno.engine.GameEngineProject.Companion.currentProject import me.anno.engine.ui.EditorState import me.anno.graph.ui.GraphPanel.Companion.greenish import me.anno.graph.ui.GraphPanel.Companion.red import me.anno.mesh.Shapes.flatCube import me.anno.ui.debug.TestStudio.Companion.testUI3 import me.anno.ui.editor.PropertyInspector import me.anno.utils.OS.documents fun main() { ECSRegistry.init() // todo index sample project val folder = documents.getChild("RemsEngine/YandereSim") val project = GameEngineProject.readOrCreate(folder)!! currentProject = project project.init() // a few temporary files; cannot be GCed, because scope isn't left at runtime val green = Material.diffuse(greenish).ref val red = Material.diffuse(red).ref val tested = MeshComponent(flatCube.front, Material()) EditorState.select(tested) testUI3("Easy Material Editing", PropertyInspector({ EditorState.selection }, style)) }
0
Kotlin
3
17
bca49870309dc54c57daba1888c8faa2a3165025
1,197
RemsEngine
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appconfig/ActionPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.appconfig import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.appconfig.CfnExtension @Generated public fun buildActionProperty(initializer: @AwsCdkDsl CfnExtension.ActionProperty.Builder.() -> Unit): CfnExtension.ActionProperty = CfnExtension.ActionProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
433
aws-cdk-kt
Apache License 2.0
domain/api/src/commonMain/kotlin/mehiz/abdallah/progres/api/dto/AcademicDecisionDto.kt
abdallahmehiz
830,308,163
false
{"Kotlin": 449026, "Swift": 621}
package mehiz.abdallah.progres.api.dto import kotlinx.serialization.Serializable @Serializable data class AcademicDecisionDto( val annuel: Boolean, val coefficient: Double? = null, val credit: Double? = null, val creditAcquis: Double? = null, val creditObtenu: Double? = null, val cumulCreditPrecedent: Double? = null, val effectif: Long? = null, val id: Long, val moyenne: Double? = null, val moyenneSn: Double? = null, val niveauRang: Long, val totalAquis: Long, val type: Long, val typeDecisionLibelleAr: String? = null, val typeDecisionLibelleFr: String? = null, )
1
Kotlin
0
8
331d3c6c8caa126fdc7df033f2574cd3aa8f8e80
601
progres
MIT License
arrow-instances/src/main/kotlin/arrow/instances/eithert.kt
rubythonode
120,027,864
true
{"Kotlin": 1404949, "CSS": 118096, "HTML": 9871, "JavaScript": 7457, "Java": 4423, "Shell": 3057}
package arrow.instances import arrow.HK import arrow.core.Either import arrow.core.Eval import arrow.core.Left import arrow.data.* import arrow.typeclasses.* interface EitherTFunctorInstance<F, L> : Functor<EitherTKindPartial<F, L>> { fun FF(): Functor<F> override fun <A, B> map(fa: EitherTKind<F, L, A>, f: (A) -> B): EitherT<F, L, B> = fa.ev().map({ f(it) }, FF()) } interface EitherTApplicativeInstance<F, L> : EitherTFunctorInstance<F, L>, Applicative<EitherTKindPartial<F, L>> { fun MF(): Monad<F> override fun <A> pure(a: A): EitherT<F, L, A> = EitherT.pure(a, MF()) override fun <A, B> map(fa: EitherTKind<F, L, A>, f: (A) -> B): EitherT<F, L, B> = fa.ev().map({ f(it) }, MF()) override fun <A, B> ap(fa: EitherTKind<F, L, A>, ff: EitherTKind<F, L, (A) -> B>): EitherT<F, L, B> = fa.ev().ap(ff, MF()) } interface EitherTMonadInstance<F, L> : EitherTApplicativeInstance<F, L>, Monad<EitherTKindPartial<F, L>> { override fun <A, B> ap(fa: EitherTKind<F, L, A>, ff: EitherTKind<F, L, (A) -> B>): EitherT<F, L, B> = fa.ev().ap(ff, MF()) override fun <A, B> flatMap(fa: EitherTKind<F, L, A>, f: (A) -> EitherTKind<F, L, B>): EitherT<F, L, B> = fa.ev().flatMap({ f(it).ev() }, MF()) override fun <A, B> tailRecM(a: A, f: (A) -> EitherTKind<F, L, Either<A, B>>): EitherT<F, L, B> = EitherT.tailRecM(a, f, MF()) } interface EitherTApplicativeErrorInstance<F, L> : EitherTApplicativeInstance<F, L>, ApplicativeError<EitherTKindPartial<F, L>, L> { override fun <A> handleErrorWith(fa: EitherTKind<F, L, A>, f: (L) -> EitherTKind<F, L, A>): EitherT<F, L, A> = EitherT(MF().flatMap(fa.ev().value, { when (it) { is Either.Left -> f(it.a).ev().value is Either.Right -> MF().pure(it) } })) override fun <A> raiseError(e: L): EitherT<F, L, A> = EitherT(MF().pure(Left(e))) } interface EitherTMonadErrorInstance<F, L> : EitherTApplicativeErrorInstance<F, L>, EitherTMonadInstance<F, L>, MonadError<EitherTKindPartial<F, L>, L> interface EitherTFoldableInstance<F, L> : Foldable<EitherTKindPartial<F, L>> { fun FFF(): Foldable<F> override fun <B, C> foldLeft(fa: HK<EitherTKindPartial<F, L>, B>, b: C, f: (C, B) -> C): C = fa.ev().foldLeft(b, f, FFF()) override fun <B, C> foldRight(fa: HK<EitherTKindPartial<F, L>, B>, lb: Eval<C>, f: (B, Eval<C>) -> Eval<C>): Eval<C> = fa.ev().foldRight(lb, f, FFF()) } interface EitherTTraverseInstance<F, L> : EitherTFunctorInstance<F, L>, EitherTFoldableInstance<F, L>, Traverse<EitherTKindPartial<F, L>> { fun TF(): Traverse<F> override fun <A, B> map(fa: EitherTKind<F, L, A>, f: (A) -> B): EitherT<F, L, B> = fa.ev().map({ f(it) }, TF()) override fun <G, B, C> traverse(fa: EitherTKind<F, L, B>, f: (B) -> HK<G, C>, GA: Applicative<G>): HK<G, EitherT<F, L, C>> = fa.ev().traverse(f, GA, TF()) } interface EitherTSemigroupKInstance<F, L> : SemigroupK<EitherTKindPartial<F, L>> { fun MF(): Monad<F> override fun <A> combineK(x: EitherTKind<F, L, A>, y: EitherTKind<F, L, A>): EitherT<F, L, A> = x.ev().combineK(y, MF()) }
0
Kotlin
0
0
18e8320b3ae19e9756c3122a03b0c137b1c2b9da
3,231
arrow
Apache License 2.0
core/src/main/kotlin/com/justai/jaicf/channel/jaicp/JaicpBotChannel.kt
discodasha
276,730,180
true
{"Kotlin": 314034, "Java": 44400}
package com.justai.jaicf.channel.jaicp import com.justai.jaicf.api.BotApi import com.justai.jaicf.channel.BotChannel import com.justai.jaicf.channel.http.HttpBotChannel /** * Basic interface for all (native or compatible) JAICP channels. */ interface JaicpBotChannel : BotChannel /** * Basic interface for external channels compatible with JAICP channels. * These channel can use channel-specific reactions. * * @see HttpBotChannel */ interface JaicpCompatibleBotChannel : JaicpBotChannel, HttpBotChannel /** * Basic interface for external asynchronous channels compatible with JAICP channels. * These channel can use channel-specific reactions. * * @see HttpBotChannel */ interface JaicpCompatibleAsyncBotChannel : JaicpBotChannel, HttpBotChannel /** * Basic interface for JAICP-provided channel factories. */ interface JaicpChannelFactory { /** * Type of JAICP channel like "telegram", "facebook", "alexa" and etc. */ val channelType: String } /** * Channel created with this factory works as a synchronous webhook. */ interface JaicpCompatibleChannelFactory : JaicpChannelFactory { /** * Creates a new [JaicpCompatibleBotChannel] instance. * * @param botApi the [BotApi] implementation used to process the requests to this channel * @see JaicpCompatibleBotChannel * @see BotApi */ fun create(botApi: BotApi): JaicpCompatibleBotChannel } /** * Channel created with this factory receives requests from JAICP and replies asynchronously to the provided API URL. */ interface JaicpCompatibleAsyncChannelFactory : JaicpChannelFactory { /** * Creates a new [JaicpCompatibleAsyncChannelFactory] instance. * * @param botApi a [BotApi] implementation used to process the requests to this channel * @param apiUrl an URL where to send a replies */ fun create(botApi: BotApi, apiUrl: String): JaicpCompatibleAsyncBotChannel }
0
Kotlin
0
0
12167490eeb9c67a1783f5148eb7c49ad5dd2058
1,931
jaicf-kotlin
Apache License 2.0
sections_old/Section 5/demo-jpa/src/main/kotlin/com/example/demo/data/repository/ItemRepository.kt
telpay
408,523,517
true
{"Kotlin": 115874, "Java": 4740}
package com.example.demo.data.repository import com.example.demo.data.entity.Item import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.JpaSpecificationExecutor import org.springframework.data.jpa.repository.Modifying import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param import javax.transaction.Transactional interface ItemRepository : JpaRepository<Item, Long>, JpaSpecificationExecutor<Item> { @Query("UPDATE Item i SET i.price = :price WHERE i.name = :name") @Modifying @Transactional fun updateAllSoccerPrice(@Param("price") price: Float, @Param("name") name: String) @Query("DELETE FROM Item i WHERE i.name = :name") @Modifying @Transactional fun deleteAllSoccer(@Param("name") name: String): Int }
0
null
0
0
f4ae3ab650c866f63651ea41768e0a73774c9f82
849
Spring-Kotlin-iThome-2021
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ecs/SystemControlPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.ecs import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.ecs.CfnTaskDefinition @Generated public fun buildSystemControlProperty(initializer: @AwsCdkDsl CfnTaskDefinition.SystemControlProperty.Builder.() -> Unit): CfnTaskDefinition.SystemControlProperty = CfnTaskDefinition.SystemControlProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
473
aws-cdk-kt
Apache License 2.0
financial-connections/src/main/java/com/stripe/android/financialconnections/ui/FinancialConnectionsSheetNativeActivity.kt
stripe
6,926,049
false
null
package com.stripe.android.financialconnections.ui import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.activity.addCallback import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalUriHandler import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.airbnb.mvrx.MavericksView import com.airbnb.mvrx.compose.collectAsState import com.airbnb.mvrx.withState import com.stripe.android.core.Logger import com.stripe.android.financialconnections.features.accountpicker.AccountPickerScreen import com.stripe.android.financialconnections.features.attachpayment.AttachPaymentScreen import com.stripe.android.financialconnections.features.common.CloseDialog import com.stripe.android.financialconnections.features.consent.ConsentScreen import com.stripe.android.financialconnections.features.institutionpicker.InstitutionPickerScreen import com.stripe.android.financialconnections.features.linkaccountpicker.LinkAccountPickerScreen import com.stripe.android.financialconnections.features.linkstepupverification.LinkStepUpVerificationScreen import com.stripe.android.financialconnections.features.manualentry.ManualEntryScreen import com.stripe.android.financialconnections.features.manualentrysuccess.ManualEntrySuccessScreen import com.stripe.android.financialconnections.features.networkinglinkloginwarmup.NetworkingLinkLoginWarmupScreen import com.stripe.android.financialconnections.features.networkinglinksignup.NetworkingLinkSignupScreen import com.stripe.android.financialconnections.features.networkinglinkverification.NetworkingLinkVerificationScreen import com.stripe.android.financialconnections.features.networkingsavetolinkverification.NetworkingSaveToLinkVerificationScreen import com.stripe.android.financialconnections.features.partnerauth.PartnerAuthScreen import com.stripe.android.financialconnections.features.reset.ResetScreen import com.stripe.android.financialconnections.features.success.SuccessScreen import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetNativeActivityArgs import com.stripe.android.financialconnections.model.FinancialConnectionsSessionManifest.Pane import com.stripe.android.financialconnections.navigation.NavigationDirections import com.stripe.android.financialconnections.navigation.NavigationManager import com.stripe.android.financialconnections.navigation.NavigationState import com.stripe.android.financialconnections.navigation.toNavigationCommand import com.stripe.android.financialconnections.presentation.CreateBrowserIntentForUrl import com.stripe.android.financialconnections.presentation.FinancialConnectionsSheetNativeViewEffect.Finish import com.stripe.android.financialconnections.presentation.FinancialConnectionsSheetNativeViewEffect.OpenUrl import com.stripe.android.financialconnections.presentation.FinancialConnectionsSheetNativeViewModel import com.stripe.android.financialconnections.ui.theme.FinancialConnectionsTheme import com.stripe.android.financialconnections.utils.argsOrNull import com.stripe.android.financialconnections.utils.viewModelLazy import com.stripe.android.uicore.image.StripeImageLoader import javax.inject.Inject internal class FinancialConnectionsSheetNativeActivity : AppCompatActivity(), MavericksView { val args by argsOrNull<FinancialConnectionsSheetNativeActivityArgs>() val viewModel: FinancialConnectionsSheetNativeViewModel by viewModelLazy() @Inject lateinit var navigationManager: NavigationManager @Inject lateinit var logger: Logger @Inject lateinit var imageLoader: StripeImageLoader override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (args == null) { finish() } else { viewModel.activityRetainedComponent.inject(this) viewModel.onEach { postInvalidate() } onBackPressedDispatcher.addCallback { viewModel.onBackPressed() } setContent { FinancialConnectionsTheme { Column { Box(modifier = Modifier.weight(1f)) { val closeDialog = viewModel.collectAsState { it.closeDialog } val firstPane = viewModel.collectAsState { it.initialPane } val reducedBranding = viewModel.collectAsState { it.reducedBranding } closeDialog.value?.let { CloseDialog( description = it.description, onConfirmClick = viewModel::onCloseConfirm, onDismissClick = viewModel::onCloseDismiss ) } NavHost( firstPane.value, reducedBranding.value ) } } } } } } /** * handle state changes here. */ override fun invalidate() { withState(viewModel) { state -> state.viewEffect?.let { viewEffect -> when (viewEffect) { is OpenUrl -> startActivity( CreateBrowserIntentForUrl( context = this, uri = Uri.parse(viewEffect.url) ) ) is Finish -> { setResult( Activity.RESULT_OK, Intent().putExtra(EXTRA_RESULT, viewEffect.result) ) finish() } } viewModel.onViewEffectLaunched() } } } @OptIn(ExperimentalMaterialApi::class) @Suppress("LongMethod") @Composable fun NavHost( initialPane: Pane, reducedBranding: Boolean ) { val context = LocalContext.current val navController = rememberNavController() val uriHandler = remember { CustomTabUriHandler(context) } val initialDestination = remember(initialPane) { initialPane.toNavigationCommand( emptyMap() ).destination } NavigationEffect(navController) CompositionLocalProvider( LocalReducedBranding provides reducedBranding, LocalNavHostController provides navController, LocalImageLoader provides imageLoader, LocalUriHandler provides uriHandler ) { NavHost(navController, startDestination = initialDestination) { composable(NavigationDirections.consent.destination) { LaunchedPane(Pane.CONSENT) BackHandler(navController, Pane.CONSENT) ConsentScreen() } composable(NavigationDirections.manualEntry.destination) { LaunchedPane(Pane.MANUAL_ENTRY) BackHandler(navController, Pane.MANUAL_ENTRY) ManualEntryScreen() } composable( route = NavigationDirections.ManualEntrySuccess.route, arguments = NavigationDirections.ManualEntrySuccess.arguments ) { LaunchedPane(Pane.MANUAL_ENTRY_SUCCESS) BackHandler(navController, Pane.MANUAL_ENTRY_SUCCESS) ManualEntrySuccessScreen(it) } composable(NavigationDirections.institutionPicker.destination) { LaunchedPane(Pane.INSTITUTION_PICKER) BackHandler(navController, Pane.INSTITUTION_PICKER) InstitutionPickerScreen() } composable(NavigationDirections.partnerAuth.destination) { LaunchedPane(Pane.PARTNER_AUTH) BackHandler(navController, Pane.PARTNER_AUTH) PartnerAuthScreen() } composable(NavigationDirections.accountPicker.destination) { LaunchedPane(Pane.ACCOUNT_PICKER) BackHandler(navController, Pane.ACCOUNT_PICKER) AccountPickerScreen() } composable(NavigationDirections.success.destination) { LaunchedPane(Pane.SUCCESS) BackHandler(navController, Pane.SUCCESS) SuccessScreen() } composable(NavigationDirections.reset.destination) { LaunchedPane(Pane.RESET) BackHandler(navController, Pane.RESET) ResetScreen() } composable(NavigationDirections.attachLinkedPaymentAccount.destination) { LaunchedPane(Pane.ATTACH_LINKED_PAYMENT_ACCOUNT) BackHandler(navController, Pane.ATTACH_LINKED_PAYMENT_ACCOUNT) AttachPaymentScreen() } composable(NavigationDirections.networkingLinkSignup.destination) { LaunchedPane(Pane.NETWORKING_LINK_SIGNUP_PANE) BackHandler(navController, Pane.NETWORKING_LINK_SIGNUP_PANE) NetworkingLinkSignupScreen() } composable(NavigationDirections.networkingLinkLoginWarmup.destination) { LaunchedPane(Pane.NETWORKING_LINK_LOGIN_WARMUP) BackHandler(navController, Pane.NETWORKING_LINK_LOGIN_WARMUP) NetworkingLinkLoginWarmupScreen() } composable(NavigationDirections.networkingLinkVerification.destination) { LaunchedPane(Pane.NETWORKING_LINK_VERIFICATION) BackHandler(navController, Pane.NETWORKING_LINK_VERIFICATION) NetworkingLinkVerificationScreen() } composable(NavigationDirections.networkingSaveToLinkVerification.destination) { LaunchedPane(Pane.NETWORKING_SAVE_TO_LINK_VERIFICATION) BackHandler(navController, Pane.NETWORKING_SAVE_TO_LINK_VERIFICATION) NetworkingSaveToLinkVerificationScreen() } composable(NavigationDirections.linkAccountPicker.destination) { LaunchedPane(Pane.LINK_ACCOUNT_PICKER) BackHandler(navController, Pane.LINK_ACCOUNT_PICKER) LinkAccountPickerScreen() } composable(NavigationDirections.linkStepUpVerification.destination) { LaunchedPane(Pane.LINK_STEP_UP_VERIFICATION) BackHandler(navController, Pane.LINK_STEP_UP_VERIFICATION) LinkStepUpVerificationScreen() } } } } @Composable private fun BackHandler(navController: NavHostController, pane: Pane) { androidx.activity.compose.BackHandler(true) { viewModel.onBackClick(pane) if (navController.popBackStack().not()) onBackPressedDispatcher.onBackPressed() } } @Composable private fun LaunchedPane( pane: Pane ) { LaunchedEffect(Unit) { viewModel.onPaneLaunched(pane) } } /** * Handles new intents in the form of the redirect from the custom tab hosted auth flow */ override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) viewModel.handleOnNewIntent(intent) } override fun onResume() { super.onResume() viewModel.onResume() } @Composable private fun NavigationEffect( navController: NavHostController ) { val navigationState by navigationManager.navigationState.collectAsState() LaunchedEffect(navigationState) { logger.debug("updateNavigationState to $navigationState") val from = navController.currentDestination?.route when (val viewState = navigationState) { is NavigationState.NavigateToRoute -> { navigateToRoute(viewState, from, navController) navigationManager.onNavigated(navigationState) } is NavigationState.Idle -> {} } } } private fun navigateToRoute( viewState: NavigationState.NavigateToRoute, from: String?, navController: NavHostController ) { val destination = viewState.command.destination if (destination.isNotEmpty() && destination != from) { logger.debug("Navigating from $from to $destination") navController.navigate(destination) { launchSingleTop = true val currentScreen: String? = navController.currentBackStackEntry?.destination?.route if (currentScreen != null && viewState.popCurrentFromBackStack) { popUpTo(currentScreen) { inclusive = true } } } } } internal companion object { internal const val EXTRA_RESULT = "result" } } internal val LocalNavHostController = staticCompositionLocalOf<NavHostController> { error("No NavHostController provided") } internal val LocalReducedBranding = staticCompositionLocalOf<Boolean> { error("No ReducedBranding provided") } internal val LocalImageLoader = staticCompositionLocalOf<StripeImageLoader> { error("No ImageLoader provided") }
87
Kotlin
606
1,133
8103aa6791ce4de7739d201f35e3572334a60553
14,613
stripe-android
MIT License
app/src/main/java/ly/david/mbjc/ui/relation/RelationListItem.kt
lydavid
458,021,427
false
null
package ly.david.mbjc.ui.relation import android.content.res.Configuration import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.ListItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import ly.david.data.common.openUrl import ly.david.data.domain.RelationListItemModel import ly.david.data.getNameWithDisambiguation import ly.david.data.network.MusicBrainzResource import ly.david.ui.common.ResourceIcon import ly.david.ui.common.theme.PreviewTheme import ly.david.ui.common.theme.TextStyles import ly.david.ui.common.theme.getSubTextColor @Composable internal fun RelationListItem( relation: RelationListItemModel, modifier: Modifier = Modifier, onItemClick: (entity: MusicBrainzResource, id: String, title: String?) -> Unit = { _, _, _ -> }, ) { val context = LocalContext.current ListItem( headlineContent = { Column { Text( text = "${relation.label}:", style = TextStyles.getCardBodyTextStyle() ) Row( modifier = Modifier.padding(top = 4.dp), verticalAlignment = Alignment.CenterVertically ) { ResourceIcon( resource = relation.linkedResource, modifier = Modifier.padding(end = 8.dp) ) Text( text = relation.name, style = TextStyles.getCardTitleTextStyle() ) } val disambiguation = relation.disambiguation if (!disambiguation.isNullOrEmpty()) { Text( modifier = Modifier.padding(top = 4.dp), text = "($disambiguation)", style = TextStyles.getCardBodyTextStyle(), color = getSubTextColor() ) } val attributes = relation.attributes if (!attributes.isNullOrEmpty()) { Text( modifier = Modifier.padding(top = 4.dp), text = "($attributes)", style = TextStyles.getCardBodyTextStyle(), ) } val additionalInfo = relation.additionalInfo if (!additionalInfo.isNullOrEmpty()) { Text( modifier = Modifier.padding(top = 4.dp), text = additionalInfo, style = TextStyles.getCardBodyTextStyle(), ) } } }, modifier = modifier.clickable { val entity = relation.linkedResource if (entity == MusicBrainzResource.URL) { context.openUrl(relation.name) } else { onItemClick(entity, relation.linkedResourceId, relation.getNameWithDisambiguation()) } } ) } @Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun Artist() { PreviewTheme { Surface { RelationListItem( relation = RelationListItemModel( id = "2_0", linkedResourceId = "2", linkedResource = MusicBrainzResource.ARTIST, label = "miscellaneous support", name = "Artist Name", disambiguation = "that guy", attributes = "task: director & organizer, strings", ) ) } } } @Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun Recording() { PreviewTheme { Surface { RelationListItem( relation = RelationListItemModel( id = "2_1", linkedResourceId = "2", linkedResource = MusicBrainzResource.RECORDING, label = "DJ-mixes", name = "Recording Name", additionalInfo = "by Artist Names (order: 10)", ) ) } } }
27
Kotlin
0
3
50f78703164a8d880e955800e7bbe0a1150ed45a
4,686
MusicSearch
Apache License 2.0
sample/app/src/main/java/dev/tuongnt/tinder/di/DataModule.kt
alanrb
296,359,249
false
null
package dev.tuongnt.tinder.di import dev.tuongnt.tinder.data.repo.UserRepositoryImpl import dev.tuongnt.tinder.domain.repo.UserRepository import org.koin.dsl.module val dataModule = module { single<UserRepository> { UserRepositoryImpl(get(), get()) } }
0
null
0
0
4b70d16f40078747704a263b140f31fae03a5ce8
258
Android-motion-layout
Apache License 2.0
character-detail/data/src/main/java/com/haldny/dragonball/character/detail/data/CharacterDetailRepositoryImpl.kt
haldny
771,170,616
false
{"Kotlin": 58917}
package com.haldny.dragonball.character.detail.data import com.haldny.dragonball.character.detail.data.api.CharacterDetailApi import com.haldny.dragonball.character.detail.data.mapper.toBusinessModel import com.haldny.dragonball.character.detail.domain.CharacterDetailRepository import com.haldny.dragonball.character.detail.domain.DragonBallCharacterDetail import com.haldny.dragonball.core.business.BusinessResult import com.haldny.dragonball.network.extensions.handleResponse import javax.inject.Inject class CharacterDetailRepositoryImpl @Inject constructor( private val characterDetailApi: CharacterDetailApi ) : CharacterDetailRepository { override suspend fun getCharacterDetail(id: Int): BusinessResult<DragonBallCharacterDetail> { return characterDetailApi.getCharacterDetail(id).handleResponse { response -> response.toBusinessModel() } } }
0
Kotlin
0
0
360f823818d830a24fb1f76d6cc959530faece32
894
DragonBall-Compose
Apache License 2.0
app/app/src/main/java/dev/kevinesg/notepadapp/ui/theme/Type.kt
kevinesg
580,732,488
false
null
package dev.kevinesg.notepadapp.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import dev.kevinesg.notepadapp.R // Set of Material typography styles to start with val fonts = FontFamily( Font(R.font.dejavu_sans_bold, weight = FontWeight.Bold), Font(R.font.dejavu_sans_bold_italic, weight = FontWeight.Bold, style = FontStyle.Italic), Font(R.font.dejavu_sans_italic, weight = FontWeight.Normal, style = FontStyle.Italic), Font(R.font.dejavu_sans_regular, weight = FontWeight.Normal) ) val Typography = Typography( defaultFontFamily = fonts, body1 = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 16.sp ), // Other default text styles to override button = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 14.sp ), caption = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 12.sp ), body2 = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 16.sp ), subtitle1 = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 16.sp ), subtitle2 = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 12.sp ), overline = TextStyle( fontFamily = fonts, fontWeight = FontWeight.Normal, fontSize = 12.sp ) )
0
Kotlin
0
0
39b063082829ef32e7c93ff2aee073955bba189c
1,755
Notepad.app
MIT License
src/main/kotlin/org/anglur/joglext/jogl2d/impl/GLGraphicsDevice.kt
jonatino
69,714,321
false
{"Kotlin": 588625, "Java": 17760}
/* * Copyright 2016 <NAME> <https://github.com/Jonatino> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anglur.joglext.jogl2d.impl import java.awt.GraphicsConfiguration import java.awt.GraphicsDevice /** * Fulfills the contract of a `GraphicsDevice`. */ class GLGraphicsDevice(private val config: GLGraphicsConfiguration) : GraphicsDevice() { override fun getType(): Int { if (config.target.chosenGLCapabilities.isOnscreen) { return GraphicsDevice.TYPE_RASTER_SCREEN } else { return GraphicsDevice.TYPE_IMAGE_BUFFER } } override fun getIDstring(): String { return "glg2d" } override fun getConfigurations(): Array<GraphicsConfiguration> { return arrayOf(defaultConfiguration) } override fun getDefaultConfiguration(): GraphicsConfiguration { return config } }
0
Kotlin
4
28
b43cbe514a496e2a45b45475c0100622ea190dc0
1,357
JOGL2D
Apache License 2.0
ui/src/main/java/com/mhacks/app/ui/events/widget/EventTimeLineItem.kt
a-ye13
207,436,130
true
{"Kotlin": 302268, "Java": 2165}
package com.mhacks.app.ui.events.widget import android.content.Context import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintLayout import com.mhacks.app.data.models.Event import com.mhacks.app.ui.events.model.EventSectionModel import kotlinx.android.synthetic.main.events_timeline_item.view.* import org.mhacks.mhacksui.R /** * Add events TextViews to a Linear Layout */ class EventTimeLineItem(context: Context): ConstraintLayout(context) { var onEventClicked: ((event: Event, isChecked: Boolean) -> Unit)? = null init { inflate(context, R.layout.events_timeline_item, this) layoutParams = LayoutParams( LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) } var timeLineType: Int = -999 set(viewType) { events_timeline_view.initLine(viewType) } var timeText: String? = null set(time) { events_description_time_textview.text = time } fun addEventGroup(eventsSection: EventSectionModel) { events_description_linear_layout.removeAllViews() for (event in eventsSection.events) { val eventDescriptionItem = EventDescriptionItem(context, null) eventDescriptionItem.bindItem(event, onEventClicked) events_description_linear_layout.addView(eventDescriptionItem) } } }
0
null
0
0
edf4ae94b7be31f25bf47a77062c74e80430c663
1,434
mhacks-android
MIT License
composables/src/commonMain/kotlin/eu/baroncelli/dkmpsample/composables/navigation/HandleBackButton.kt
dbaroncelli
348,513,314
false
null
package eu.baroncelli.dkmpsample.composables.navigation import androidx.compose.runtime.Composable import eu.baroncelli.dkmpsample.shared.viewmodel.Navigation @Composable expect fun Navigation.HandleBackButton()
7
Kotlin
64
602
74009f93f7a1dd809ef7f21ceca4e2c0d1cbd67c
213
D-KMP-sample
Apache License 2.0
feature/app-theme/domain/src/main/kotlin/ru/maksonic/beresta/feature/app_theme/domain/usecase/AppThemeInteractor.kt
maksonic
580,058,579
false
{"Kotlin": 1622432}
package ru.maksonic.beresta.feature.app_theme.domain.usecase import ru.maksonic.beresta.feature.app_theme.domain.AppThemeDomain import ru.maksonic.beresta.feature.app_theme.domain.AppThemePaletteDomain import ru.maksonic.beresta.feature.app_theme.domain.AppThemeRepository /** * @Author maksonic on 13.10.2023 */ interface AppThemeInteractor { suspend fun setTheme(theme: AppThemeDomain) suspend fun updateDarkMode(isDark: Boolean) suspend fun setPalette(palette: AppThemePaletteDomain) class Core(private val repository: AppThemeRepository) : AppThemeInteractor { override suspend fun setTheme(theme: AppThemeDomain) = repository.setTheme(theme) override suspend fun setPalette(palette: AppThemePaletteDomain) = repository.setPalette(palette) override suspend fun updateDarkMode(isDark: Boolean) = repository.updateDarkMode(isDark) } }
0
Kotlin
0
0
227b0a5f6c27b0f731b1f6e81b1fe2deeaa720aa
885
Beresta
MIT License
telegram-bot-core/src/main/kotlin/io/github/dehuckakpyt/telegrambot/api/ex/TelegramReactionExApi.kt
DEHuckaKpyT
670,859,055
false
{"Kotlin": 517509}
package io.github.dehuckakpyt.telegrambot.api.ex import io.github.dehuckakpyt.telegrambot.api.TelegramReactionApi import io.github.dehuckakpyt.telegrambot.model.type.ReactionType /** * Created on 11.01.2024. *<p> * * @author Denis Matytsin */ interface TelegramReactionExApi : TelegramReactionApi { suspend fun setMessageReaction( chatId: Long, messageId: Long, reaction: Iterable<ReactionType>? = null, isBig: Boolean? = null, ): Boolean = setMessageReaction( chatId = chatId, messageId = messageId, reaction = reaction, isBig = isBig ) }
1
Kotlin
0
9
fd400d4222cf7b10964bb350a943f4d6e7c6f5bd
624
telegram-bot
Apache License 2.0
app/src/main/java/ru/nightgoat/weather/core/extentions/ContextExt.kt
NightGoat
255,927,899
false
{"Kotlin": 101372}
package ru.nightgoat.weather.core.extentions import android.content.Context import android.graphics.Typeface import ru.nightgoat.weather.core.utils.FONTS_PATH fun Context.createTypeFace(): Typeface? = Typeface.createFromAsset( this.assets, FONTS_PATH )
0
Kotlin
0
2
dddb5463ded919f43fd1450bb0fcdffc34a2752e
262
WeatherAndroidApp
MIT License
net.akehurst.language/agl-processor/src/commonMain/kotlin/agl/runtime/graph/GrowingChildren.kt
dhakehurst
197,245,665
false
null
/** * Copyright (C) 2020 Dr. David H. Akehurst (http://dr.david.h.akehurst.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.akehurst.language.agl.runtime.graph import net.akehurst.language.agl.automaton.ParserState import net.akehurst.language.agl.runtime.structure.RuleOptionId import net.akehurst.language.api.sppt.SPPTNode internal class GrowingChildren { var length: Int = 0; private set var numberNonSkip: Int = 0; private set var nextInputPosition: Int = -1 var startPosition: Int = -1 private var _firstChild: GrowingChildNode? = null private var _firstChildAlternatives: MutableMap<List<RuleOptionId>, MutableList<GrowingChildNode>>? = null private var _lastChild: GrowingChildNode? = null private var _nextChildAlts: MutableMap<Int, MutableMap<List<RuleOptionId>, Int>>? = null private fun clone(): GrowingChildren { val cl = GrowingChildren() cl.length = this.length cl.numberNonSkip = this.numberNonSkip cl.nextInputPosition = this.nextInputPosition cl.startPosition = this.startPosition cl._firstChild = this._firstChild if (null != this._firstChildAlternatives) { cl._firstChildAlternatives = mutableMapOf() this._firstChildAlternatives!!.entries.forEach { val l = it.value.toMutableList() cl._firstChildAlternatives!![it.key] = l } } cl._lastChild = this._lastChild if (null != this._nextChildAlts) { cl._nextChildAlts = mutableMapOf() this._nextChildAlts!!.entries.forEach { val mapCl = it.value.toMutableMap() cl._nextChildAlts!![it.key] = mapCl } } return cl } private fun nextChildAlt(childIndex: Int, ruleOption: RuleOptionId): Int { return when { null == _nextChildAlts -> 0 else -> { val m = _nextChildAlts!![childIndex] when { null == m -> 0 else -> m.entries.firstOrNull { it.key.contains(ruleOption) }?.value ?: 0 } } } } internal fun incNextChildAlt(childIndex: Int, value: List<RuleOptionId>) { if (null == _nextChildAlts) _nextChildAlts = mutableMapOf() var m = _nextChildAlts!![childIndex] if (null == m) { m = mutableMapOf() _nextChildAlts!![childIndex] = m } val v = m[value] if (null == v) { m[value] = 1 } else { m[value] = v + 1 } } internal fun setNextChildAlt(childIndex: Int, value: List<RuleOptionId>, altNum:Int) { if (null == _nextChildAlts) _nextChildAlts = mutableMapOf() var m = _nextChildAlts!![childIndex] if (null == m) { m = mutableMapOf() _nextChildAlts!![childIndex] = m } m[value] = altNum } val isEmpty: Boolean get() = null == _firstChild && null == _firstChildAlternatives val hasSkipAtStart: Boolean get() = null == _firstChild!!.state val lastInitialSkipChild: GrowingChildNode? get() = when { isEmpty -> null null != this._firstChildAlternatives -> null //skips never have alternatives else -> { var n = this._firstChild var last: GrowingChildNode? = null while (null != n && null == n.state) { last = n n = n.nextChild } last } } val lastChild: GrowingChildNode? get() = this._lastChild fun firstChild(ruleOption: RuleOptionId?): GrowingChildNode? = when { null == this._firstChildAlternatives -> this._firstChild null == ruleOption -> null //skip will not have alternatives else -> this._firstChildAlternatives!!.entries.firstOrNull { it.key.contains(ruleOption) }?.value?.get(this.nextChildAlt(0, ruleOption)) } fun firstNonSkipChild(ruleOption: RuleOptionId): GrowingChildNode? { var r = this.firstChild(ruleOption) var index = 1 while (null != r && null == r.state) { r = r.next(this.nextChildAlt(index, ruleOption), ruleOption) index++ } return r } fun setFirstChildAlternative() { } fun appendChild(state: ParserState, nextChildAlts: List<SPPTNode>): GrowingChildren? { return when { isEmpty -> { _firstChild = GrowingChildNode(state, nextChildAlts) startPosition = nextChildAlts[0].startPosition _lastChild = _firstChild this.length++ this.numberNonSkip++ //check(1 == nextChildAlts.map { it.nextInputPosition }.toSet().size) this.nextInputPosition = nextChildAlts[0].nextInputPosition //FIXME: not really correct, are all children same length? this } state.isGoal -> { val lisc = lastInitialSkipChild when { null == lisc -> { // must be duplicate of firstNode which is goal //TODO: if nextInputPosition of duplicate ?? val alternativeNextChild = GrowingChildNode(state, nextChildAlts) val res = this.clone() res._firstChildAlternatives = mutableMapOf() val alts = mutableListOf(res._firstChild!!) res._firstChildAlternatives!![state.rulePositionIdentity] = alts res._firstChild = null alts.add(alternativeNextChild) res.incNextChildAlt(0, state.rulePositionIdentity) res._lastChild = alternativeNextChild // because its a duplicate of existing goal // will not changed the length or numberNonSkip res.nextInputPosition = nextChildAlts[0].nextInputPosition //FIXME: not really correct, are all children same length? res } else -> { // must be initial skip and duplicate of existing goal val changeLength = lisc.isLast val appended = lisc.appendLast(this, this.length - 1, state, nextChildAlts) appended?.let { this._lastChild = it if (changeLength) { this.length++ this.numberNonSkip++ } else { // because its a duplicate of existing goal // will not changed the length or numberNonSkip } this.nextInputPosition = nextChildAlts[0].nextInputPosition //FIXME: not really correct, are all children same length? this } } } } else -> { val res = this.clone() val lastChild = res._lastChild!! val appended = lastChild.appendLast(res, res.length, state, nextChildAlts) appended?.let { res._lastChild = it res.length++ res.numberNonSkip++ //check(1 == nextChildAlts.map { it.nextInputPosition }.toSet().size) res.nextInputPosition = nextChildAlts[0].nextInputPosition //FIXME: not really correct, are all children same length? res } } } } fun appendSkipIfNotEmpty(skipChildren: List<SPPTNode>): GrowingChildren { return if (skipChildren.isEmpty()) { //do nothing this } else { if (isEmpty) { this._firstChild = GrowingChildNode(null, skipChildren) this.startPosition = skipChildren[0].startPosition this._lastChild = _firstChild this.length++ this.nextInputPosition = skipChildren.last().nextInputPosition this } else { val lastChild = this.lastChild!! when { lastChild.isLast -> { val res = this.clone() val nextChild = GrowingChildNode(null, skipChildren) res._lastChild!!.nextChild = nextChild res._lastChild = nextChild res.length++ res.nextInputPosition = skipChildren.last().nextInputPosition res } else -> { val lastNext = lastChild.nextChild when { null != lastNext -> when { //one alt lastNext.nextInputPosition == skipChildren.last().nextInputPosition -> { //ignore it, use existing val res = this.clone() res._lastChild = lastNext res.length++ res.nextInputPosition = skipChildren.last().nextInputPosition res } else -> { error("TODO got another skip?") } } else -> { //multiple alts error("TODO got another skip?") } } } } } } } operator fun get(ruleOption: RuleOptionId): List<SPPTNode> { return when { isEmpty -> emptyList() else -> { val res = mutableListOf<SPPTNode>() var n: GrowingChildNode? = firstChild(ruleOption) var index = 1 while (n != _lastChild && null != n) { res.addAll(n[ruleOption]) n = n.next(this.nextChildAlt(index, ruleOption), ruleOption) index++ } if (null == n) { //this list of children died error("TODO") } else { res.addAll(_lastChild!![ruleOption]) } res } } } fun concatenate(other: GrowingChildren) { val lasChild = this._lastChild!! lasChild.nextChild = other._firstChild if (null != other._firstChildAlternatives) { lasChild.nextChildAlternatives = mutableMapOf() other._firstChildAlternatives!!.entries.forEach { val l = it.value.toMutableList() lasChild.nextChildAlternatives!![it.key] = l } } if (null != other._nextChildAlts) { other._nextChildAlts!!.forEach { this._nextChildAlts!![it.key + this.length] = it.value.toMutableMap() } } this._lastChild = other._lastChild this.length += other.length this.numberNonSkip += other.numberNonSkip this.nextInputPosition = other.nextInputPosition } override fun toString(): String = when { isEmpty -> "{}" else -> { val res = mutableMapOf<RuleOptionId?, List<String>>() val initialSkip = mutableListOf<String>() var sn = _firstChild var lastSkip = sn while (sn != null && null == sn.state) { initialSkip.add(sn.children.joinToString() { it.name }) lastSkip = sn sn = sn.nextChild } val rpIds = when { // there are no skips null != _firstChildAlternatives -> _firstChildAlternatives!!.entries.flatMap { it.key } null == sn -> when { //lastSkip.next has alts null != lastSkip!!.nextChildAlternatives -> lastSkip.nextChildAlternatives!!.entries.flatMap { it.key } //nothing after skips else -> emptyList() } //sn (lastSkip.next) is the first nonSkip node else -> sn.state?.rulePositionIdentity ?: emptyList() } when { rpIds.isEmpty() -> res[null] = initialSkip else -> { for (rpId in rpIds) { res[rpId] = initialSkip var n = firstNonSkipChild(rpId) var skip = "" var index = 1 while (_lastChild != n && null != n) { val state = n.state when { null == state -> skip += n.children.joinToString { it.name } //skipNodes else -> { if (skip.isNotBlank()) { res[rpId] = res[rpId]!! + skip skip = "" } res[rpId] = res[rpId]!! + n[rpId].joinToString() { it.name } } } n = n.next(this.nextChildAlt(index, rpId), rpId) index++ } if (null == n) { //this list of children died res[rpId] = res[rpId]!! + "-X" } else { val state = n.state when { null == state -> { skip += n.children.joinToString { it.name } //skipNodes if (skip.isNotBlank()) { res[rpId] = res[rpId]!! + skip skip = "" } } else -> { if (skip.isNotBlank()) { res[rpId] = res[rpId]!! + skip skip = "" } res[rpId] = res[rpId]!! + n[rpId].joinToString() { it.name } } } } } } } res.entries.map { "(${this.startPosition},${this.nextInputPosition},${it.key?.runtimeRule?.tag}[${it.key?.option}]) -> ${it.value.joinToString()}" }.joinToString(separator = "\n") } } }
2
Kotlin
5
36
c4a404149d165ea57220f978c5f2bde3ac6f14f3
15,800
net.akehurst.language
Apache License 2.0
src/main/kotlin/com/jalgoarena/JAlgoArenaAuthServer.kt
natalia75
108,680,756
true
{"Kotlin": 52398, "Shell": 103}
package com.jalgoarena import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.cloud.netflix.eureka.EnableEurekaClient import org.springframework.context.annotation.Bean import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableEurekaClient @EnableConfigurationProperties @EnableSwagger2 open class JAlgoArenaAuthServer fun main(args: Array<String>) { SpringApplication.run(JAlgoArenaAuthServer::class.java, *args) } @Bean fun api(): Docket = Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.jalgoarena.web")) .paths(PathSelectors.any()) .build()
0
Kotlin
0
0
938af56fca76807d1cb181dc569d110b920d8706
1,199
JAlgoArena-Auth
Apache License 2.0
app/src/main/java/com/github/androidhappyclub/datasample/StudentDbActivity.kt
AndroidHappyClub
732,649,245
false
{"Kotlin": 83338, "Java": 3464}
/* * MIT License * * Copyright (c) 2024 AndroidHappyClub * * 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.github.androidhappyclub.datasample import android.content.ContentValues import android.database.Cursor import android.os.Bundle import android.provider.BaseColumns import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.database.getIntOrNull import androidx.core.database.getStringOrNull import androidx.recyclerview.widget.LinearLayoutManager import com.ave.vastgui.adapter.widget.AdapterClickListener import com.ave.vastgui.tools.view.dialog.MaterialAlertDialogBuilder import com.ave.vastgui.tools.viewbinding.viewBinding import com.github.androidhappyclub.datasample.adapter.ContentProviderAdapter import com.github.androidhappyclub.datasample.databinding.ActivityStudentDbBinding import com.github.androidhappyclub.datasample.helper.StudentDbHelper import com.github.androidhappyclub.datasample.log.mLogFactory import com.github.androidhappyclub.datasample.model.Student import com.google.android.material.textfield.TextInputEditText class StudentDbActivity : AppCompatActivity(R.layout.activity_student_db) { private val mBinding by viewBinding(ActivityStudentDbBinding::bind) private val mLogger = mLogFactory.getLog(StudentDbActivity::class.java) private val mDialogBuilder by lazy { MaterialAlertDialogBuilder(this) } private val mAdapter = ContentProviderAdapter(this) private lateinit var mStudentDbHelper: StudentDbHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindViews() } override fun onDestroy() { mStudentDbHelper.close() super.onDestroy() } private fun bindViews() { mStudentDbHelper = StudentDbHelper(this) mAdapter.registerClickEvent(object : AdapterClickListener { override fun onItemClick(view: View, pos: Int) { mDialogBuilder .setMessage("真的要删除该记录吗?") .setPositiveButton("是") { _, _ -> //删除数据 mStudentDbHelper.delete(pos.toLong()) updateListView("0,19") } .setNegativeButton("否", null) .show() } }) mBinding.lvStudents.apply { adapter = mAdapter layoutManager = LinearLayoutManager(this@StudentDbActivity) } mBinding.addStudent.setOnClickListener { mDialogBuilder.apply { setTitle("新增学生") setView(R.layout.dialog_add_student) setPositiveButton("确定") { _, _ -> val result = mStudentDbHelper.insert { put( Student.COLUMN_NAME, findViewById<TextInputEditText>(R.id.stuName).text.toString() ) put( Student.COLUMN_SEX, findViewById<TextInputEditText>(R.id.stuSex).text.toString() ) put( Student.COLUMN_AGE, findViewById<TextInputEditText>(R.id.stuAge).text.toString() ) } if (-1L != result) { val count = mStudentDbHelper.getCount() updateListView(getString(R.string.format_sql_limit, 0, count)) } } show() } } mBinding.addStudentByProvider.setOnClickListener { mDialogBuilder.apply { setTitle("新增学生") setView(R.layout.dialog_add_student) setPositiveButton("确定") { _, _ -> val values = ContentValues().apply { put( Student.COLUMN_NAME, findViewById<TextInputEditText>(R.id.stuName).text.toString() ) put( Student.COLUMN_SEX, findViewById<TextInputEditText>(R.id.stuSex).text.toString() ) put( Student.COLUMN_AGE, findViewById<TextInputEditText>(R.id.stuAge).text.toString() ) } contentResolver.insert(Student.CONTENT_URI, values)?.apply { contentResolver.notifyChange(this, null) val count = mStudentDbHelper.getCount() updateListView(getString(R.string.format_sql_limit, 0, count)) } } show() } } mBinding.queryStudent.setOnClickListener { val count = mStudentDbHelper.getCount() mLogger.d("目前数据总数 $count") updateListView(getString(R.string.format_sql_limit, 0, count)) } //查询数据,获取游标 updateListView() } private fun updateListView(limit: String? = null) { if (0 != mBinding.lvStudents.childCount) { mBinding.lvStudents.removeAllViews() mAdapter.clear() } val columns = arrayOf( BaseColumns._ID, Student.COLUMN_NAME, Student.COLUMN_SEX, Student.COLUMN_AGE ) mStudentDbHelper.query(columns, limit).use { while (it.moveToNext()) { mAdapter.addStudent(it.newStudent()) } } } private fun Cursor.newStudent(): Student { val id: Int = getIntOrNull(getColumnIndex(Student.COLUMN_ID)) ?: 0 val name: String = getStringOrNull(getColumnIndex(Student.COLUMN_NAME)) ?: "" val sex: String = getStringOrNull(getColumnIndex(Student.COLUMN_SEX)) ?: "" val age: Int = getIntOrNull(getColumnIndex(Student.COLUMN_AGE)) ?: 0 return Student(id, name, sex, age) } }
0
Kotlin
0
1
6347e4864e0bf06ce828927e129a537507f2339d
7,181
DataSample
MIT License
app/src/main/kotlin/de/digitalService/useID/util/CoroutineContextProvider.kt
digitalservicebund
486,188,046
false
null
package de.digitalService.useID.util import kotlinx.coroutines.Dispatchers import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.CoroutineContext @Singleton class CoroutineContextProvider @Inject constructor() : CoroutineContextProviderType { override val Default: CoroutineContext by lazy { Dispatchers.Default } override val Main: CoroutineContext by lazy { Dispatchers.Main } override val IO: CoroutineContext by lazy { Dispatchers.IO } }
2
Kotlin
2
5
bfb1bea70b827563f80ff9828439de37197a431f
484
useid-app-android
MIT License
src/test/kotlin/no/nav/dagpenger/grunnbelop/features/GrunnbeløpSteps.kt
navikt
380,168,317
false
{"Kotlin": 37400, "Gherkin": 1010}
package no.nav.dagpenger.grunnbelop.features import io.cucumber.java8.No import io.kotest.assertions.withClue import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import no.nav.dagpenger.grunnbelop.Grunnbeløp import no.nav.dagpenger.grunnbelop.Regel import no.nav.dagpenger.grunnbelop.Regel.Grunnlag import no.nav.dagpenger.grunnbelop.Regel.Minsteinntekt import no.nav.dagpenger.grunnbelop.forDato import no.nav.dagpenger.grunnbelop.getGrunnbeløpForRegel import java.math.BigDecimal import java.time.LocalDate import java.time.Month import java.time.format.DateTimeFormatter import java.util.Locale class GrunnbeløpSteps() : No { private var grunnbeløp: Grunnbeløp? = null private var år: Int? = null private var verdi: BigDecimal? = null private companion object { private val dateFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy").localizedBy(Locale("no", "NO")) } init { Gitt("at grunnbeløpet for {int} er {int} kroner") { år: Int, kroner: Int -> this.år = år verdi = kroner.toBigDecimal() grunnbeløp = Grunnbeløp.valueOf("FastsattI$år") grunnbeløp!!.verdi shouldBe kroner.toBigDecimal() } Når("grunnbeløpet trer i kraft {string}") { dato: String -> val iverksettesFom = LocalDate.parse("$dato $år", dateFormatter) grunnbeløp!!.iverksattFom shouldBe iverksettesFom } Så("skal grunnlag bruke {int} kroner etter 1. mai") { kroner: Int -> val førsteMai = grunnbeløp ved Grunnlag den LocalDate.of(år!!, Month.MAY, 1) førsteMai shouldBe grunnbeløp førsteMai.verdi shouldBe kroner.toBigDecimal() } Og("minsteinntekt bruke {int} kroner etter {string}") { kroner: Int, hg: String -> val hengendeG = LocalDate.parse("$hg $år", dateFormatter) // Sjekk at grunnbeløpet ikke trår i kraft før dagen til hengende G har passert withClue("Grunnbeløpet trår i kraft for minsteinntekt før hengende G") { val gFørGjustering = grunnbeløp ved Minsteinntekt den hengendeG.minusDays(1) gFørGjustering shouldNotBe grunnbeløp } // Sjekk at grunnbeløpet etter gjustering (hengende G) er riktig val gJustering = grunnbeløp ved Minsteinntekt den hengendeG gJustering shouldBe grunnbeløp gJustering.verdi shouldBe kroner.toBigDecimal() } } fun Regel.grunnbeløp( dato: LocalDate, iverksattFom: LocalDate, ) = getGrunnbeløpForRegel(this).forDato(dato, iverksattFom) } private infix fun Grunnbeløp?.ved(regel: Regel) = object { infix fun den(dato: LocalDate) = getGrunnbeløpForRegel(regel).forDato(dato, this@ved!!.iverksattFom) }
1
Kotlin
0
0
99c83c4bc0df72fb3950cd6ea2fa751d9d5ecfaa
2,811
dp-grunnbelop
MIT License
app/src/main/java/in/dragonbra/vapulla/broadcastreceiver/IgnoreRequestReceiver.kt
Longi94
123,719,266
false
null
package `in`.dragonbra.vapulla.broadcastreceiver import `in`.dragonbra.vapulla.service.SteamService import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import org.jetbrains.anko.startService class IgnoreRequestReceiver : BroadcastReceiver() { companion object { const val EXTRA_ID = "id" } override fun onReceive(context: Context, intent: Intent) { if (!intent.hasExtra(EXTRA_ID)) { throw IllegalStateException("missing extra steam id") } context.startService<SteamService>( SteamService.EXTRA_ID to intent.getLongExtra(AcceptRequestReceiver.EXTRA_ID, 9L), SteamService.EXTRA_ACTION to "ignore_request" ) } }
7
Kotlin
1
7
0984265dfe0308131d72019d095e501baaf620ca
764
Vapulla
Apache License 2.0
src/main/java/ru/hollowhorizon/hc/client/audio/formats/Mp3Format.kt
HollowHorizon
450,852,365
false
{"Kotlin": 1204836, "Java": 256412, "GLSL": 44525}
package ru.hollowhorizon.hc.client.audio.formats import org.lwjgl.system.MemoryUtil import ru.hollowhorizon.hc.client.audio.Wave import ru.hollowhorizon.hc.client.audio.decoder.* import java.io.ByteArrayOutputStream import java.io.InputStream import java.nio.ByteOrder object Mp3Format { private const val DECODER_ERROR: Int = 0x200 const val UNKNOWN_ERROR: Int = DECODER_ERROR const val UNSUPPORTED_LAYER: Int = DECODER_ERROR + 1 const val ILLEGAL_SUBBAND_ALLOCATION: Int = DECODER_ERROR + 2 private class Decode { lateinit var output: OutputBuffer private lateinit var filter1: SynthesisFilter private lateinit var filter2: SynthesisFilter private var l3decoder: LayerIIIDecoder? = null private var l2decoder: LayerIIDecoder? = null private var l1decoder: LayerIDecoder? = null private var initialized = false fun decodeFrame(header: Header, stream: Bitstream) { if (!initialized) initialize(header) val layer: Int = header.layer() val decoder = retrieveDecoder(header, stream, layer) decoder.decodeFrame() } private fun retrieveDecoder(header: Header, stream: Bitstream, layer: Int): FrameDecoder { var decoder: FrameDecoder? = null when (layer) { 3 -> { if (l3decoder == null) l3decoder = LayerIIIDecoder(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS) decoder = l3decoder } 2 -> { if (l2decoder == null) { l2decoder = LayerIIDecoder() l2decoder!!.create(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS) } decoder = l2decoder } 1 -> { if (l1decoder == null) { l1decoder = LayerIDecoder() l1decoder!!.create(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS) } decoder = l1decoder } } if (decoder == null) throw DecoderException(UNSUPPORTED_LAYER, null) return decoder } private fun initialize(header: Header) { val scalefactor = 32700.0f val mode: Int = header.mode() header.layer() val channels = if (mode == Header.SINGLE_CHANNEL) 1 else 2 filter1 = SynthesisFilter(0, scalefactor) if (channels == 2) filter2 = SynthesisFilter(1, scalefactor) initialized = true } } fun read(stream: InputStream): Wave { val bitstream = Bitstream(stream) var header: Header? = bitstream.readFrame() ?: throw IllegalStateException("Empty mp3 file!") val channels = if (header?.mode() == Header.SINGLE_CHANNEL) 1 else 2 val rate: Int = header?.sampleRate ?: -1 val outputBuffer = OutputBuffer(channels, false) val buffer = ByteArrayOutputStream(4096) val decoder = Decode() decoder.output = outputBuffer while (true) { header = bitstream.readFrame() if (header == null) break try { decoder.decodeFrame(header, bitstream) } catch (ex: Exception) { ex.printStackTrace() } bitstream.closeFrame() buffer.write(outputBuffer.buffer, 0, outputBuffer.reset()) } bitstream.close() val bytes = buffer.size() - (buffer.size() % (if (channels > 1) 4 else 2)) val output = MemoryUtil.memAlloc(bytes) output.order(ByteOrder.nativeOrder()) output.put(buffer.toByteArray(), 0, bytes) output.flip() return Wave(channels, rate, 16, buffer.toByteArray()) } }
0
Kotlin
4
20
e9a8a81a06eb9f355163d4fb966999dcd680727f
3,981
HollowCore
MIT License
mobile/src/main/kotlin/io/github/delr3ves/dotto/flash/FlashManager.kt
delr3ves
73,222,981
false
null
package io.github.delr3ves.dotto.flash import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraMetadata import android.hardware.camera2.CaptureRequest import io.github.delr3ves.dotto.core.model.IndicatorStatus import io.github.delr3ves.dotto.core.model.IndicatorStatus.Off import io.github.delr3ves.dotto.core.model.IndicatorStatus.On class FlashManager(builder: CaptureRequest.Builder, session: CameraCaptureSession) { private val builder = builder private val session = session fun toggle(): IndicatorStatus { return when (getStatus()) { is Off -> { turnOn() } is On -> { turnOff() } } } fun setStatus(status: IndicatorStatus) = when (status) { is On -> turnOn() is Off -> turnOff() } fun turnOn(): IndicatorStatus { builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH) session.setRepeatingRequest(builder!!.build(), null, null) return On } fun turnOff(): IndicatorStatus { builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF) session.setRepeatingRequest(builder!!.build(), null, null) return Off } fun getStatus(): IndicatorStatus { if (builder.get(CaptureRequest.FLASH_MODE).equals(CameraMetadata.FLASH_MODE_OFF)) { return Off } else { return On } } }
0
Kotlin
0
1
9ea01cd3010d701db6b739944168945efc5740ef
1,493
AndroidDotto
MIT License
app/src/main/java/com/personal/weathering/search/presentation/SearchViewModel.kt
Avvami
702,061,643
false
{"Kotlin": 348568}
package com.personal.weathering.search.presentation import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.personal.weathering.core.data.local.SearchResultEntity import com.personal.weathering.search.domain.models.SearchInfo import com.personal.weathering.core.domain.repository.LocalRepository import com.personal.weathering.search.domain.repository.SearchRepository import com.personal.weathering.core.util.Resource import com.personal.weathering.core.presentation.SearchHistoryState import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class SearchViewModel( private val searchRepository: SearchRepository, private val localRepository: LocalRepository ): ViewModel() { private val _searchHistoryState = MutableStateFlow<List<SearchHistoryState>>(listOf()) val searchHistoryState: StateFlow<List<SearchHistoryState>> = _searchHistoryState.asStateFlow() init { viewModelScope.launch { localRepository.getSearchHistory() .collect { searchResultsEntity -> _searchHistoryState.value = searchResultsEntity.map { SearchHistoryState(it.id, it.cityId, it.city, it.lat, it.lon) } } } } var searchQuery by mutableStateOf("") private set var searchFieldActive by mutableStateOf(true) private set var searchState by mutableStateOf(SearchState()) private set private var searchJob: Job? = null var isLanguageDropdownExpanded by mutableStateOf(false) private set private fun searchLocation(query: String, language: String) { if (query.isBlank()) { searchState = SearchState() } else { viewModelScope.launch { searchState = searchState.copy( isLoading = true, error = null ) var searchInfo: SearchInfo? = null var error: String? = null searchRepository.getSearchData(query = query.trim(), language = language).let { result -> when (result) { is Resource.Error -> { error = result.message } is Resource.Success -> { searchInfo = result.data } } } searchState = searchState.copy( searchInfo = searchInfo, isLoading = false, error = error ) } } } fun searchUiEvent(event: SearchUiEvent) { when (event) { is SearchUiEvent.OnSearchQueryChange -> { searchQuery = event.query searchJob?.cancel() searchJob = viewModelScope.launch { delay(1000L) searchLocation(searchQuery, event.languageCode) } } is SearchUiEvent.SetLanguageDropdownExpanded -> { isLanguageDropdownExpanded = event.expanded } is SearchUiEvent.SetSearchLanguage -> { isLanguageDropdownExpanded = false searchLocation(searchQuery, event.languageCode) } is SearchUiEvent.AddToHistory -> { viewModelScope.launch { localRepository.addToHistory( SearchResultEntity(cityId = event.cityId, city = event.city, lat = event.lat, lon = event.lon) ) } } is SearchUiEvent.RemoveFromHistory -> { viewModelScope.launch { localRepository.removeFromHistory( SearchResultEntity(id = event.id, cityId = event.cityId, city = event.city, lat = event.lat, lon = event.lon) ) } } } } }
0
Kotlin
1
2
eb6c7b47d90bde7fb0b35f985b20ea06872de0df
4,306
Weathering
MIT License
app/src/main/java/com/jetpack/multipledraggable/MainActivity.kt
MakeItEasyDev
417,903,626
false
{"Kotlin": 7977}
package com.jetpack.multipledraggable import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Colors import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember 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.input.pointer.consumeAllChanges import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.jetpack.multipledraggable.ui.theme.MultipleDraggableTheme import com.jetpack.multipledraggable.ui.theme.Purple500 import kotlin.math.roundToInt class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MultipleDraggableTheme { Surface(color = MaterialTheme.colors.background) { Column( modifier = Modifier .fillMaxSize() ) { Column( modifier = Modifier .fillMaxWidth() .height(55.dp) .background(Purple500), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Multiple Draggable Object", color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold ) } Column( modifier = Modifier .background(Color.White) .padding(15.dp) .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(25.dp), horizontalAlignment = Alignment.CenterHorizontally ) { MultipleDraggableObject(letter = "A", bgColor = Color(0xFFFF0000)) MultipleDraggableObject(letter = "B", bgColor = Color(0xFF00FF00)) MultipleDraggableObject(letter = "C", bgColor = Color(0xFF0000FF)) MultipleDraggableObject(letter = "D", bgColor = Color(0xFFFFF000)) MultipleDraggableObject(letter = "E", bgColor = Color(0xFF00FFF0)) } } } } } } } @Composable fun MultipleDraggableObject(letter: String, bgColor: Color) { val offsetX = remember { mutableStateOf(0f) } val offsetY = remember { mutableStateOf(0f) } Box( modifier = Modifier .offset { IntOffset( x = offsetX.value.roundToInt(), y = offsetY.value.roundToInt() ) } .pointerInput(Unit) { detectDragGestures { change, dragAmount -> change.consumeAllChanges() offsetX.value += dragAmount.x offsetY.value += dragAmount.y } } .size(80.dp) .clip(CircleShape) .background(bgColor), contentAlignment = Alignment.Center ) { Text( text = letter, fontSize = 30.sp, color = Color.White, textAlign = TextAlign.Center, fontWeight = FontWeight.Bold ) } }
0
Kotlin
1
1
2a11fd71ec4633646a3d84139be40d6be76541d6
4,454
Jetpack-Compose-Multiple-Draggable-Object
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/screens/Navigation.kt
hkawii
342,975,575
false
{"Kotlin": 55150}
/* * 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.example.androiddevchallenge.screens import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.androiddevchallenge.screens.home_list_screen.HomeView import com.example.androiddevchallenge.screens.pet_details_screen.PetView @Composable fun ComposeNavigation() { val navController = rememberNavController() NavHost( navController = navController, startDestination = "home_screen" ) { composable("home_screen") { HomeView(navController = navController) } composable("pet_screen/{caseID}") { backStackEntry -> backStackEntry.arguments?.getString("caseID")?.let { PetView(navController, it) } } } }
0
Kotlin
0
2
e3d6950c93a5b3008c63c06de5d47b61b8626767
1,461
Purr-House
Apache License 2.0
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/wall/methods/WallGetComment.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection") package name.anton3.vkapi.generated.wall.methods import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import name.anton3.vkapi.generated.common.objects.UserGroupFields import name.anton3.vkapi.generated.wall.objects.GetCommentResponse import name.anton3.vkapi.method.UserMethod import name.anton3.vkapi.method.VkMethod /** * [https://vk.com/dev/wall.getComment] * * Returns a comment on a post on a user wall or community wall. * * @property ownerId User ID or community ID. Use a negative value to designate a community ID. * @property commentId Comment ID. * @property fields No description */ data class WallGetComment( var ownerId: Long? = null, var commentId: Long, var fields: List<UserGroupFields>? = null ) : VkMethod<GetCommentResponse, UserMethod>("wall.getComment", jacksonTypeRef())
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
907
kotlin-vk-api
MIT License
kotlin-node/src/jsMain/generated/node/os/UserInfoStringOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package node.os sealed external interface UserInfoStringOptions { var encoding: node.buffer.BufferEncoding }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
168
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/docubox/data/remote/models/responses/StorageConsumption.kt
Vaibhav2002
499,822,014
false
{"Kotlin": 142319}
package com.docubox.data.remote.models.responses import com.google.gson.annotations.SerializedName data class StorageConsumption( @SerializedName("storageConsumption") val storageConsumption: String = "", @SerializedName("totalStorage") val totalStorage: String = "50" )
0
Kotlin
8
38
5e8bccbc4c6dd1cb3c004224a4a407ebc913ec12
289
DocuBox-AndroidApp
MIT License
app/src/main/java/com/masterplus/trdictionary/features/list/presentation/show_list/navigation/ShowListNavigation.kt
Ramazan713
634,957,286
false
{"Kotlin": 990286}
package com.masterplus.trdictionary.features.list.presentation.show_list.navigation import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.getValue import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.masterplus.trdictionary.features.list.presentation.show_list.ShowListPage import com.masterplus.trdictionary.features.list.presentation.show_list.ShowListViewModel const val RouteList = "ShowList" @ExperimentalMaterial3Api fun NavGraphBuilder.showListPage( onNavigateToArchive: ()->Unit, onNavigateToDetailList: (listId: Int)->Unit, onNavigateToSelectSavePoint: (String,List<Int>,Int)->Unit, onNavigateToSettings: ()->Unit, windowWidthSizeClass: WindowWidthSizeClass ){ composable(RouteList){ val listViewModel: ShowListViewModel = hiltViewModel() val state by listViewModel.state.collectAsStateWithLifecycle() ShowListPage( onNavigateToDetailList = onNavigateToDetailList, onNavigateToSelectSavePoint = onNavigateToSelectSavePoint, onNavigateToArchive = onNavigateToArchive, onNavigateToSettings = onNavigateToSettings, state = state, onEvent = listViewModel::onEvent, windowWidthSizeClass = windowWidthSizeClass ) } }
0
Kotlin
0
1
0aa1643c4347203f9339dfa4896bf176712472c9
1,540
Turkce-ve-Osmanlica-Sozluk
Apache License 2.0
lib/rabbit/src/main/kotlin/vdi/component/rabbit/RabbitInstance.kt
VEuPathDB
575,990,672
false
{"Kotlin": 614384, "Java": 211077, "RAML": 89879, "Makefile": 2331, "Dockerfile": 729, "Shell": 493}
package vdi.component.rabbit import com.rabbitmq.client.Channel import com.rabbitmq.client.Connection import kotlinx.coroutines.* import org.slf4j.LoggerFactory import kotlin.time.Duration.Companion.seconds private const val MaxChannelRetries = 5 private val RetryDelay = 1.seconds internal class RabbitInstance(private val con: Connection) { private val log = LoggerFactory.getLogger(javaClass) private var rChan = runBlocking { retryChannel() } suspend fun getChannel(): Channel { if (rChan.isOpen) return rChan return retryChannel().also { rChan = it } } fun close() { try { rChan.close() } catch (e: Throwable) { log.error("encountered error while closing rabbitmq channel", e) } try { con.close() } catch (e: Throwable) { log.error("encountered error while closing rabbitmq connection", e) } } private suspend fun retryChannel(attempt: Int = 1): Channel { if (!con.isOpen) throw RabbitConnectionClosedError("could not re-open closed channel, base connection is closed") else if (attempt > MaxChannelRetries) throw Exception("could not re-open closed channel after $MaxChannelRetries attempts") else return coroutineScope { withContext(Dispatchers.IO) { log.info("attempt $attempt/$MaxChannelRetries to reopen rabbitmq channel") try { con.createChannel() } catch (e: Throwable) { log.warn("failed to open a new channel on attempt $attempt/$MaxChannelRetries, retrying in $RetryDelay", e) delay(RetryDelay) retryChannel(attempt + 1) } } } } }
47
Kotlin
0
0
5639c59dc59bbc2e3960e34ea25e9d4db3f49c70
1,631
vdi-service
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/luna_rite/LunaRiteTakeSacrificeRewardRsp.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.activity.luna_rite import org.anime_game_servers.core.base.Version.GI_2_1_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.CommandType.* import org.anime_game_servers.core.base.annotations.proto.ProtoCommand import org.anime_game_servers.multi_proto.gi.data.general.Retcode @AddedIn(GI_2_1_0) @ProtoCommand(RESPONSE) internal interface LunaRiteTakeSacrificeRewardRsp { var retcode: Retcode var areaId: Int var index: Int var sacrificeRewardIndex: Int var sacrificeRewardList: List<Int> }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
632
anime-game-multi-proto
MIT License
app/src/main/kotlin/app/viewmodel/BaseViewModel.kt
levibostian
640,550,940
false
null
package app.viewmodel import android.app.Activity import android.os.Build import androidx.lifecycle.ViewModel import app.android.AndroidFeature import app.store.KeyValueStorage import app.ui.type.RuntimePermission import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow // Class that all ViewModels extend in this app. // Allows app to have extra functionality in it's ViewModels specific to this app. abstract class BaseViewModel(override val androidFeaturesUsedInViewModel: List<AndroidFeature>, private val keyValueStorage: KeyValueStorage): ViewModel(), ViewModelUsingAndroidFeatures { private var _missingRuntimePermissions: MutableStateFlow<List<RuntimePermission>> = MutableStateFlow(emptyList()) override val observeMissingPermissions: StateFlow<List<RuntimePermission>> = _missingRuntimePermissions // Call this function when your UI starts (onResume good place) and when user interacts with a permission pop-up so you should update permissions needed. override fun updateMissingPermissions(activity: Activity) { _missingRuntimePermissions.value = androidFeaturesUsedInViewModel.flatMap { it.getRequiredPermissions().filter { permission -> // Determining if a permission is missing (meaning you should ask for permission in UI) is a little complex. // A permission pop-up can show up twice (maybe only once on some OS versions). A user must deny it twice before the OS does not show a pop-up anymore. // Android's docs suggest asking for permission without showing an explanation for the first pop-up and then show a UI explanation after denying the permission for the first time. // I don't like that experience as I want the app to open when you first install it and not be asked to login, not be asked for permission, etc. // Therefore, we keep track of the first time we ask for permission and then we ask the OS if we should show a UI explantion for a second time. val hasNeverShownPermissionPopup = !keyValueStorage.hasAskedForPermission(permission) val doesOSSuggestShowingExplanation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.shouldShowRequestPermissionRationale(permission.string) } else { false } hasNeverShownPermissionPopup || doesOSSuggestShowingExplanation } } } // Call when you tell the OS to show the runtime permission pop-up override fun hasAskedForPermission(activity: Activity, permission: RuntimePermission) { keyValueStorage.permissionHasBeenAsked(permission) } }
8
Kotlin
0
0
f001dd86ce9c42220ce84272de8404b3fe888155
2,741
BatteryBird
MIT License
sample-android/src/main/java/com/chrynan/sample/ui/adapter/DiffDispatcher.kt
chRyNaN
51,400,387
false
null
package com.chrynan.sample.ui.adapter interface DiffDispatcher<VM : UniqueAdapterItem> { suspend fun dispatchDiff(diff: DiffResult<VM>) }
0
Kotlin
5
28
5a2e21c9b4789c878f0459e3d5c6fcfcbc66658d
144
chords
Apache License 2.0
modules/bridge/src/main/kotlin/ru/astrainteractive/discordbot/module/bridge/model/MessageData.kt
Astra-Interactive
584,452,095
false
{"Kotlin": 44477}
package ru.astrainteractive.discordbot.module.bridge.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.astrainteractive.messagebridge.messaging.model.MessageEvent @Serializable @SerialName("MessageData") internal sealed interface MessageData @Serializable @SerialName("StringMessageData") internal data class StringMessageData(val value: String) : MessageData @Serializable @SerialName("MessageEventData") internal data class MessageEventData(val event: MessageEvent) : MessageData
2
Kotlin
0
0
8ebededeb5876e7275850548e921aa464abc23b0
534
TelegramBridge
MIT License
basics/src/main/kotlin/com/example/demo/DemoApplication.kt
joshlong-attic
108,974,244
false
{"Shell": 12936, "Batchfile": 9988, "Kotlin": 9107}
package com.example.demo import org.jetbrains.exposed.spring.SpringTransactionManager import org.jetbrains.exposed.sql.* import org.springframework.beans.factory.InitializingBean import org.springframework.boot.ApplicationRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.context.annotation.Profile import org.springframework.context.support.beans import org.springframework.jdbc.core.JdbcOperations import org.springframework.jdbc.core.queryForObject import org.springframework.stereotype.Controller import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import org.springframework.transaction.support.TransactionTemplate import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.view.script.ScriptTemplateConfigurer import org.springframework.web.servlet.view.script.ScriptTemplateViewResolver @SpringBootApplication class DemoApplication { /* @Bean @Profile("exposed") fun platformTransactionManager(ds: DataSource) = SpringTransactionManager(ds) @Bean fun init(customerService: CustomerService) = ApplicationRunner { customerService.insert(Customer("A")) customerService.insert(Customer("B")) customerService.insert(Customer("C")) customerService.insert(Customer("D")) customerService.all().forEach { println(it) } }*/ } fun main(args: Array<String>) { SpringApplicationBuilder() .sources(DemoApplication::class.java) .initializers(beans { bean { val customerService = ref<CustomerService>() ApplicationRunner { customerService.insert(Customer("A")) customerService.insert(Customer("B")) customerService.insert(Customer("C")) customerService.insert(Customer("D")) customerService.all().forEach { println(it) } } } bean { ScriptTemplateConfigurer().apply { this.setScripts("scripts/render.kts") this.engineName = "kotlin" this.renderFunction = "render" this.isSharedEngine = false } } bean { ScriptTemplateViewResolver().apply { this.setSuffix(".kts") this.setPrefix("templates/") } } profile("exposed") { bean { SpringTransactionManager(ref()) } } }) .run(*args) } object Customers : Table() { val id = long("id").autoIncrement().primaryKey() val name = varchar("name", 255) } @Controller class CustomerController(private val customerService: CustomerService) { @GetMapping("/customers.php") fun customers() = ModelAndView("customers", mapOf("customers" to this.customerService.all())) } /* @Configuration class TemplateViewConfiguration { @Bean fun viewResolver() = ScriptTemplateViewResolver().apply { this.setSuffix(".kts") this.setPrefix("templates/") } @Bean fun viewConfigurer() = ScriptTemplateConfigurer().apply { this.setScripts("scripts/render.kts") this.engineName = "kotlin" this.renderFunction = "render" this.isSharedEngine = false } } */ @Service @Transactional @Profile("exposed") class ExposedCustomerService(private val transactionTemplate: TransactionTemplate) : CustomerService, InitializingBean { override fun all(): Collection<Customer> = Customers.selectAll().map { Customer(it[Customers.name], it[Customers.id]) } override fun afterPropertiesSet() { this.transactionTemplate.execute { SchemaUtils.create(Customers) } } override fun insert(c: Customer) { Customers.insert { it[Customers.name] = c.name } } override fun byId(id: Long): Customer? = Customers.select { Customers.id.eq(id) }.map { Customer(it[Customers.name], it[Customers.id]) }.firstOrNull() } @Service @Transactional @Profile("jdbc") class JdbcCustomerService(private val jdbcOperations: JdbcOperations) : CustomerService { override fun all(): Collection<Customer> = this.jdbcOperations.query("SELECT * FROM CUSTOMERS") { rs, i -> Customer(rs.getString("NAME"), rs.getLong("ID")) } override fun insert(c: Customer) { this.jdbcOperations.execute("INSERT INTO CUSTOMERS(NAME) VALUES(?)") { it.setString(1, c.name) it.execute() } } override fun byId(id: Long): Customer? = this.jdbcOperations.queryForObject("select * from customers where id=?", id) { rs, i -> Customer(rs.getString("NAME"), rs.getLong("ID")) } } interface CustomerService { fun all(): Collection<Customer> fun insert(c: Customer) fun byId(id: Long): Customer? } data class Customer(val name: String, var id: Long? = null)
0
Shell
0
8
24ed2a7d9c1a466df73d8a581f5532783f10eb8b
5,376
kotlin-conf-2017
Apache License 2.0
src/main/kotlin/com/simonschoof/tsmct/domain/Events.kt
simonschoof
677,126,234
false
{"Kotlin": 25981}
package com.simonschoof.tsmct.domain data class InventoryItemCreated( val name: String ) : Event() data class InventoryItemNameChanged( val newName: String ): Event() data class InventoryItemsRemoved( val count: Int ): Event() data class InventoryItemsCheckedIn( val count: Int ): Event() data class InventoryItemMaxQuantityChanged( val newMaxQuantity: Int ): Event() class InventoryItemDeactivated : Event()
0
Kotlin
0
0
e5a49bba53e494d15f0fd40e16f87b7b50b68f29
434
tsmct
MIT License
datasource/src/main/kotlin/gq/kirmanak/mealient/datasource/ktor/TokenChangeListenerKtor.kt
kirmanak
431,195,533
false
{"Kotlin": 476781}
package gq.kirmanak.mealient.datasource.ktor import gq.kirmanak.mealient.datasource.TokenChangeListener import gq.kirmanak.mealient.logging.Logger import io.ktor.client.HttpClient import io.ktor.client.plugins.auth.Auth import io.ktor.client.plugins.auth.providers.BearerAuthProvider import io.ktor.client.plugins.plugin import javax.inject.Inject internal class TokenChangeListenerKtor @Inject constructor( private val httpClient: HttpClient, private val logger: Logger, ) : TokenChangeListener { override fun onTokenChange() { logger.v { "onTokenChange() called" } httpClient.plugin(Auth) .providers .filterIsInstance<BearerAuthProvider>() .forEach { logger.d { "onTokenChange(): removing the token" } it.clearToken() } } }
16
Kotlin
2
99
6f8a9520f3736ae641e4541d24afb0dcf9623ea0
840
Mealient
MIT License
app/src/main/java/org/covidwatch/android/data/UserFlow.kt
atiqaraj
265,264,915
true
{"Kotlin": 104726}
package org.covidwatch.android.data sealed class UserFlow object FirstTimeUser : UserFlow() object ReturnUser : UserFlow()
0
null
0
0
c4484fc1a706e542aecfcf4f0377e48fb6cc1bc2
125
covidwatch-android-en
Apache License 2.0
src/main/kotlin/sh/astrid/mizuki/commands/Reload.kt
astridlol
588,225,747
false
null
package sh.astrid.mizuki.commands import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.bukkit.entity.Player import sh.astrid.mizuki.Mizuki class Reload : CommandExecutor { init { Mizuki.instance.getCommand("reload")!!.setExecutor(this); } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { val canExecute = (sender is ConsoleCommandSender || sender is Player && sender.isOp) if(!canExecute) return false Mizuki.instance.reloadConfig(); sender.sendMessage("[Mizuki] Successfully reloaded config.") return true } }
2
Kotlin
2
5
5e3fda449024ed1bb987fea80653ba5406dbc6d4
767
Mizuki
Apache License 2.0
src/main/kotlin/hullmods/Retreat.kt
isturdy
169,434,831
false
null
package com.github.isturdy.automaticorders.hullmods import com.fs.starfarer.api.combat.BaseHullMod import com.fs.starfarer.api.combat.ShipAPI class DirectRetreat : BaseHullMod() { companion object { const val ID = "automatic_orders_direct_retreat" } } class RetreatNoMissiles : BaseHullMod() { companion object { const val ID = "automatic_orders_retreat_no_missiles" } } abstract class BaseRetreatThreshold(val id: String) : BaseHullMod() { companion object { val IDS = setOf(RetreatTenPPT().id, RetreatZeroPPT().id, RetreatMalfunction().id, RetreatCritical().id, NoCrRetreat().id, NoRetreat().id) } override fun isApplicableToShip(ship: ShipAPI): Boolean { for (hullMod in ship.variant.hullMods) { if (hullMod in IDS && hullMod != id) return false } return true } override fun getUnapplicableReason(ship: ShipAPI?): String { return "Personality overrides are mutually exclusive." } } class RetreatTenPPT : BaseRetreatThreshold("automatic_orders_retreat_ten_ppt") class RetreatZeroPPT : BaseRetreatThreshold("automatic_orders_retreat_zero_ppt") class RetreatMalfunction : BaseRetreatThreshold("automatic_orders_retreat_malfunction") class RetreatCritical : BaseRetreatThreshold("automatic_orders_retreat_critical") class NoCrRetreat : BaseRetreatThreshold("automatic_orders_no_cr_retreat") class NoRetreat : BaseRetreatThreshold("automatic_orders_no_retreat")
0
Kotlin
2
2
893d36e72e523655e560ab632538936e75bedeb9
1,474
automatic-orders
MIT License
app/src/main/java/com/demo/virginmoneydemo/adapters/HomePagerAdapter.kt
arpitbandil
515,951,286
false
{"Kotlin": 30713}
package com.demo.virginmoneydemo.adapters import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import com.demo.virginmoneydemo.ui.people.PeopleFragment import com.demo.virginmoneydemo.ui.rooms.RoomsListFragment const val PEOPLES_PAGE_INDEX = 0 const val ROOM_LIST_PAGE_INDEX = 1 class HomePagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { private val tabFragmentsCreators: Map<Int, () -> Fragment> = mapOf( PEOPLES_PAGE_INDEX to { PeopleFragment() }, ROOM_LIST_PAGE_INDEX to { RoomsListFragment() } ) override fun getItemCount() = tabFragmentsCreators.size override fun createFragment(position: Int): Fragment { return tabFragmentsCreators[position]?.invoke() ?: throw IndexOutOfBoundsException() } }
0
Kotlin
0
0
7b1c5a53bdd718e74c9f5fc6e9a985a95206185f
810
mvvm_with_di_demo
MIT License
src/commonMain/kotlin/jp.kukv.ulid/Example.kt
kukv
629,768,691
false
null
package jp.kukv.ulid fun echo(value: String): String = "echo by $value"
3
Kotlin
0
1
2700714a6c52bc57e5eb0fdd1a40248d812ba0a4
73
kotlin-ulid
MIT License
library/src/main/java/com/chenfei/util/ActivityIntentQueue.kt
chenfei0928
130,954,695
false
null
package com.chenfei.util import android.content.Context import android.content.Intent import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.chenfei.util.kotlin.removeSelf import java.util.* /** * activity初始化流程中可能需要连续启动多个子activity, * 但这些activity可能会有先后顺序,或它们之间不应覆盖,要one by one的显示 * * @author ChenFei(chenfei0928@gmail.com) * @date 2020-01-07 15:07 */ class ActivityIntentQueue : Fragment() { private val queue: Queue<Any> = LinkedList() private val activityResultCallback: Queue<Function2<Int, Intent?, Unit>> = LinkedList() override fun onAttach(context: Context) { super.onAttach(context) pollIntentOrRemoveSelf() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE) { // 通知回调 activityResultCallback .poll() ?.invoke(resultCode, data) // 尝试调用下一个intent pollIntentOrRemoveSelf() } } private fun pollIntentOrRemoveSelf() { when (val intent = queue.poll()) { null -> { removeSelf() } is Intent -> { startActivityForResult(intent, REQUEST_CODE) } is ShowFuncWithDismissListener -> { intent.show { if (isAdded) { pollIntentOrRemoveSelf() } } } else -> { throw IllegalArgumentException("无法处理的请求类型: ${intent.javaClass}") } } } @JvmOverloads fun offer( intent: Intent, callback: (resultCode: Int, data: Intent?) -> Unit = { _, _ -> } ): ActivityIntentQueue { queue.offer(intent) activityResultCallback.offer(callback) return this } fun offer(showWithDismissListener: ShowFuncWithDismissListener): ActivityIntentQueue { queue.offer(showWithDismissListener) return this } fun emit(fragmentManager: FragmentManager) { if (isAdded || queue.isEmpty()) { return } fragmentManager .beginTransaction() .add(this, "ActivityIntentQueue") .commitAllowingStateLoss() } interface ShowFuncWithDismissListener { fun show(dismissListener: () -> Unit) } companion object { private const val REQUEST_CODE = 1 } }
0
Kotlin
0
0
3a1a4fb80e47f4f5d7ac1843cdda3bb0c9de4aba
2,552
Util
MIT License
src/main/kotlin/org/celtric/kotlin/html/input.kt
celtric
121,420,012
false
null
package org.celtric.kotlin.html fun input( // Mandatory type: String, // Optional accept: String? = null, autocomplete: String? = null, autofocus: Boolean = false, capture: Boolean = false, checked: Boolean = false, disabled: Boolean = false, list: String? = null, max: String? = null, maxlength: Int? = null, min: String? = null, minlength: Int? = null, multiple: Boolean = false, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean = false, required: Boolean = false, size: Int? = null, step: String? = null, value: String? = null, // Global classes: String? = null, id: String? = null, title: String? = null, // Custom other: Attributes = emptyMap(), data: Attributes = emptyMap() ) = EmptyBlockElement("input", AllAttributes(mapOf( "type" to type, "accept" to accept, "autocomplete" to autocomplete, "autofocus" to autofocus, "capture" to capture, "checked" to checked, "disabled" to disabled, "list" to list, "max" to max, "maxlength" to maxlength, "min" to min, "minlength" to minlength, "multiple" to multiple, "name" to name, "pattern" to pattern, "placeholder" to placeholder, "readonly" to readonly, "required" to required, "size" to size, "step" to step, "value" to value, "class" to classes, "id" to id, "title" to title ), other, data))
1
Kotlin
3
25
70cd501bb534ad84f8c8c3a8f8fb18dddd7054e4
1,512
kotlin-html
Apache License 2.0
shared/src/commonMain/kotlin/dev/pinkroom/pokedex/data/repository/PokedexRepository.kt
pink-room
584,850,613
false
null
package dev.pinkroom.pokedex.data.repository import com.kuuurt.paging.multiplatform.Pager import com.kuuurt.paging.multiplatform.PagingConfig import com.kuuurt.paging.multiplatform.PagingData import com.kuuurt.paging.multiplatform.PagingResult import com.kuuurt.paging.multiplatform.helpers.cachedIn import dev.pinkroom.pokedex.data.models.Pokemon import dev.pinkroom.pokedex.data.service.PokedexService import dev.pinkroom.pokedex.local.PokemonDao import dev.pinkroom.pokedex.utils.CommonFlow import dev.pinkroom.pokedex.utils.asCommonFlow import dev.pinkroom.pokedex.utils.toPokemon import dev.pinkroom.pokedex.utils.toPokemonModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.MainScope import org.koin.core.component.KoinComponent class PokedexRepository( private val pokedexService: PokedexService, private val pokemonDao: PokemonDao, ) : KoinComponent { companion object { private const val PAGING_SIZE = 20L } var scope: CoroutineScope = MainScope() @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) val pokedexPagingData: CommonFlow<PagingData<Pokemon>> get() = pager.pagingData.cachedIn(scope).asCommonFlow() @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) val pager = Pager( clientScope = scope, config = PagingConfig(pageSize = PAGING_SIZE.toInt(), enablePlaceholders = false), initialKey = 0L, getItems = { key, _ -> PagingResult( items = getPokemons(key), currentKey = key, prevKey = { null }, nextKey = { key + 1 } ) } ) private suspend fun getPokemons(key: Long): List<Pokemon> { val local = pokemonDao.get(PAGING_SIZE, key * PAGING_SIZE) return if (local.isEmpty()) getPokemonsRemote(key) else local.map { it.toPokemon() } } private suspend fun getPokemonsRemote(key: Long): List<Pokemon> = try { val result = pokedexService.getPokemons(PAGING_SIZE, key * PAGING_SIZE) if (key == 0L) pokemonDao.deleteAll() pokemonDao.insert(result.results.map { it.toPokemonModel() }) result.results } catch (e: Exception) { emptyList() } }
1
Kotlin
1
8
380c65b2fe047dc83eecacacee9e923f8fb8c38f
2,343
Pokedex
Apache License 2.0
src/main/kotlin/samples/follow/UnfollowNonFollowers.kt
bardimardy
301,651,456
true
{"Kotlin": 249618}
package samples.follow import bot.InstagramBot import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.runBlocking @ExperimentalCoroutinesApi fun main() { val username = "your_instagram_username" val password = "your_instagram_password" val bot = InstagramBot() bot.prepare(username) bot.login(username, password) runBlocking { bot.unfollowNonFollowers().collect { println(it) } } }
0
null
0
0
fc9d38dced83679ae1422cf5f0dc04974808e3cb
484
insta-bot
MIT License
src/commonMain/kotlin/com/ashampoo/kim/common/FourCC.kt
Ashampoo
647,186,626
false
null
/* * Copyright 2024 Ashampoo GmbH & Co. KG * * 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.ashampoo.kim.common /** * See https://en.wikipedia.org/wiki/FourCC * * PNG Chunks and HEIC boxes share the concept where the four * type bytes of a chunk/box translate to human readable strings * like "IHDR" & "IDAT" for PNG and "FTYP" & "META" for HEIC. * * This excension function converts an int to such an type string. */ @Suppress("MagicNumber") fun Int.toFourCCTypeString(): String = charArrayOf( (0xFF and (this shr 24)).toChar(), (0xFF and (this shr 16)).toChar(), (0xFF and (this shr 8)).toChar(), (0xFF and (this shr 0)).toChar() ).concatToString()
8
null
8
172
5e6cd23c52abf8c840b235eb68744a9ab135c235
1,226
kim
Apache License 2.0
resume-ab-logics/src/main/kotlin/ru/otus/otuskotlin/resume/logics/workers/RepoUpdate.kt
otuskotlin
377,710,400
false
null
package ru.otus.otuskotlin.resume.logics.workers import ru.otus.otuskotlin.resume.backend.common.context.CorStatus import ru.otus.otuskotlin.resume.backend.common.context.ResumeContext import ru.otus.otuskotlin.resume.backend.repo.common.DbResumeIdRequest import ru.otus.otuskotlin.resume.backend.repo.common.DbResumeModelRequest import ru.otus.otuskotlin.resume.cor.ICorChainDsl import ru.otus.otuskotlin.resume.cor.handlers.worker internal fun ICorChainDsl<ResumeContext>.repoUpdate(title: String) = worker { this.title = title description = "Data from request updates the DB Repository object" on { status == CorStatus.RUNNING } handle { val result = resumeRepo.update(DbResumeModelRequest(resume = requestResume)) val resultValue = result.result if (result.isSuccess && resultValue != null) { responseResume = resultValue } else { result.errors.forEach { addError(it) } } } }
0
Kotlin
0
0
920d87731a128acc1c113acd393dcc09ed01411a
967
ok-202105-resume-ab
MIT License
domain/src/main/java/com/mctech/stocktradetracking/domain/stock_share/interaction/strategies/ComputeBalanceStrategy.kt
MayconCardoso
258,571,301
false
null
package com.mctech.stocktradetracking.domain.stock_share.interaction.strategies import com.mctech.stocktradetracking.domain.extentions.round import com.mctech.stocktradetracking.domain.stock_share.entity.StockShare import com.mctech.stocktradetracking.domain.stock_share.entity.StockShareFinalBalance /** * This class will compute the balance of a list of stocks into a [StockShareFinalBalance] instance. */ abstract class ComputeBalanceStrategy { fun execute(stockShareList: List<StockShare>): StockShareFinalBalance { var balance = 0.0 var investment = 0.0 for (stock in stockShareList) { investment += stock.getFinalStockPrice() balance += getConsideredBalance(stock) } val variation = if (investment == 0.0) { 0.0 } else { (((investment + balance) / investment * 100) - 100).round(2) } return StockShareFinalBalance( balance, investment, variation ) } abstract fun getConsideredBalance(item: StockShare): Double }
14
Kotlin
14
91
0c8757ea6822eb5d65cf39d82e60ede13bf55346
1,009
StockTradeTracking
Apache License 2.0
token-service/src/main/java/org/p2p/token/service/model/UpdateTokenMetadataResult.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.token.service.model import org.p2p.core.token.TokensMetadataInfo sealed interface UpdateTokenMetadataResult { object NoUpdate : UpdateTokenMetadataResult data class NewMetadata(val remoteTokensMetadata: TokensMetadataInfo) : UpdateTokenMetadataResult data class Error(val throwable: Throwable) : UpdateTokenMetadataResult }
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
357
key-app-android
MIT License
src/test/kotlin/com/melardev/spring/restcrud/RestCrudApplicationTests.kt
melardev
190,716,423
false
null
package com.melardev.spring.restcrud import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest class RestCrudApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
73a5563226ce39a2950ea0187b825372b30a8265
328
KotlinSpringBootApiJpaCrud
MIT License
catan/src/main/kotlin/design/cardia/game/catan/game/usecase/PlaceRoad.kt
Spanner41
419,025,235
false
{"Kotlin": 35031}
package design.cardia.game.catan.game.usecase import design.cardia.game.catan.entity.Catan import design.cardia.game.catan.event.RoadBuiltEvent import design.cardia.game.engine.event.EventEnqueue import org.springframework.stereotype.Service import java.util.UUID @Service class PlaceRoad( private val eventQueue: EventEnqueue<Catan> ) { operator fun invoke(game: UUID, player: UUID, edge: UUID) { val event = RoadBuiltEvent(game, player, edge) eventQueue.put(event) } }
0
Kotlin
0
0
1304ad30845c9426235c8fff9d0445961817967b
501
kt-board-game-engine
MIT License
src/main/kotlin/com/robotutor/iot/accounts/models/Policy.kt
IOT-echo-system
768,195,181
false
{"Kotlin": 180103, "HTML": 428, "Shell": 151, "Dockerfile": 130}
package com.robotutor.iot.accounts.models import org.bson.types.ObjectId import org.springframework.data.annotation.Id import org.springframework.data.annotation.TypeAlias import org.springframework.data.mongodb.core.index.Indexed import org.springframework.data.mongodb.core.mapping.Document const val POLICY_COLLECTION = "policies" @TypeAlias("Policy") @Document(POLICY_COLLECTION) data class Policy( @Id var id: ObjectId? = null, @Indexed(unique = true) val policyId: PolicyId, @Indexed(unique = true) val name: String, ) typealias PolicyId = String
0
Kotlin
0
0
75c6801f3288d7988a43af1c7f5c51dc1ea56418
581
cloud-backend-service
MIT License
nebulosa-xisf/src/main/kotlin/nebulosa/xisf/Xisf.kt
tiagohm
568,578,345
false
{"Kotlin": 2562989, "TypeScript": 464111, "HTML": 237584, "JavaScript": 49239, "SCSS": 13679, "Python": 2817, "Makefile": 160}
package nebulosa.xisf import nebulosa.image.format.Hdu import nebulosa.image.format.ImageRepresentation import nebulosa.io.SeekableSource import okio.Sink import java.util.* /** * Represents a XISF image. */ open class Xisf : LinkedList<Hdu<*>>, ImageRepresentation { constructor() : super() constructor(hdus: Collection<Hdu<*>>) : super(hdus) final override fun read(source: SeekableSource) { addAll(XisfFormat.read(source)) } final override fun write(sink: Sink) { XisfFormat.write(sink, this) } }
4
Kotlin
2
4
b122c890df5ad63f828c468cb600310ddbcec99b
548
nebulosa
MIT License
data/src/main/java/com/example/data/core/DatabaseModule.kt
jorgela92
183,626,476
false
null
package com.example.data.core import com.google.firebase.firestore.FirebaseFirestore import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DatabaseModule { @Provides @Singleton fun providesFirebaseFirestore(): FirebaseFirestore = FirebaseFirestore.getInstance() }
0
Kotlin
3
0
744642feba9473bc15fc98ef8f6ecc2d094f38ba
312
ChatApp-Android
MIT License
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/report/model/DotCoverClass.kt
JetBrains
49,584,664
false
{"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
package jetbrains.buildServer.dotcover.report.model import jetbrains.coverage.report.ClassInfo import jetbrains.coverage.report.Entry class DotCoverClass(private val _namespace: NamespaceInfo, name: String, private val _coveredFiles: CoveredFiles) : ClassInfo, ClassHolder { private val _name: String private val _innerClasses = ArrayList<ClassInfo>(0) private val _methods = AdditiveValue() private val _statements = AdditiveValue() init { _name = _namespace.makeClassName(name) } override fun addClassInfo(info: ClassInfo) { _innerClasses.add(info) } override fun getModule(): String { return _namespace.assembly.assemblyName } fun setMethodsCoverage(total: Int, covered: Int) { _methods.increment(total, covered) } fun addStatementCoverage(total: Int, covered: Int) { _statements.increment(total, covered) } override fun getStatementStats(): Entry? { return _statements.entry } override fun getName(): String { return _name } override fun getNamespace(): String { return _namespace.namespaceName } override fun getFQName(): String { return "$namespace.$name" } override fun getMethodStats(): Entry { return _methods.entry } override fun getBlockStats(): Entry? { return null } override fun getLineStats(): Entry? { return null } override fun getInnerClasses(): Collection<ClassInfo> { return _innerClasses } fun asNamespace(): NamespaceInfo { return _namespace.forClass(this) } override fun getCoveredFiles(): CoveredFiles { return _coveredFiles } }
3
Kotlin
25
94
cdecbf2c7721a40265a031453262614809d5378d
1,768
teamcity-dotnet-plugin
Apache License 2.0
2021/src/main/kotlin/day23.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import Day23.Cell.EMPTY import utils.Parser import utils.Point3i import utils.Solution fun main() { Day23.run() } object Day23 : Solution<Day23.Burrow>() { override val name = "day23" override val parser = Parser.lines.map { lines -> val roomCells = lines.drop(2).filter { "#########" !in it } .map { it.substring(3, 10).split('#').map { Cell.valueOf(it) } } val rooms = (0..3).map { idx -> Room(roomCells.map { it[idx] }) } Burrow(List(size = 7) { EMPTY }, rooms) } data class Burrow( val hallway: List<Cell>, // always size=7 val rooms: List<Room>, // always size=4 ) { val solved: Boolean get() { for (room in rooms.indices) { for (cell in rooms[room].cells) { if (cell.room != room) { return false } } } return true } fun swap(hallwayIndex: Int, roomIndex: Int): Burrow { val hallwayCell = hallway[hallwayIndex] val cellIndex = if (hallwayCell == EMPTY) { rooms[roomIndex].cells.indexOfFirst { it != EMPTY } } else { rooms[roomIndex].cells.indexOfLast { it == EMPTY } } val roomCell = rooms[roomIndex].cells[cellIndex] require(hallway[hallwayIndex] == EMPTY || rooms[roomIndex].cells[cellIndex] == EMPTY) { "Can't swap if one of the places isn't empty" } return copy( hallway = List(size = 7) { if (it == hallwayIndex) roomCell else hallway[it] }, rooms = List(size = 4) { if (it == roomIndex) { rooms[it].copy(cells = rooms[it].cells.mapIndexed { index, cell -> if (index == cellIndex) hallway[hallwayIndex] else cell }) } else rooms[it] } ) } override fun toString(): String { return buildString { append("#############\n") append("#${hallway[0]}${hallway[1]}.${hallway[2]}.${hallway[3]}.${hallway[4]}.${hallway[5]}${hallway[6]}#\n") val cells = rooms.first().cells.size for (i in 0 until cells) { if (i == 0) { append("###") } else { append(" #") } for (room in rooms) { append("${room.cells[i]}#") } if (i == 0) { append("##\n") } else { append(" \n") } } append(" ######### ") } } } data class Room( val cells: List<Cell> // size = arbitrary ) enum class Cell(val energy: Int, val room: Int) { EMPTY(0, -1), A(1, 0), B(10, 1), C(100, 2), D(1000, 3); override fun toString() = when (this) { EMPTY -> "." else -> this.name } } fun canMove(burrow: Burrow, from: Int, roomIndex: Int): Boolean { val left = roomIndex + 1 val right = roomIndex + 2 if (from <= left) { return burrow.hallway.subList(from + 1, left + 1).all { it == EMPTY } } else { return burrow.hallway.subList(right, from).all { it == EMPTY } } } val hallwayCoords = listOf( Point3i(0, 0, 0), Point3i(1, 0, 0), Point3i(3, 0, 0), Point3i(5, 0, 0), Point3i(7, 0, 0), Point3i(9, 0, 0), Point3i(10, 0, 0), ) val roomCoords = listOf( Point3i(2, 1, 0), Point3i(4, 1, 0), Point3i(6, 1, 0), Point3i(8, 1, 0), ) fun cost(hallway: Int, room: Int, cell: Cell, cellIndex: Int): Long { val dist = hallwayCoords[hallway].distanceManhattan(roomCoords[room]) + cellIndex return (dist.toLong() * cell.energy).also { require(it > 0) } } fun moveHtoR(burrow: Burrow, from: Int): Pair<Burrow, Long>? { val cell = burrow.hallway[from] if (cell == EMPTY) { return null } val room = cell.room val cellIndex = burrow.rooms[room].cells.indexOfLast { it == EMPTY } if (cellIndex == -1) { return null } for (i in cellIndex + 1 until burrow.rooms[room].cells.size) { if (burrow.rooms[room].cells[i] != cell) { return null } } if (canMove(burrow, from, room)) { return burrow.swap(from, room) to cost(from, room, cell, cellIndex) } return null } fun moveRtoH(burrow: Burrow, fromRoom: Int, to: Int): Pair<Burrow, Long>? { val room = burrow.rooms[fromRoom] val cellIndex = burrow.rooms[fromRoom].cells.indexOfFirst { it != EMPTY } if (cellIndex == -1) { return null } if (burrow.hallway[to] != EMPTY) { return null } if (!canMove(burrow, to, fromRoom)) { return null } val cell = burrow.rooms[fromRoom].cells[cellIndex] if (cell.room == fromRoom) { if (burrow.rooms[fromRoom].cells.subList(cellIndex + 1, burrow.rooms[fromRoom].cells.size).all { it.room == fromRoom }) { // all in place return null } } return burrow.swap(to, fromRoom) to cost(to, fromRoom, cell, cellIndex) } fun solve(input: Burrow): Long? { val seenStates = mutableMapOf<Burrow, Long>() val stack = ArrayDeque<Pair<List<Burrow>, Long>>() stack.add(listOf(input) to 0L) var best = input to Long.MAX_VALUE while (stack.isNotEmpty()) { val (burrows, cost) = stack.removeLast() val burrow = burrows.last() val seenCost = seenStates[burrow] if (seenCost != null && seenCost <= cost) { // prune this search path continue } seenStates[burrow] = cost if (cost > best.second) { // prune this search path continue } if (burrow.solved) { if (cost < best.second) { best = burrow to cost } continue } for (index in burrow.hallway.indices) { moveHtoR(burrow, index)?.let { (newBurrow, moveCost) -> stack.add(burrows + newBurrow to cost + moveCost) } } for (room in burrow.rooms.indices) { for (hallway in burrow.hallway.indices) { moveRtoH(burrow, room, hallway)?.let { (newBurrow, moveCost) -> stack.add(burrows + newBurrow to cost + moveCost) } } } } return best.second } override fun part1(input: Burrow): Long? { return solve(input.copy( rooms = input.rooms.map { Room(listOf(it.cells.first(), it.cells.last())) } )) } override fun part2(input: Burrow): Long? { return solve(input) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
6,358
aoc_kotlin
MIT License
browser-kotlin/src/jsMain/kotlin/web/cssom/MediaQueryListEvent.types.kt
karakum-team
393,199,102
false
{"Kotlin": 6915863}
// Automatically generated - do not modify! package web.cssom import seskar.js.JsValue import seskar.js.JsVirtual import web.events.EventTarget import web.events.EventType @JsVirtual sealed external class MediaQueryListEventTypes : MediaQueryListEventTypes_deprecated { @JsValue("change") fun <C : EventTarget> change(): EventType<MediaQueryListEvent<C>> }
0
Kotlin
7
31
d1315f1524758eb6883a4f7e0a0da46816152ed8
373
types-kotlin
Apache License 2.0
demo/src/main/java/com/rozetkapay/demo/presentation/menu/MenuScreen.kt
rozetkapay
869,498,229
false
{"Kotlin": 223681}
package com.rozetkapay.demo.presentation.menu import android.content.res.Configuration 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.rozetkapay.demo.presentation.components.ToolbarTitle import com.rozetkapay.demo.presentation.theme.RozetkaPayDemoTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun MenuScreen( title: String = "Rozetka Pay Demo", subtitle: String? = null, onNavigationEvent: (Route) -> Unit, ) { Scaffold( topBar = { TopAppBar( title = { Column { ToolbarTitle( title = title, subtitle = subtitle ) } } ) }, ) { innerPadding -> Column( modifier = Modifier .padding(innerPadding) .fillMaxSize() .padding(16.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { InfoCard() Spacer(modifier = Modifier.height(32.dp)) Text( text = "Choose an option to try:", style = MaterialTheme.typography.titleMedium ) Spacer(modifier = Modifier.height(8.dp)) MenuButton( text = "Tokenize card", onClick = { onNavigationEvent(Route.Tokenization) } ) MenuButton( text = "Make a payment", onClick = { onNavigationEvent(Route.Payment) } ) } } } @Composable private fun InfoCard() { Card( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceContainer, ), modifier = Modifier .widthIn(max = 500.dp) .fillMaxWidth() ) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), ) { Icon( imageVector = Icons.Outlined.Info, contentDescription = "icon-lamp" ) Column( verticalArrangement = Arrangement.spacedBy(4.dp) ) { Text( text = "Welcome to Rozetka Pay Demo!", modifier = Modifier.padding(start = 16.dp), style = MaterialTheme.typography.titleMedium ) Text( text = "This is a demo application for Rozetka Pay SDK integration. You can try different features of the SDK here.", modifier = Modifier.padding(start = 16.dp), style = MaterialTheme.typography.bodyMedium ) } } } } @Composable private fun MenuButton( text: String, enabled: Boolean = true, onClick: () -> Unit, ) { Button( modifier = Modifier .width(280.dp) .height(56.dp), onClick = onClick, enabled = enabled ) { Text(text = text) } } @Composable @Preview @Preview("Dark Theme", uiMode = Configuration.UI_MODE_NIGHT_YES) private fun MenuScreenPreview() { RozetkaPayDemoTheme { MenuScreen( onNavigationEvent = {} ) } }
0
Kotlin
0
0
da2574a3a8a6a9e2f04a2b47a75221c8d4c8faa8
4,706
android-sdk
MIT License
src/main/kotlin/nvd/NVDResponseStructures/extensions/metricToBaseData.kt
vobbla16
605,997,235
false
null
package nvd.NVDResponseStructures.extensions import nvd.returnStructures.MetricBaseData import nvd.returnStructures.MetricBaseDataVersion import nvd.NVDResponseStructures.Metrics fun Metrics.toBaseData(): MetricBaseData { if (this.cvssMetricV31 != null) { return MetricBaseData( MetricBaseDataVersion.CVSSv31, this.cvssMetricV31[0].cvssData.baseScore.toFloat(), this.cvssMetricV31[0].cvssData.baseSeverity, this.cvssMetricV31[0].cvssData.vectorString ) } else if(this.cvssMetricV30 != null) { return MetricBaseData( MetricBaseDataVersion.CVSSv30, this.cvssMetricV30[0].cvssData.baseScore.toFloat(), this.cvssMetricV30[0].cvssData.baseSeverity, this.cvssMetricV30[0].cvssData.vectorString ) } else { return MetricBaseData( MetricBaseDataVersion.CVSSv2, this.cvssMetricV2!![0].cvssData.baseScore.toFloat(), this.cvssMetricV2[0].baseSeverity, this.cvssMetricV2[0].cvssData.vectorString ) } }
0
Kotlin
0
0
2a2ce4225793dd79cfa43c0538b4c8452386d447
1,098
verchk
MIT License
src/commonMain/kotlin/matt/obs/prop/typed/typed.kt
mgroth0
521,720,515
false
null
@file:OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class, ExperimentalSerializationApi::class) package matt.obs.prop.typed import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.CompositeDecoder import kotlinx.serialization.encoding.CompositeEncoder import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.serializer import matt.lang.nametoclass.classForName import matt.obs.prop.BindableProperty import kotlin.reflect.KClass @OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class) class TypedBindablePropertySerializer<T>(private val dataSerializer: KSerializer<T>): KSerializer<TypedBindableProperty<T>> { override val descriptor: SerialDescriptor = dataSerializer.descriptor override fun serialize(encoder: Encoder, value: TypedBindableProperty<T>) { /*@Suppress("UNCHECKED_CAST")*/ /*(encoder as JsonEncoder).encodeJsonElement( dataSerializer.serialize(value.value) Json.encodeToJsonElement(dataSerializer, value.value) *//*Json.encodeToJsonElement((value.cls).serializer() as KSerializer<T>, value.value)*//* )*/ dataSerializer.serialize(encoder, value.value) } override fun deserialize(decoder: Decoder): TypedBindableProperty<T> { /*val jsonDecoder = decoder as JsonDecoder*/ /*val element = jsonDecoder.decodeJsonElement()*/ val value = dataSerializer.deserialize(decoder) val valueDescriptor = dataSerializer.descriptor val cls = classForName(valueDescriptor.serialName) // println("value=${value}") // println("valueDescriptor.serialName=${valueDescriptor.serialName}") // println("cls=${cls}") val goodClass = cls as KClass<*> return TypedBindableProperty( cls = goodClass, nullable = valueDescriptor.isNullable, value = value ) } } inline fun <reified T> typedBindableProperty(value: T) = TypedBindableProperty(T::class, null is T, value) @OptIn(InternalSerializationApi::class) @Serializable(with = TypedBindablePropertySerializer::class) class TypedBindableProperty<T>(val cls: KClass<*>, val nullable: Boolean, value: T): BindableProperty<T>(value) { fun encode(encoder: CompositeEncoder, index: Int) { val ser = cls.serializer() @Suppress("UNCHECKED_CAST") encoder.encodeSerializableElement<T>( descriptor = ser.descriptor, index = index, serializer = ser as SerializationStrategy<T>, value = value ) } fun decode(decoder: CompositeDecoder, index: Int) { val ser = cls.serializer() @Suppress("UNCHECKED_CAST") val loadedValue = decoder.decodeSerializableElement<T>( descriptor = ser.descriptor, index = index, deserializer = ser as DeserializationStrategy<T> ) value = loadedValue } }
0
Kotlin
0
0
28b8465b14046b4c634bcd90b5d377e8fa5b0772
3,042
obs
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Rules.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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.straight.Icons public val Icons.Filled.Rules: ImageVector get() { if (_rules != null) { return _rules!! } _rules = Builder(name = "Rules", 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) { moveToRelative(22.922f, 1.726f) curveToRelative(-0.686f, -0.572f, -1.579f, -0.808f, -2.516f, -0.636f) lineToRelative(-4.122f, 1.003f) curveToRelative(-1.903f, 0.346f, -3.284f, 2.001f, -3.284f, 3.936f) verticalLineToRelative(14.802f) lineToRelative(-1.0f, 0.182f) lineToRelative(-1.0f, -0.182f) lineTo(11.0f, 6.029f) curveToRelative(0.0f, -1.935f, -1.381f, -3.589f, -3.227f, -3.923f) lineTo(3.536f, 1.078f) curveToRelative(-0.881f, -0.162f, -1.774f, 0.077f, -2.458f, 0.648f) curveToRelative(-0.686f, 0.572f, -1.078f, 1.411f, -1.078f, 2.303f) verticalLineToRelative(16.834f) lineToRelative(12.0f, 2.182f) lineToRelative(12.0f, -2.182f) lineTo(24.0f, 4.029f) curveToRelative(0.0f, -0.892f, -0.393f, -1.731f, -1.078f, -2.303f) close() moveTo(5.887f, 13.647f) curveToRelative(-0.459f, 0.474f, -1.22f, 0.471f, -1.674f, -0.007f) lineToRelative(-2.037f, -2.152f) lineToRelative(1.387f, -1.441f) lineToRelative(1.496f, 1.581f) lineToRelative(2.543f, -2.631f) lineToRelative(1.398f, 1.43f) lineToRelative(-3.113f, 3.221f) close() moveTo(21.914f, 13.394f) lineToRelative(-1.414f, 1.414f) lineToRelative(-1.793f, -1.793f) lineToRelative(-1.793f, 1.793f) lineToRelative(-1.414f, -1.414f) lineToRelative(1.793f, -1.793f) lineToRelative(-1.793f, -1.793f) lineToRelative(1.414f, -1.414f) lineToRelative(1.793f, 1.793f) lineToRelative(1.793f, -1.793f) lineToRelative(1.414f, 1.414f) lineToRelative(-1.793f, 1.793f) lineToRelative(1.793f, 1.793f) close() } } .build() return _rules!! } private var _rules: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,280
icons
MIT License
app/src/test/java/com/anabelmm/imboredapp/model/RepositoryTest.kt
mtnez-anabel
493,637,783
false
null
package com.anabelmm.imboredapp.model import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.anabelmm.imboredapp.model.db.CardDAO import com.anabelmm.imboredapp.model.db.CardEntity import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory private val card1 = CardEntity( key = 9924423, activity = "Learn how to make a website", accessibility = 0.3, type = "education", participants = 1, price = 0.1, link = "" ) private val card2 = CardEntity( key = 8442249, activity = "Have a bonfire with your close friends", accessibility = 0.1, type = "social", participants = 4, price = 0.1, link = "" ) @ExperimentalCoroutinesApi class RepositoryTest { private val mockWebServer = MockWebServer() private lateinit var mockedResponse: String private lateinit var restDataSource: APIActivityService private lateinit var testAPIClient: APIClient private lateinit var testRepository: RepositoryImp @get:Rule val rule = InstantTaskExecutorRule() @Before fun onBefore() { mockWebServer.start(8000) mockedResponse = MockResponseFileReader.content("api_response.json") mockWebServer.enqueue( MockResponse() .setResponseCode(200) .setBody(mockedResponse) ) restDataSource = Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .client(OkHttpClient.Builder().build()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(APIActivityService::class.java) testAPIClient = APIClient(restDataSource) testRepository = RepositoryImp(MockDao(), testAPIClient) } @After fun tearDown() { mockWebServer.shutdown() } @Test fun `getActivityFromAPI function is responding correctly when response is not null`() { val newActivityCard = runBlocking { testRepository.getActivityFromAPI()!! } println(newActivityCard.toString()) assertEquals(newActivityCard.activity, "Learn the NATO phonetic alphabet") assertEquals(newActivityCard.accessibility, 0.0, 0.1) assertEquals(newActivityCard.type, "education") assertEquals(newActivityCard.participants, 1) assertEquals(newActivityCard.price, 0.0, 0.1) assertEquals( newActivityCard.link, "https://en.wikipedia.org/wiki/NATO_phonetic_alphabet" ) assertEquals(newActivityCard.key, 6706598) } @Test fun `Activities on the DB are retrieved correctly`() { val activityCardList = runBlocking { testRepository.getListActivityFromDB() } assertEquals(2, activityCardList.size) } @Test fun `All activities are deleted correctly from DB`() { lateinit var activityCardList: List<ActivityCard?> runBlocking { testRepository.deleteAllCardActivities() activityCardList = testRepository.getListActivityFromDB() } assert(activityCardList.isEmpty()) } @Test fun `A new CardActivity is inserted correctly into DB`() { val activityCard = ActivityCard( activity = "Learn the NATO phonetic alphabet", accessibility = 0.0, type = "education", participants = 1, price = 0.0, link = "https://en.wikipedia.org/wiki/NATO_phonetic_alphabet", key = 6706598 ) lateinit var activityCardList: List<ActivityCard?> runBlocking { testRepository.insertActivityCardToDB(activityCard) activityCardList = testRepository.getListActivityFromDB() assertEquals(3, activityCardList.size) } } } class MockDao : CardDAO { private val cards = mutableListOf(card1, card2) override suspend fun getAllCards(): List<CardEntity> = cards override suspend fun insertCard(card: CardEntity) { cards.add(card) } override suspend fun deleteAllCards() { cards.clear() } }
0
Kotlin
0
0
5496349d8ee74ff9a1aa45fc9a9e300494316c39
4,435
ImBoredApp
MIT License
app/src/main/java/an/maguste/android/navier/MainActivity.kt
AnnGal
310,618,728
false
{"Kotlin": 51463}
package an.maguste.android.navier import an.maguste.android.navier.databinding.ActivityMainBinding import an.maguste.android.navier.movieslist.FragmentMoviesListDirections import an.maguste.android.navier.notifiactions.MovieNotifications import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.activity.viewModels import androidx.navigation.findNavController class MainActivity : AppCompatActivity() { // view model private val viewModel: MainActivityViewModel by viewModels { MainActivityViewModelFactory() } private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root if (savedInstanceState == null) { intent?.let(::handleIntent) } setObservers() setContentView(view) } private fun setObservers() { viewModel.navigateToSelectedMovie.observe(this, { movie -> if (null != movie) { findNavController(R.id.navigationFragment) .navigate(FragmentMoviesListDirections.actionToMoviesDetails(movie)) } }) } private fun handleIntent(intent: Intent) { when (intent.action) { Intent.ACTION_VIEW -> { val id = intent.data?.lastPathSegment?.toLongOrNull() if (id != null) { viewModel.showMovieFromNotification(id.toLong()) viewModel.showMovieFromNotificationComplete() // dismissNotification // bad decision? val notifications = MovieNotifications(App.context()) notifications.initialize() notifications.dismissNotification(id) } } // first start else -> viewModel.startBackgroundMovieCheck() } } }
0
Kotlin
0
0
76b52c6e3538fe999943c4aca1e34dd14472c43e
2,074
Navier
Apache License 2.0
qaf-ixin/src/main/kotlin/qaf/ixin/Supports.kt
phylame
63,782,651
false
null
/* * Copyright 2015-2016 <NAME> <<EMAIL>> * * This file is part of IxIn. * * 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 qaf.ixin import jclp.io.IOUtils import jclp.log.Log import jclp.text.Converter import jclp.text.ConverterManager import jclp.util.StringUtils import qaf.core.App import java.awt.Color import java.awt.Dimension import java.awt.Font import java.awt.Point import java.awt.event.MouseEvent import java.util.* import javax.swing.* infix fun Int.x(height: Int): Dimension = Dimension(this, height) fun Dimension.scale(rate: Double): Dimension = Dimension((width * rate).toInt(), (height * rate).toInt()) val MouseEvent.isLeft: Boolean get() = SwingUtilities.isLeftMouseButton(this) val MouseEvent.isRight: Boolean get() = SwingUtilities.isRightMouseButton(this) object Ixin { const val JAVA_THEME = "Java" const val SYSTEM_THEME = "System" const val DEFAULT_THEME = "Default" const val FONTS_KEY_PATH = "!qaf/ixin/font-keys.txt" const val MNEMONIC_PREFIX = '&' val isMnemonicSupport by lazy { "mac" !in System.getProperty("os.name") } var isMnemonicEnable = isMnemonicSupport fun init(antiAliasing: Boolean, decorated: Boolean, theme: String, font: Font?) { isAntiAliasing = antiAliasing isWindowDecorated = decorated lafTheme = theme globalFont = font } val themes = HashMap<String, String>() fun themeFor(name: String): String = themes[name] ?: when (name) { DEFAULT_THEME -> UIManager.getLookAndFeel().javaClass.name SYSTEM_THEME -> UIManager.getSystemLookAndFeelClassName() JAVA_THEME -> UIManager.getCrossPlatformLookAndFeelClassName() else -> name } val delegate: IDelegate<*> get() = if (App.delegate is IDelegate<*>) App.delegate as IDelegate<*> else throw IllegalStateException("App should run with IDelegate") // 1 var isAntiAliasing: Boolean = false set(value) { updateAntiAliasing(value) field = value } fun updateAntiAliasing(enable: Boolean) { System.setProperty("awt.useSystemAAFontSettings", if (enable) "on" else "off") System.setProperty("swing.aatext", enable.toString()) } // 2 var isWindowDecorated: Boolean = false set(value) { updateWindowDecorated(value) field = value } fun updateWindowDecorated(enable: Boolean) { JDialog.setDefaultLookAndFeelDecorated(enable) JFrame.setDefaultLookAndFeelDecorated(enable) } // 3 var lafTheme: String = DEFAULT_THEME set(value) { updateLafTheme(value) field = value } fun updateLafTheme(name: String) { if (name.isNotEmpty()) { try { UIManager.setLookAndFeel(themeFor(name)) } catch (e: Exception) { throw RuntimeException("Cannot set to new laf: $name", e) } } else { Log.d("Ixin", "empty laf theme specified") } } // 4 var globalFont: Font? = null set(value) { if (value != null) { updateGlobalFont(value) } field = value } private val fontKeys by lazy { val keys = LinkedList<String>() IOUtils.openResource(FONTS_KEY_PATH, Ixin::class.java.classLoader)?.bufferedReader()?.forEachLine { keys.add(it.trim()) } keys } fun updateGlobalFont(font: Font) { val defaults = UIManager.getLookAndFeelDefaults() for (key in fontKeys) { val value = defaults[key] defaults[key] = when (value) { null -> font is Font -> font.deriveFont(value.style) is UIDefaults.ActiveValue -> font.deriveFont((value.createValue(defaults) as Font).style) is UIDefaults.LazyValue -> font.deriveFont((value.createValue(defaults) as Font).style) else -> throw RuntimeException("unknown name for key $key") } } } data class MnemonicTuple(val name: String, val mnemonic: Int, val index: Int) { val isEnable: Boolean get() = isMnemonicEnable && mnemonic != 0 } fun mnemonicOf(name: String): MnemonicTuple { // get mnemonic from name var text = name var mnemonic = 0 val index = name.indexOf(MNEMONIC_PREFIX) if (index >= 0 && index < name.length) { val next = name[index + 1] if (next.isLetterOrDigit()) { // has mnemonic mnemonic = next.toInt() text = name.substring(0, index) + name.substring(index + 1) } } return MnemonicTuple(text, mnemonic, index) } fun trimMnemonic(text: String, mnemonicIndex: Int, bracketLength: Int = 1): String { if (mnemonicIndex == -1 || bracketLength == 0) { return text } return text.substring(0, mnemonicIndex - bracketLength) + text.substring(mnemonicIndex + 1 + bracketLength) } fun formatKeyStroke(keyStroke: KeyStroke): String { var str = keyStroke.toString() str = str.replaceFirst("ctrl ", "Ctrl+") str = str.replaceFirst("shift ", "Shift+") str = str.replaceFirst("alt ", "Alt+") str = str.replaceFirst("typed ", "") str = str.replaceFirst("pressed ", "") str = str.replaceFirst("released ", "") return str } init { for (feel in UIManager.getInstalledLookAndFeels()) { themes[feel.name] = feel.className } // register converter for UI objects ConverterManager.registerConverter(Point::class.java, object : Converter<Point> { override fun parse(str: String): Point { val pair = StringUtils.partition(str, "-") return Point(Integer.decode(pair.first.trim()), Integer.decode(pair.second.trim())) } override fun render(o: Point): String = "${o.x}-${o.y}" }) ConverterManager.registerConverter(Dimension::class.java, object : Converter<Dimension> { override fun parse(str: String): Dimension { val pair = StringUtils.partition(str, "-") return Dimension(Integer.decode(pair.first.trim()), Integer.decode(pair.second.trim())) } override fun render(o: Dimension): String = "${o.width}-${o.height}" }) ConverterManager.registerConverter(Font::class.java, object : Converter<Font> { override fun parse(str: String): Font = Font.decode(str) override fun render(o: Font): String { val b = StringBuilder(o.family).append('-') when (o.style) { Font.PLAIN -> b.append("plain") Font.BOLD -> b.append("bold") Font.ITALIC -> b.append("italic") Font.BOLD or Font.ITALIC -> b.append("bolditalic") } return b.append('-').append(o.size).toString() } }) ConverterManager.registerConverter(Color::class.java, object : Converter<Color> { override fun parse(str: String): Color = Color.decode(str) override fun render(o: Color): String = "#%X".format(o.rgb).substring(2) }) } }
0
Kotlin
0
0
c7ff839178ae2ef775f7864f34693351f74fd5f8
7,931
qaf
Apache License 2.0
ggdsl-api/src/test/kotlin/org/jetbrains/kotlinx/ggdsl/dsl/LineType.kt
Kotlin
502,039,936
false
null
/* * Copyright 2020-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.ggdsl.dsl data class LineType(val description: String)
48
Kotlin
1
44
8a161098d0d946c28bde3cf3c7bea6a1eeba073c
195
ggdsl
Apache License 2.0
app/shared/f8e-client/impl/src/commonMain/kotlin/build/wallet/f8e/partnerships/GetPurchaseQuoteListServiceImpl.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.f8e.partnerships import build.wallet.bitkey.f8e.FullAccountId import build.wallet.f8e.F8eEnvironment import build.wallet.f8e.client.F8eHttpClient import build.wallet.f8e.partnerships.GetPurchaseQuoteListService.Success import build.wallet.ktor.result.NetworkingError import build.wallet.ktor.result.bodyResult import build.wallet.money.FiatMoney import build.wallet.platform.settings.CountryCodeGuesser import com.github.michaelbull.result.Result import com.github.michaelbull.result.map import io.ktor.client.request.post import io.ktor.client.request.setBody import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable class GetPurchaseQuoteListServiceImpl( private val countryCodeGuesser: CountryCodeGuesser, private val f8eHttpClient: F8eHttpClient, ) : GetPurchaseQuoteListService { override suspend fun purchaseQuotes( fullAccountId: FullAccountId, f8eEnvironment: F8eEnvironment, fiatAmount: FiatMoney, paymentMethod: String, ): Result<Success, NetworkingError> { return f8eHttpClient .authenticated( accountId = fullAccountId, f8eEnvironment = f8eEnvironment ) .bodyResult<ResponseBody> { post("/api/partnerships/purchases/quotes") { setBody( RequestBody( country = countryCodeGuesser.countryCode().uppercase(), fiatAmount = fiatAmount.value.doubleValue(exactRequired = false), fiatCurrency = fiatAmount.currency.textCode.code.uppercase(), paymentMethod = paymentMethod ) ) } } .map { body -> Success(body.quotes) } } @Serializable private data class RequestBody( val country: String, @SerialName("fiat_amount") val fiatAmount: Double, @SerialName("fiat_currency") val fiatCurrency: String, @SerialName("payment_method") val paymentMethod: String, ) @Serializable private data class ResponseBody( val quotes: List<Quote>, ) }
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
2,017
bitkey
MIT License
app/src/main/java/com/seif/booksislandapp/data/remote/dto/notification/NotificationDto.kt
SeifEldinMohamed
570,587,114
false
null
package com.seif.booksislandapp.data.remote.dto.notification import com.google.gson.annotations.SerializedName data class NotificationDto( @SerializedName("notification") val fcmMessageDto: FCMMessageDto, @SerializedName("to") val token: String = "" )
0
Kotlin
0
0
8a65e6406811c2d6c59064c5e1af8f9493aa7cc2
262
Books-Island-App
Apache License 2.0
app/src/main/java/com/ayia/workernotification/framework/Mappers.kt
ayiaware
525,784,017
false
null
package com.ayia.workernotification.framework import com.ayia.workernotification.data.TodoEntity import com.ayia.workernotification.domain.Todo fun Todo.toEntity(): TodoEntity { return TodoEntity( id = id, date = date, title = title, updated = updated, done = isDone, deadline = deadline, isReminderOn = isReminderOn, priority = priority, ) }
0
Kotlin
0
3
b9fc6c12d134d6c56b21c0863103e1d2c7171383
417
WorkerNotification
MIT License
app/src/main/java/com/ayia/workernotification/framework/Mappers.kt
ayiaware
525,784,017
false
null
package com.ayia.workernotification.framework import com.ayia.workernotification.data.TodoEntity import com.ayia.workernotification.domain.Todo fun Todo.toEntity(): TodoEntity { return TodoEntity( id = id, date = date, title = title, updated = updated, done = isDone, deadline = deadline, isReminderOn = isReminderOn, priority = priority, ) }
0
Kotlin
0
3
b9fc6c12d134d6c56b21c0863103e1d2c7171383
417
WorkerNotification
MIT License
app/src/main/java/com/oussama/portfolio/ui/fragments/DemoImagePiecesFragment.kt
Meglali20
752,721,331
false
{"Kotlin": 255952, "Java": 21500, "Python": 7142, "GLSL": 5407}
package com.oussama.portfolio.ui.fragments import android.annotation.SuppressLint import android.graphics.Bitmap import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.MotionEvent import android.view.View import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.FutureTarget import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.oussama.portfolio.databinding.FragmentDemoImagePiecesBinding import com.oussama.portfolio.utils.BitmapUtils import com.oussama.portfolio.utils.Utils.Companion.dpToPx import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class DemoImagePiecesFragment : BaseFragment<FragmentDemoImagePiecesBinding>() { override fun getViewBinding(): FragmentDemoImagePiecesBinding = FragmentDemoImagePiecesBinding.inflate(layoutInflater) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) /*lifecycleScope.launch { val backgroundBitmap: Bitmap val foregroundBitmap: Bitmap withContext(Dispatchers.IO) { val img1 = "https://tympanus.net/Development/AnimatedImagePieces/img/3d.jpg" val img2 = "https://tympanus.net/Development/AnimatedImagePieces/img/4b.jpg" backgroundBitmap = requestImage(img1).get() foregroundBitmap = requestImage(img2).get() } withContext(Dispatchers.Main) { if (!BitmapUtils.isEmptyBitmap(backgroundBitmap) && !BitmapUtils.isEmptyBitmap( foregroundBitmap ) ) binding.imagePieces.setImages( foregroundImage = foregroundBitmap, backgroundImage = backgroundBitmap, 250.dpToPx(), 350.dpToPx() ) } }*/ } @SuppressLint("ClickableViewAccessibility") override fun setupListeners() { super.setupListeners() Handler(Looper.getMainLooper()).postDelayed({ Glide.with(requireContext()) .asBitmap() .listener(object : RequestListener<Bitmap?> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Bitmap?>, isFirstResource: Boolean ): Boolean { return false } override fun onResourceReady( resource: Bitmap, model: Any, target: Target<Bitmap?>?, dataSource: DataSource, isFirstResource: Boolean ): Boolean { binding.glImageTextureView.setBitmapImage(resource) return false } }) .load("https://raw.githubusercontent.com/codrops/ImagePixelLoading/main/img/4.jpg") .submit(binding.glImageTextureView.width, binding.glImageTextureView.height) }, 400) /*binding.textShufflerView.setOnClickListener { Handler(Looper.getMainLooper()).postDelayed({ binding.textShufflerView.shuffleText(reset = true, withDelay = false) }, 100) }*/ /*binding.imagePieces.setOnTouchListener { view, event -> when (event?.action) { MotionEvent.ACTION_DOWN -> { binding.imagePieces.demoAnimateIn() true } MotionEvent.ACTION_UP -> { binding.imagePieces.demoAnimateOut(event.x, event.y) true } else -> false } }*/ } private fun requestImage(url: String): FutureTarget<Bitmap> { return Glide.with(requireContext()) .asBitmap() .listener(object : RequestListener<Bitmap?> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Bitmap?>, isFirstResource: Boolean ): Boolean { return false } override fun onResourceReady( resource: Bitmap, model: Any, target: Target<Bitmap?>?, dataSource: DataSource, isFirstResource: Boolean ): Boolean { return false } }) .load(url) .submit() } }
0
Kotlin
0
4
1437e6cf47fc7f4c64f46eee10c9d25b2399b649
4,918
Portfolio-Android-MVVM
MIT License
transferwise/src/test/java/com/transferwise/banks/account/login/HandleLoginViewModelTest.kt
JeroenMols
335,055,882
true
{"Kotlin": 448648}
/* * Copyright 2019 TransferWise Ltd. * * 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.transferwise.banks.account.login import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import com.transferwise.banks.account.login.HandleLoginUiState.Failed import com.transferwise.banks.account.login.HandleLoginUiState.LoggingIn import com.transferwise.banks.account.login.HandleLoginUiState.NoNetwork import com.transferwise.banks.api.BanksWebService import com.transferwise.banks.shared.NavigationAction.ToConnectAccount import com.transferwise.banks.shared.NavigationAction.ToQuote import com.transferwise.banks.shared.QuoteDescription import com.transferwise.banks.shared.SharedViewModel import com.transferwise.banks.testutils.TestCoroutineExtension import com.transferwise.banks.testutils.TestLiveDataExtension import com.transferwise.banks.util.fake.FakeConfiguration import kotlinx.coroutines.test.runBlockingTest import okhttp3.internal.EMPTY_RESPONSE import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import retrofit2.Response @ExtendWith(MockitoExtension::class, TestCoroutineExtension::class, TestLiveDataExtension::class) internal class HandleLoginViewModelTest { @Mock lateinit var webService: BanksWebService @Nested @DisplayName("When screen open") inner class Open { @Test internal fun `show login state`() = runBlockingTest { whenever(webService.logIn(any(), any())).thenReturn(Response.success(null)) val viewModel = viewModel(webService, SharedViewModel(FakeConfiguration), code = "uniqueCode") assertThat(viewModel.uiState.value).isEqualTo(LoggingIn) } @Test internal fun `login with code`() = runBlockingTest { viewModel(webService, code = "uniqueCode") verify(webService).logIn(any(), eq("uniqueCode")) } @Test internal fun `login with customer id`() = runBlockingTest { viewModel(webService, customerId = 5) verify(webService).logIn(eq(5), any()) } @Test internal fun `navigate to quote when login success`() = runBlockingTest { val sharedModel = SharedViewModel(FakeConfiguration) whenever(webService.logIn(any(), any())).thenReturn(Response.success(null)) viewModel(webService, sharedModel) assertThat(sharedModel.navigationAction.value).isInstanceOf(ToQuote::class.java) } @Test internal fun `navigate to quote with customer id`() = runBlockingTest { val sharedModel = SharedViewModel(FakeConfiguration) whenever(webService.logIn(any(), any())).thenReturn(Response.success(null)) viewModel(webService, sharedModel, 5) assertThat((sharedModel.navigationAction.value as ToQuote).customerId).isEqualTo(5) } @Test internal fun `navigate to quote with source amount`() = runBlockingTest { val sharedModel = SharedViewModel(FakeConfiguration) val fakeQuote = QuoteDescription.FixedSource(100f, "GBP", "EUR") whenever(webService.logIn(any(), any())).thenReturn(Response.success(null)) viewModel(webService, sharedModel, quote = fakeQuote) assertThat((sharedModel.navigationAction.value as ToQuote).quote).isEqualTo(fakeQuote) } @Test internal fun `don't navigate to quote when login failed`() = runBlockingTest { val sharedModel = SharedViewModel(FakeConfiguration) whenever(webService.logIn(any(), any())).thenReturn(Response.error(400, EMPTY_RESPONSE)) viewModel(webService, sharedModel) assertThat(sharedModel.navigationAction.value).isNull() } @Test internal fun `show error when login failed`() = runBlockingTest { whenever(webService.logIn(any(), any())).thenReturn(Response.error(400, EMPTY_RESPONSE)) val viewModel = viewModel(webService) assertThat(viewModel.uiState.value).isEqualTo(Failed) } @Test internal fun `show no network when network error`() = runBlockingTest { whenever(webService.logIn(any(), any())).thenThrow(RuntimeException()) val viewModel = viewModel(webService) assertThat(viewModel.uiState.value).isEqualTo(NoNetwork) } } @Nested @DisplayName("When go back") inner class Back { @Test internal fun `navigate to connect account`() { val sharedModel = SharedViewModel(FakeConfiguration) viewModel(webService, sharedModel).doGoBack() assertThat(sharedModel.navigationAction.value).isInstanceOf(ToConnectAccount::class.java) } @Test internal fun `navigate to connect account with customer id`() { val sharedModel = SharedViewModel(FakeConfiguration) viewModel(webService, sharedModel, 5).doGoBack() assertThat((sharedModel.navigationAction.value as ToConnectAccount).customerId).isEqualTo(5) } @Test internal fun `navigate to connect account with source amount`() { val sharedModel = SharedViewModel(FakeConfiguration) val fakeQuote = QuoteDescription.FixedSource(100f, "GBP", "EUR") viewModel(webService, sharedModel, quote = fakeQuote).doGoBack() assertThat((sharedModel.navigationAction.value as ToConnectAccount).quote).isEqualTo(fakeQuote) } } private fun viewModel( service: BanksWebService = mock(), sharedViewModel: SharedViewModel = mock(), customerId: Int = 0, quote: QuoteDescription = mock(), code: String = "" ) = HandleLoginViewModel(service, sharedViewModel, customerId, quote, code) }
0
null
0
1
ea0aa12bca3f1c15fbaad29c62b36893d7ce09a6
6,739
banks-reference-android
Apache License 2.0
buildSrc/src/main/kotlin/family/amma/Dependencies.kt
AMMA-Family
339,682,898
false
null
@file:JvmMultifileClass private const val kotlinVersion = "1.5.30" object BuildPlugin { const val gradle = "com.android.tools.build:gradle:7.0.1" const val kotlin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } object Dependency { const val xmlpull = "xmlpull:xmlpull:1.1.3.1" const val kotlinpoet = "com.squareup:kotlinpoet:1.9.0" object Kotlin { object X { object Serialization { const val core = "org.jetbrains.kotlinx:kotlinx-serialization-core:1.2.2" } object Coroutines { const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2" } } } object Test { const val mockk = "io.mockk:mockk:1.12.0" } }
0
Kotlin
0
9
98364a6bf39aaaf37adba8c7c446b124c5352938
772
android-navigation-deeplinks
MIT License
src/main/kotlin/com/yapp/weekand/domain/sticker/entity/ScheduleSticker.kt
YAPP-Github
475,727,764
false
null
package com.yapp.weekand.domain.sticker.entity import com.yapp.weekand.domain.schedule.entity.ScheduleRule import com.yapp.weekand.domain.user.entity.User import com.yapp.weekand.common.entity.BaseEntity import java.time.LocalDate import javax.persistence.* @Entity class ScheduleSticker( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "schedule_sticker_id") val id: Long? = null, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") var user: User, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "schedule_rule_id") var scheduleRule: ScheduleRule, @Enumerated(EnumType.STRING) var name: ScheduleStickerName, @Column(name = "schedule_date", columnDefinition = "스티커를 붙인 일정의 특정 날짜") var scheduleDate: LocalDate, ) : BaseEntity()
3
Kotlin
0
4
382c212a6af89c6009a776be8eb4de96c5c3d147
790
20th-ALL-Rounder-Team-1-BE
Apache License 2.0
app/src/main/java/com/aridwiprayogo/popularmovie/ui/movie/PopularMovieAdapter.kt
aridwiprayogo
168,526,153
false
null
package com.aridwiprayogo.popularmovie.ui.movie import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.aridwiprayogo.popularmovie.domain.model.PopularMovie import com.aridwiprayogo.popularmovie.R import com.aridwiprayogo.popularmovie.utils.loadImage import kotlinx.android.synthetic.main.popular_movie_item.view.* class PopularMovieAdapter( private val listPopularMovie: List<PopularMovie>, private val onClick: PopularMovieCallback ): RecyclerView.Adapter<PopularMovieAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.popular_movie_item, parent, false) return ViewHolder( view ) } override fun getItemCount(): Int { return listPopularMovie.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.onBind(listPopularMovie[position],onClick) } class ViewHolder(val view: View) : RecyclerView.ViewHolder(view){ inline fun onBind( popularMovie: PopularMovie, crossinline onClick: PopularMovieCallback ) { with(this.view){ tv_title.text = popularMovie.title imageView.loadImage(popularMovie.src) this.setOnClickListener { onClick(popularMovie) } } } } } typealias PopularMovieCallback = (popularMovie: PopularMovie)->Unit
0
Kotlin
4
7
1684fec7aa2f0375871e62a31958ffb7f0d06470
1,642
PopularMovie
MIT License
src/main/kotlin/viral_game/board_generators/RandomBoardGenerator.kt
AvansInformatica-Marc
255,536,528
false
null
@file:Suppress("EXPERIMENTAL_API_USAGE", "EXPERIMENTAL_UNSIGNED_LITERALS") package viral_game.board_generators import viral_game.data.Paradigm import viral_game.grid.Coordinates object RandomBoardGenerator { val generator: BoardGenerator = { boardSize -> { coordinates -> randomBoardGenerator(coordinates, boardSize) } } private fun randomBoardGenerator(coordinates: Coordinates, boardSize: Pair<Int, Int>): Paradigm { val (x, y) = coordinates val (width, height) = boardSize val ooChance = when (x) { in 0 until width / 2 -> 8 in 0 until width / 3 * 2 -> 4 else -> 1 } val dclChance = when { x in width / 3 * 2 until width && y in height / 3 * 2 until height -> 8 x in width / 2 until width && y in height / 2 until height -> 4 else -> 1 } val fpChance = when { x in width / 3 * 2 until width && y in 0 until height / 2 -> 8 x in width / 3 until width && y in 0 until height / 2 -> 4 x in width / 2 until width && y in 0 until height / 3 * 2 -> 4 else -> 1 } return Array(ooChance + fpChance + dclChance) { when { it < ooChance -> Paradigm.OO it < ooChance + fpChance -> Paradigm.FUNCTIONAL else -> Paradigm.DECLARATIVE } }.random() } }
0
Kotlin
0
0
310b1186c070b2fb660f6f5068e460f35153f433
1,462
ViralGame
MIT License
electronapp/src/main/kotlin/ElectronUtil.kt
olegchir
300,762,256
false
null
import Electron.* class ElectronUtil { companion object { var app: App = Electron.app public fun disableAllStandardShortcuts() { Menu.setApplicationMenu(null); } public fun disableWindowShortcuts (browserWindow: BrowserWindow) { browserWindow.setMenu(null) } public fun registerGlobalShortcut(recipient: App, activationKey: dynamic, callback: () -> Unit) { app.whenReady().then { globalShortcut.register(activationKey, callback) }; } public fun registerGlobalShortcut(recipient: BrowserWindow, activationKey: Accelerator, callback: () -> Unit) { app.whenReady().then { globalShortcut.register(activationKey, callback) }; } } }
0
Kotlin
0
0
13edf73b6a1961ad3af048dab3cbc67dca3db9c9
816
projector-launcher
MIT License
modules/tak/core/src/main/kotlin/dev/jonpoulton/alakazam/tak/core/PluginContext.kt
jonapoul
375,762,483
false
{"Kotlin": 3035874, "Shell": 670}
package dev.jonpoulton.alakazam.tak.core import android.content.Context import android.content.ContextWrapper import com.atak.plugins.impl.PluginContextProvider import gov.tak.api.plugin.IServiceController public class PluginContext(context: Context) : ContextWrapper(context) { public constructor(serviceController: IServiceController) : this( context = serviceController.getService(PluginContextProvider::class.java).pluginContext ) }
0
Kotlin
0
0
18e415e5f6079ab8d18a4a2e4b630d8a52aedc30
447
alakazam
Apache License 2.0
app/src/main/java/dev/maxsiomin/fiftycognitivedistortions/activity/AlarmReceiver.kt
MaxSiominDev
469,830,503
false
{"Kotlin": 24293}
package dev.maxsiomin.fiftycognitivedistortions.activity import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import dev.maxsiomin.fiftycognitivedistortions.R import dev.maxsiomin.fiftycognitivedistortions.activity.MainActivity.Companion.CHANNEL_ID import dev.maxsiomin.fiftycognitivedistortions.activity.MainActivity.Companion.setAlarm import dev.maxsiomin.fiftycognitivedistortions.extensions.getDefaultSharedPrefs import dev.maxsiomin.fiftycognitivedistortions.util.SharedPrefsConfig.DISTORTIONS_SHOWED import timber.log.Timber class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Timber.i("onReceive called") val i = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_IMMUTABLE) with (context.getDefaultSharedPrefs()) { this.edit().putInt(DISTORTIONS_SHOWED, this.getInt(DISTORTIONS_SHOWED, 1) + 1).apply() } setAlarm(context) showNotification(context, pendingIntent) } private fun showNotification(context: Context, intent: PendingIntent) { val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setContentTitle(context.getString(R.string.new_distortion)) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(intent) .setAutoCancel(true) .build() val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(0, notification) } }
0
Kotlin
0
0
24ea7136ea0c77ef79e60f53359154a399943070
1,872
50-cognitive-distortions
MIT License