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
sample/shared/compose/src/commonMain/kotlin/com/arkivanov/sample/shared/customnavigation/KittenContent.kt
arkivanov
437,015,897
false
{"Kotlin": 522787}
package com.arkivanov.sample.shared.customnavigation import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.material.LocalContentColor import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.arkivanov.decompose.extensions.compose.subscribeAsState import decompose.sample.shared.compose.generated.resources.Res import decompose.sample.shared.compose.generated.resources.cat1 import decompose.sample.shared.compose.generated.resources.cat2 import decompose.sample.shared.compose.generated.resources.cat3 import decompose.sample.shared.compose.generated.resources.cat4 import decompose.sample.shared.compose.generated.resources.cat5 import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @Composable internal fun KittenContent( component: KittenComponent, textStyle: TextStyle, modifier: Modifier = Modifier, ) { val model by component.model.subscribeAsState() Box(modifier = modifier) { Image( painter = getKittenPainter(imageType = model.imageType), contentDescription = "Kitten image", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop, ) CompositionLocalProvider(LocalContentColor provides Color.White) { Text( text = model.text, modifier = Modifier .align(Alignment.TopCenter) .fillMaxWidth() .background(Brush.verticalGradient(colors = listOf(Color.Black.copy(alpha = 0.75F), Color.Transparent))) .statusBarsPadding() .padding(top = 16.dp, bottom = 24.dp), style = textStyle, textAlign = TextAlign.Center, ) } } } @OptIn(ExperimentalResourceApi::class) @Composable internal fun getKittenPainter(imageType: KittenComponent.ImageType): Painter = painterResource( when (imageType) { KittenComponent.ImageType.CAT_1 -> Res.drawable.cat1 KittenComponent.ImageType.CAT_2 -> Res.drawable.cat2 KittenComponent.ImageType.CAT_3 -> Res.drawable.cat3 KittenComponent.ImageType.CAT_4 -> Res.drawable.cat4 KittenComponent.ImageType.CAT_5 -> Res.drawable.cat5 } )
2
Kotlin
82
2,100
d16e901b1bdce7cc863272d7b8918c20d70c497c
3,150
Decompose
Apache License 2.0
app/src/main/java/com/kurantsov/integritycheck/data/remote/BackendSecretsDataSource.kt
ArtsemKurantsou
781,690,628
false
{"Kotlin": 26632, "CMake": 800, "C++": 575}
package com.kurantsov.integritycheck.data.remote import com.google.firebase.appcheck.FirebaseAppCheck import com.kurantsov.integritycheck.data.RemoteSecretsDataSource import com.kurantsov.integritycheck.domain.Secrets import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get import io.ktor.client.request.headers import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import javax.inject.Inject internal class BackendSecretsDataSource @Inject constructor( private val client: HttpClient, private val appCheck: FirebaseAppCheck, private val mapper: SecretsDtoMapper, ) : RemoteSecretsDataSource { override suspend fun getSecrets(): Secrets = withContext(Dispatchers.IO) { // Fetches AppCheck token val token = appCheck.limitedUseAppCheckToken .await() .token // Sends request to the Backend with a token to get secrets val dto = client.get("/secrets") { headers { append("X-Firebase-AppCheck", token) } }.body<SecretsDto>() return@withContext mapper.map(dto) } }
0
Kotlin
0
0
64aa3a64a3c9a2f8650d15646e3efbee8567d619
1,198
Secrets-in-Android
Apache License 2.0
src/main/kotlin/org/saphka/discord/bot/model/GameEnrollmentDTO.kt
saphka
591,354,472
false
null
package org.saphka.discord.bot.model data class GameEnrollmentDTO( val id: Long, val serverId: Long, val gameId: Long, val characterId: Long ) data class GameEnrollmentChangeRequest( val serverId: Long, val gameSlug: String, val characterSlug: String )
1
Kotlin
0
0
eb7b511aab30a9e0e3334c85e83385d749c0f6d4
282
discord-dnd-bot
Apache License 2.0
src/commonMain/kotlin/com/github/adriantodt/lin/parser/parselets/control/ContinueParser.kt
adriantodt
280,314,655
false
null
package com.github.adriantodt.lin.parser.parselets.control import com.github.adriantodt.lin.ast.node.Node import com.github.adriantodt.lin.ast.node.control.ContinueExpr import com.github.adriantodt.lin.lexer.TokenType import com.github.adriantodt.tartar.api.grammar.PrefixParselet import com.github.adriantodt.tartar.api.parser.ParserContext import com.github.adriantodt.tartar.api.parser.Token public object ContinueParser : PrefixParselet<TokenType, Token<TokenType>, Node> { override fun parse(ctx: ParserContext<TokenType, Token<TokenType>, Node>, token: Token<TokenType>): Node { return ContinueExpr(token.section) } }
16
Kotlin
0
7
b3b10f34e85bc7dec2d3b94d0d6fb2e51dcf1fbf
642
Lin
MIT License
beagle/src/main/kotlin/br/com/zup/beagle/android/view/custom/BeaglePageView.kt
ZupIT
391,144,851
false
null
/* * Copyright 2020, 2022 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.android.view.custom import android.content.Context import androidx.viewpager.widget.ViewPager import br.com.zup.beagle.android.components.page.PageIndicatorOutput class BeaglePageView(context: Context) : ViewPager(context), PageIndicatorOutput { override fun swapToPage(newIndex: Int) { setCurrentItem(newIndex, true) } }
0
Kotlin
2
9
812a330777edd79a123495e9f678dc8f25a019f7
1,001
beagle-android
Apache License 2.0
src/commonMain/kotlin/org/breact/radical/useEffect.kt
wy2010344
660,453,263
false
null
package org.breact.radical fun <V> V.useBeforeAttrEffectWithDestroy(callback: (V) -> ((V)->Unit)?) { org.breact.core.useBeforeAttrEffect(callback, this) } fun <V> V.useAttrEffectWithDestroy(callback: (V) -> ((V)->Unit)?) { org.breact.core.useAttrEffect(callback, this) } fun <V> V.useEffectWithDestroy(callback: (V) -> ((V)->Unit)?) { org.breact.core.useEffect(callback, this) } fun <V> V.useBeforeAttrEffect(callback: (V) -> Unit) { this.useBeforeAttrEffectWithDestroy{ callback(it) null } } fun <V> V.useAttrEffect(callback: (V) -> Unit) { this.useAttrEffectWithDestroy{ callback(it) null } } fun <V> V.useEffect(callback: (V) -> Unit) { this.useEffectWithDestroy{ callback(it) null } } fun <V, T> V.useDestroy(callback: (V) -> Unit) { this.useEffectWithDestroy { callback } }
0
Kotlin
0
0
bbd89583594284e008ad9125f7b0ea3efe10c8a4
884
kotlin-better-react
MIT License
presentation/src/main/java/com/jyproject/presentation/ui/feature/common/util/TopBar.kt
JunYeong0314
778,833,940
false
{"Kotlin": 208970}
package com.jyproject.presentation.ui.feature.common.util import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.jyproject.presentation.R @Composable fun TopBar() { Row( modifier = Modifier .fillMaxWidth() .height(45.dp) .background(Color.White) , horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Image(painter = painterResource(id = R.drawable.ic_app), contentDescription = "ic_app") } }
0
Kotlin
0
0
edb71cf4db51cee1593aa31c66c25d616492d24c
1,011
PlacePick
MIT License
kruth/kruth/src/commonTest/kotlin/androidx/kruth/MathUtilTest.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.kruth import kotlin.test.Test class MathUtilTest { @Test fun floatEquals() { assertThat(equalWithinTolerance(1.3f, 1.3f, 0.00000000000001f)).isTrue() assertThat(equalWithinTolerance(1.3f, 1.3f, 0.0f)).isTrue() assertThat( equalWithinTolerance( 0.0f, 1.0f + 2.0f - 3.0f, 0.00000000000000000000000000000001f ) ) .isTrue() assertThat(equalWithinTolerance(1.3f, 1.303f, 0.004f)).isTrue() assertThat(equalWithinTolerance(1.3f, 1.303f, 0.002f)).isFalse() assertThat(equalWithinTolerance(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, 0.01f)) .isFalse() assertThat(equalWithinTolerance(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.01f)) .isFalse() assertThat(equalWithinTolerance(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.01f)) .isFalse() assertThat(equalWithinTolerance(Float.NaN, Float.NaN, 0.01f)).isFalse() } @Test fun doubleEquals() { assertThat(equalWithinTolerance(1.3, 1.3, 0.00000000000001)).isTrue() assertThat(equalWithinTolerance(1.3, 1.3, 0.0)).isTrue() assertThat(equalWithinTolerance(0.0, 1.0 + 2.0 - 3.0, 0.00000000000000000000000000000001)) .isTrue() assertThat(equalWithinTolerance(1.3, 1.303, 0.004)).isTrue() assertThat(equalWithinTolerance(1.3, 1.303, 0.002)).isFalse() assertThat(equalWithinTolerance(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0.01)) .isFalse() assertThat(equalWithinTolerance(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.01)) .isFalse() assertThat(equalWithinTolerance(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.01)) .isFalse() assertThat(equalWithinTolerance(Double.NaN, Double.NaN, 0.01)).isFalse() } @Test fun floatNotEquals() { assertThat(notEqualWithinTolerance(1.3f, 1.3f, 0.00000000000001f)).isFalse() assertThat(notEqualWithinTolerance(1.3f, 1.3f, 0.0f)).isFalse() assertThat( notEqualWithinTolerance(0.0f, 1.0f + 2.0f - 3.0f, 0.00000000000000000000000000000001f) ) .isFalse() assertThat(notEqualWithinTolerance(1.3f, 1.303f, 0.004f)).isFalse() assertThat(notEqualWithinTolerance(1.3f, 1.303f, 0.002f)).isTrue() assertThat(notEqualWithinTolerance(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, 0.01f)) .isFalse() assertThat(notEqualWithinTolerance(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.01f)) .isFalse() assertThat(notEqualWithinTolerance(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.01f)) .isFalse() assertThat(notEqualWithinTolerance(Float.NaN, Float.NaN, 0.01f)).isFalse() } @Test fun doubleNotEquals() { assertThat(notEqualWithinTolerance(1.3, 1.3, 0.00000000000001)).isFalse() assertThat(notEqualWithinTolerance(1.3, 1.3, 0.0)).isFalse() assertThat( notEqualWithinTolerance(0.0, 1.0 + 2.0 - 3.0, 0.00000000000000000000000000000001) ) .isFalse() assertThat(notEqualWithinTolerance(1.3, 1.303, 0.004)).isFalse() assertThat(notEqualWithinTolerance(1.3, 1.303, 0.002)).isTrue() assertThat( notEqualWithinTolerance( Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0.01 ) ) .isFalse() assertThat( notEqualWithinTolerance( Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.01 ) ) .isFalse() assertThat( notEqualWithinTolerance( Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.01 ) ) .isFalse() assertThat(notEqualWithinTolerance(Double.NaN, Double.NaN, 0.01)).isFalse() } }
29
Kotlin
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
4,724
androidx
Apache License 2.0
app/src/main/java/com/adityagupta/lumos/common/Constants.kt
aadityaguptaa
440,561,573
false
{"Kotlin": 2128}
package com.adityagupta.gdsc_nie.common object Constants { //Base URL for the News API const val BASE_URL = "https://api.coinpaprika.com/" }
1
Kotlin
3
0
267dd9bc8fd7c5b076ae97549915c28f0039290c
151
Lumos
MIT License
WeatherApp/app/src/main/java/com/arcapp/weatherapp/data/model/weather/FeelsLike.kt
mrnirva
552,269,945
false
null
package com.arcapp.weatherapp.data.model.weather import com.google.gson.annotations.SerializedName data class FeelsLike( @SerializedName("day") val day: Double?, @SerializedName("eve") val eve: Double?, @SerializedName("morn") val morn: Double?, @SerializedName("night") val night: Double? )
0
null
0
1
10da4a7931a02fec72558ed01476feeccd317a43
326
Patika-Pazarama-Bootcamp-Week-4-Task
MIT License
app/src/main/java/com/example/rifsa_mobile/model/entity/remote/finance/FinanceResultResponse.kt
RIFSA
491,493,199
false
null
package com.example.rifsa_mobile.model.entity.remote.finance import android.os.Parcelable import com.example.rifsa_mobile.model.entity.remote.harvestresult.HarvestResponData import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize data class FinanceResultResponse( @field:SerializedName("data") val financeResponseData: List<FinanceResponseData>, @field:SerializedName("message") val message: String, @field:SerializedName("status") val status: Int ) @Parcelize data class FinanceResponseData( @field:SerializedName("createdAt") val createdAt: String, @field:SerializedName("kegiatan") val kegiatan: String, @field:SerializedName("id_keuangan") val idKeuangan: Int, @field:SerializedName("jumlah") val jumlah: String, @field:SerializedName("jenis") val jenis: String, @field:SerializedName("catatan") val catatan: String, @field:SerializedName("tanggal") val tanggal: String, @field:SerializedName("updatedAt") val updatedAt: String ): Parcelable
0
Kotlin
3
6
42ae846f0bec4efcbf0c522ff9712e59312d3ea2
1,009
Rifsa-Mobile
The Unlicense
platform/lang-impl/src/com/intellij/platform/documentation/impl/InternalLinkResult.kt
GunoH
19,505,706
false
{"Text": 7456, "INI": 582, "YAML": 420, "Ant Build System": 9, "Batchfile": 28, "Dockerfile": 6, "Shell": 618, "Markdown": 689, "Ignore List": 131, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 246, "XML": 7429, "SVG": 3739, "Kotlin": 50560, "Java": 81275, "HTML": 3744, "Java Properties": 214, "Gradle": 392, "Maven POM": 78, "JavaScript": 220, "CSS": 74, "JSON": 1328, "JFlex": 32, "Groovy": 3293, "XSLT": 113, "desktop": 1, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 731, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 5, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 67, "GraphQL": 79, "OpenStep Property List": 47, "Python": 15245, "Makefile": 2, "C": 109, "C++": 33, "fish": 1, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 83, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "TOML": 154, "Proguard": 2, "PlantUML": 6, "Checksums": 46, "Java Server Pages": 11, "Vue": 1, "reStructuredText": 68, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 18, "Handlebars": 1, "Rust": 11, "Go": 34, "Go Checksums": 1, "Go Module": 1, "VBScript": 1, "NSIS": 5, "PowerShell": 1, "SCSS": 2, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.platform.documentation.impl import com.intellij.platform.documentation.ContentUpdater sealed class InternalLinkResult { object InvalidTarget : InternalLinkResult() object CannotResolve : InternalLinkResult() class Request(val request: DocumentationRequest) : InternalLinkResult() class Updater(val updater: ContentUpdater) : InternalLinkResult() }
1
null
1
1
ed76b8fbb07c29a548d5e716b3b54da9861c1844
504
intellij-community
Apache License 2.0
mediator/src/test/kotlin/no/nav/dagpenger/mottak/db/PostgresTestHelper.kt
navikt
351,793,236
false
{"Kotlin": 432966, "Dockerfile": 201}
package no.nav.dagpenger.mottak.db import org.flywaydb.core.internal.configuration.ConfigUtils import org.testcontainers.containers.PostgreSQLContainer import org.testcontainers.containers.PostgreSQLContainer.POSTGRESQL_PORT import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy internal object PostgresTestHelper { val instance by lazy { PostgreSQLContainer<Nothing>("postgres:12").apply { this.waitingFor(HostPortWaitStrategy()) start() } } fun withMigratedDb(block: () -> Unit) { withCleanDb { PostgresDataSourceBuilder.runMigration() block() } } fun withCleanDb(block: () -> Unit) { setup() PostgresDataSourceBuilder.clean().run { block() }.also { tearDown() } } fun setup() { System.setProperty(ConfigUtils.CLEAN_DISABLED, "false") System.setProperty(PostgresDataSourceBuilder.DB_HOST_KEY, instance.host) System.setProperty( PostgresDataSourceBuilder.DB_PORT_KEY, instance.getMappedPort(POSTGRESQL_PORT).toString(), ) System.setProperty(PostgresDataSourceBuilder.DB_DATABASE_KEY, instance.databaseName) System.setProperty(PostgresDataSourceBuilder.DB_PASSWORD_KEY, instance.password) System.setProperty(PostgresDataSourceBuilder.DB_USERNAME_KEY, instance.username) } fun tearDown() { System.clearProperty(PostgresDataSourceBuilder.DB_PASSWORD_KEY) System.clearProperty(PostgresDataSourceBuilder.DB_USERNAME_KEY) System.clearProperty(PostgresDataSourceBuilder.DB_HOST_KEY) System.clearProperty(PostgresDataSourceBuilder.DB_PORT_KEY) System.clearProperty(PostgresDataSourceBuilder.DB_DATABASE_KEY) System.clearProperty(ConfigUtils.CLEAN_DISABLED) } }
5
Kotlin
0
0
9197842a97b95d591d5b157a37328b992f97c56c
1,882
dp-mottak
MIT License
app/src/main/java/com/stylingandroid/muselee/MuseleeAppGlideModule.kt
StylingAndroid
163,316,982
false
null
package com.stylingandroid.muselee import android.content.Context import android.util.Log import com.bumptech.glide.BuildConfig import com.bumptech.glide.GlideBuilder import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule class MuseleeAppGlideModule : AppGlideModule() { override fun applyOptions(context: Context, builder: GlideBuilder) { super.applyOptions(context, builder) if (BuildConfig.DEBUG) { builder.setLogLevel(Log.VERBOSE) } } }
2
null
9
59
7d7e4096e16057e8667446d8a6a4a87c5742ed5d
543
Muselee
Apache License 2.0
wrapper/godot-library/src/main/kotlin/godot/generated/AudioEffectEQ21.kt
payload
189,718,948
true
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch") package godot import godot.gdnative.* import godot.core.* import godot.utils.* import godot.icalls.* import kotlinx.cinterop.* // NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG open class AudioEffectEQ21 : AudioEffectEQ { constructor() : super("AudioEffectEQ21") constructor(variant: Variant) : super(variant) internal constructor(mem: COpaquePointer) : super(mem) internal constructor(name: String) : super(name) // Enums // Signals class Signal { companion object { } } companion object { infix fun from(other: AudioEffectEQ): AudioEffectEQ21 = AudioEffectEQ21("").apply { setRawMemory(other.rawMemory) } infix fun from(other: AudioEffect): AudioEffectEQ21 = AudioEffectEQ21("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Resource): AudioEffectEQ21 = AudioEffectEQ21("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Reference): AudioEffectEQ21 = AudioEffectEQ21("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Object): AudioEffectEQ21 = AudioEffectEQ21("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Variant): AudioEffectEQ21 = fromVariant(AudioEffectEQ21(""), other) // Constants } // Properties // Methods }
0
Kotlin
1
2
70473f9b9a0de08d82222b735e7f9b07bbe91700
1,514
kotlin-godot-wrapper
Apache License 2.0
logging/src/main/kotlin/ru/yuksanbo/common/logging/Logger.kt
yuksanbo
85,976,455
false
null
package ru.yuksanbo.common.logging import org.slf4j.Logger inline fun Logger.debug(op: () -> String) { if (!isDebugEnabled) return debug(op.invoke()) } inline fun Logger.debug(op: () -> String, t: Throwable) { if (!isDebugEnabled) return debug(op.invoke(), t) }
1
Kotlin
0
0
deefce04a45f10878e20c0e45a59aad4b0440fd4
280
common
MIT License
src/main/kotlin/gay/pizza/foundation/concrete/SetupMinecraftServer.kt
GayPizzaSpecifications
512,310,428
false
null
package gay.pizza.foundation.concrete import org.gradle.api.DefaultTask import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.getByType import java.io.File import java.nio.file.Files import java.util.* abstract class SetupMinecraftServer : DefaultTask() { init { outputs.upToDateWhen { false } } @TaskAction fun setupMinecraftAction() { val minecraftServerDirectory = getServerDirectory() if (!minecraftServerDirectory.exists()) { minecraftServerDirectory.mkdirs() } val serverPluginsDirectory = minecraftServerDirectory.resolve("plugins") if (!serverPluginsDirectory.exists()) { serverPluginsDirectory.mkdirs() } for (project in project.findPluginProjects()) { val task = project.shadowJarTask!! val pluginJarFile = task.outputs.files.first() val pluginLinkFile = serverPluginsDirectory.resolve("${project.name}.jar") pluginLinkFile.delete() Files.createSymbolicLink(pluginLinkFile.toPath(), pluginJarFile.toPath()) } val concrete = project.extensions.getByType<ConcreteRootExtension>() if (concrete.acceptServerEula.isPresent && concrete.acceptServerEula.get()) { val writer = minecraftServerDirectory.resolve("eula.txt").bufferedWriter() val properties = Properties() properties.setProperty("eula", "true") properties.store(writer, "Written by Concrete") writer.close() } } @Internal abstract fun getServerDirectory(): File }
3
Kotlin
1
3
c16c5cbcb5060fe46a051d429392e66a97b6fd92
1,522
concrete
MIT License
app/src/main/java/com/xeniac/fifaultimateteamcoin_dsfut_sell_fut/feature_pick_up_player/presentation/picked_up_player_info/components/PickedUpPlayerInfoComponents.kt
WilliamGates99
543,831,202
false
null
package com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.feature_pick_up_player.presentation.picked_up_player_info.components import androidx.compose.animation.AnimatedContent import androidx.compose.animation.animateContentSize import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box 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.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.airbnb.lottie.LottieComposition import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.rememberLottieComposition import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.R import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.domain.models.Player import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.presentation.utils.UiText import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.presentation.utils.asUiText import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.ui.theme.Neutral40 import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.ui.theme.Red import com.xeniac.fifaultimateteamcoin_dsfut_sell_fut.core.ui.theme.RedAlpha20 @Composable fun PickedUpPlayerInfo( player: Player, timerText: String, horizontalPadding: Dp, modifier: Modifier = Modifier, layoutDirection: LayoutDirection = LocalLayoutDirection.current, animationComposition: LottieComposition? = rememberLottieComposition( spec = LottieCompositionSpec.RawRes(R.raw.anim_pick_up_player_success) ).value, animationIteration: Int = 1, animationSpeed: Float = 0.75f ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier ) { Box(modifier = Modifier.fillMaxWidth()) { LottieAnimation( composition = animationComposition, iterations = animationIteration, speed = animationSpeed, modifier = Modifier .align(Alignment.TopCenter) .size(200.dp) ) ExpiryTimer( timerText = when (layoutDirection) { LayoutDirection.Ltr -> timerText LayoutDirection.Rtl -> timerText.reversed() }, modifier = Modifier .align(Alignment.TopEnd) .padding(end = horizontalPadding) ) } Spacer(modifier = Modifier.height(4.dp)) PickUpMessage( message = stringResource( id = R.string.picked_up_player_info_message, player.name ), modifier = Modifier .fillMaxWidth() .padding(horizontal = horizontalPadding) ) Spacer(modifier = Modifier.height(24.dp)) PlayerInfo( player = player, modifier = Modifier.fillMaxWidth() ) } } @Composable fun ExpiryTimer( timerText: String, modifier: Modifier = Modifier, shape: Shape = RoundedCornerShape(4.dp), background: Color = RedAlpha20, fontSize: TextUnit = 10.sp, lineHeight: TextUnit = 10.sp, fontWeight: FontWeight = FontWeight.Black, textAlign: TextAlign = TextAlign.Center, maxLines: Int = 1, color: Color = Red ) { val direction = LocalLayoutDirection.current var oldTimerText by remember { mutableStateOf(timerText) } SideEffect { oldTimerText = timerText } Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier .clip(shape) .background(background) .padding( horizontal = 8.dp, vertical = 4.dp ) .animateContentSize( alignment = when (direction) { LayoutDirection.Ltr -> Alignment.CenterEnd LayoutDirection.Rtl -> Alignment.CenterStart } ) ) { val isTimerFinished = timerText.reversed() == UiText.StringResource( R.string.picked_up_player_info_timer_expired ).asString() if (isTimerFinished) { Text( text = stringResource(id = R.string.picked_up_player_info_timer_expired), fontSize = fontSize, lineHeight = lineHeight, fontWeight = fontWeight, textAlign = textAlign, maxLines = maxLines, color = color ) } else { timerText.indices.forEach { i -> val oldChar = oldTimerText.getOrNull(i) val newChar = timerText[i] val timerChar = if (oldChar == newChar) { oldTimerText[i] } else { timerText[i] } AnimatedContent( targetState = timerChar, transitionSpec = { slideInVertically { -it } togetherWith slideOutVertically { it } }, label = "ExpiryTimer", ) { char -> Text( text = char.toString(), fontSize = fontSize, lineHeight = lineHeight, fontWeight = fontWeight, textAlign = textAlign, maxLines = maxLines, color = color, softWrap = false ) } } } } } @Composable fun PickUpMessage( message: String, modifier: Modifier = Modifier, fontSize: TextUnit = 16.sp, lineHeight: TextUnit = 16.sp, fontWeight: FontWeight = FontWeight.ExtraBold, textAlign: TextAlign = TextAlign.Center, color: Color = MaterialTheme.colorScheme.primary ) { Text( text = message, fontSize = fontSize, lineHeight = lineHeight, fontWeight = fontWeight, textAlign = textAlign, color = color, modifier = modifier ) } @Composable fun PlayerInfo( player: Player, modifier: Modifier = Modifier, ) { var rowHeight by remember { mutableIntStateOf(IntSize.Zero.height) } val rowHeightDp = LocalDensity.current.run { rowHeight.toDp() } Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.onSizeChanged { rowHeight = it.height } ) { Column( verticalArrangement = Arrangement.spacedBy(space = 24.dp), modifier = Modifier .weight(1f) .padding( horizontal = 8.dp, vertical = 8.dp ) ) { PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_rating), value = player.rating, modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_start_price), value = player.buyNowPrice, modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_owners), value = player.owners.toString(), modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_chemistry_style), value = player.chemistryStyle, modifier = Modifier.fillMaxWidth() ) } Box( modifier = Modifier .width(1.dp) .height(rowHeightDp) .clip(RoundedCornerShape(4.dp)) .background(MaterialTheme.colorScheme.outlineVariant) ) Column( verticalArrangement = Arrangement.spacedBy(space = 24.dp), modifier = Modifier .weight(1f) .padding( horizontal = 8.dp, vertical = 8.dp ) ) { PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_position), value = player.position, modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_buy_now_price), value = player.buyNowPrice, modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_contracts), value = player.contracts.toString(), modifier = Modifier.fillMaxWidth() ) PlayerInfoText( title = stringResource(id = R.string.picked_up_player_info_title_platform), value = player.platform.asUiText().asString(), modifier = Modifier.fillMaxWidth() ) } } } @Composable fun PlayerInfoText( title: String, value: String, modifier: Modifier = Modifier, titleFontSize: TextUnit = 12.sp, titleLineHeight: TextUnit = 12.sp, titleFontWeight: FontWeight = FontWeight.SemiBold, titleTextAlign: TextAlign = TextAlign.Center, titleMaxLines: Int = 1, titleColor: Color = Neutral40, valueFontSize: TextUnit = 14.sp, valueLineHeight: TextUnit = 14.sp, valueFontWeight: FontWeight = FontWeight.ExtraBold, valueTextAlign: TextAlign = TextAlign.Center, valueMaxLines: Int = 1, valueColor: Color = MaterialTheme.colorScheme.onSurfaceVariant ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(space = 4.dp), modifier = modifier ) { Text( text = title, fontSize = titleFontSize, lineHeight = titleLineHeight, fontWeight = titleFontWeight, textAlign = titleTextAlign, maxLines = titleMaxLines, color = titleColor, modifier = Modifier .fillMaxSize() .basicMarquee() ) Text( text = value, fontSize = valueFontSize, lineHeight = valueLineHeight, fontWeight = valueFontWeight, textAlign = valueTextAlign, maxLines = valueMaxLines, color = valueColor, modifier = Modifier .fillMaxSize() .basicMarquee() ) } }
0
null
0
1
a0b03bf204e6e681bbe587fdc928bff81e7e67e6
12,583
FUTSale
Apache License 2.0
CustomizeKeyBoard/app/src/main/java/com/aqrlei/customizekeyboard/MainActivity.kt
AqrLei
348,929,204
false
null
package com.aqrlei.customizekeyboard import android.os.Bundle import android.util.Log import android.view.View import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val et = findViewById<EditText>(R.id.etInput) val keyboardView = findViewById<NumberSimpleKeyboardView>(R.id.numberKeyboard) val keyboardUtil = KeyBoardUtil() keyboardUtil.bind(this, keyboardView, et) findViewById<View>(R.id.tvHelloWorld).setOnClickListener { Log.d("TouchDown", "hello world click") Toast.makeText(this,"hello world",Toast.LENGTH_SHORT).show() } } }
0
Kotlin
1
0
cd83243144ceb0a3c6f8c344953de76662bd2cd1
855
CustomizeWidgets
Apache License 2.0
androidApp/src/main/java/com/example/movieskmm/android/ui/components/MovieList.kt
pushpalroy
735,486,564
false
{"Kotlin": 130661, "Swift": 14743, "Ruby": 2424, "Shell": 255}
package com.example.movieskmm.android.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.movieskmm.domain.model.MovieItem @Composable internal fun MovieList( modifier: Modifier = Modifier, listItems: List<MovieItem>, onClick: (id: Int) -> Unit ) { LazyVerticalGrid(columns = GridCells.Fixed(2), modifier = modifier.padding(start = 5.dp, end = 5.dp, top = 0.dp), content = { items(listItems) { movieItem -> Column( modifier = Modifier.padding( start = 5.dp, end = 5.dp, top = 0.dp, bottom = 10.dp ) ) { MovieItem( modifier = Modifier, movieItem = movieItem, onClick = onClick ) } } } ) }
12
Kotlin
0
8
fdd72a9062e3bd962291554b3c597000746bf53c
1,243
movieskmm
MIT License
kmath-optimization/src/commonMain/kotlin/space/kscience/kmath/optimization/QowOptimizer.kt
SciProgCentre
129,486,382
false
{"Kotlin": 1988014, "ANTLR": 887}
/* * Copyright 2018-2022 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.kmath.optimization import space.kscience.kmath.UnstableKMathAPI import space.kscience.kmath.expressions.* import space.kscience.kmath.linear.* import space.kscience.kmath.misc.log import space.kscience.kmath.operations.Float64Field import space.kscience.kmath.operations.Float64L2Norm import space.kscience.kmath.operations.algebra import space.kscience.kmath.structures.Float64Buffer import kotlin.math.abs public class QowRuns(public val runs: Int) : OptimizationFeature { init { require(runs >= 1) { "Number of runs must be more than zero" } } override fun toString(): String = "QowRuns(runs=$runs)" } /** * An optimizer based onf Fyodor Tkachev's quasi-optimal weights method. * See [the article](http://arxiv.org/abs/physics/0604127). */ @UnstableKMathAPI public object QowOptimizer : Optimizer<Double, XYFit> { private val linearSpace: LinearSpace<Double, Float64Field> = Double.algebra.linearSpace private val solver: LinearSolver<Double> = linearSpace.lupSolver() @OptIn(UnstableKMathAPI::class) private class QoWeight( val problem: XYFit, val freeParameters: Map<Symbol, Double>, ) : SymbolIndexer { val size get() = freeParameters.size override val symbols: List<Symbol> = freeParameters.keys.toList() val data get() = problem.data val allParameters by lazy { problem.startPoint + freeParameters } /** * Derivatives of the spectrum over parameters. First index in the point number, second one - index of parameter */ val derivs: Matrix<Double> by lazy { linearSpace.buildMatrix(problem.data.size, symbols.size) { d, s -> problem.distance(d).derivative(symbols[s]).invoke(allParameters) } } /** * Array of dispersions in each point */ val dispersion: Point<Double> by lazy { Float64Buffer(problem.data.size) { d -> 1.0 / problem.weight(d).invoke(allParameters) } } val prior: DifferentiableExpression<Double>? get() = problem.getFeature<OptimizationPrior<Double>>()?.withDefaultArgs(allParameters) override fun toString(): String = freeParameters.toString() } /** * The signed distance from the model to the [d]-th point of data. */ private fun QoWeight.distance(d: Int, parameters: Map<Symbol, Double>): Double = problem.distance(d)(allParameters + parameters) /** * The derivative of [distance] */ private fun QoWeight.distanceDerivative(symbol: Symbol, d: Int, parameters: Map<Symbol, Double>): Double = problem.distance(d).derivative(symbol).invoke(allParameters + parameters) /** * Theoretical covariance of weight functions * * D(\phi)=E(\phi_k(\theta_0) \phi_l(\theta_0))= disDeriv_k * disDeriv_l /sigma^2 */ private fun QoWeight.covarF(): Matrix<Double> = linearSpace.matrix(size, size).symmetric { s1, s2 -> (0 until data.size).sumOf { d -> derivs[d, s1] * derivs[d, s2] / dispersion[d] } } /** * Experimental covariance Eq (22) from * http://arxiv.org/abs/physics/0604127 */ private fun QoWeight.covarFExp(theta: Map<Symbol, Double>): Matrix<Double> = with(linearSpace) { /* * Важно! Если не делать предварителього вычисления этих производных, то * количество вызывов функции будет dim^2 вместо dim Первый индекс - * номер точки, второй - номер переменной, по которой берется производная */ val eqvalues = linearSpace.buildMatrix(data.size, size) { d, s -> distance(d, theta) * derivs[d, s] / dispersion[d] } buildMatrix(size, size) { s1, s2 -> (0 until data.size).sumOf { d -> eqvalues[d, s2] * eqvalues[d, s1] } } } /** * Equation derivatives for Newton run */ private fun QoWeight.getEqDerivValues( theta: Map<Symbol, Double> = freeParameters, ): Matrix<Double> = with(linearSpace) { //Derivative of k Eq over l parameter val sderiv = buildMatrix(data.size, size) { d, s -> distanceDerivative(symbols[s], d, theta) } buildMatrix(size, size) { s1, s2 -> val base = (0 until data.size).sumOf { d -> require(dispersion[d] > 0) sderiv[d, s2] * derivs[d, s1] / dispersion[d] } prior?.let { prior -> //Check if this one is correct val pi = prior(theta) val deriv1 = prior.derivative(symbols[s1])(theta) val deriv2 = prior.derivative(symbols[s2])(theta) base + deriv1 * deriv2 / pi / pi } ?: base } } /** * Quasi optimal weights equations values */ private fun QoWeight.getEqValues(theta: Map<Symbol, Double>): Point<Double> { val distances = Float64Buffer(data.size) { d -> distance(d, theta) } return Float64Buffer(size) { s -> val base = (0 until data.size).sumOf { d -> distances[d] * derivs[d, s] / dispersion[d] } //Prior probability correction prior?.let { prior -> base - prior.derivative(symbols[s]).invoke(theta) / prior(theta) } ?: base } } private fun QoWeight.newtonianStep( theta: Map<Symbol, Double>, eqValues: Point<Double>, ): QoWeight = linearSpace { val start = theta.toPoint() val invJacob = solver.inverse(getEqDerivValues(theta)) val step = invJacob.dot(eqValues) return QoWeight(problem, theta + (start - step).toMap()) } private fun QoWeight.newtonianRun( maxSteps: Int = 100, tolerance: Double = 0.0, fast: Boolean = false, ): QoWeight { val logger = problem.getFeature<OptimizationLog>() var dis: Double //discrepancy value var par = freeParameters logger?.log { "Starting newtonian iteration from: \n\t$allParameters" } var eqvalues = getEqValues(par) //Values of the weight functions dis = Float64L2Norm.norm(eqvalues) // discrepancy logger?.log { "Starting discrepancy is $dis" } var i = 0 var flag = false while (!flag) { i++ logger?.log { "Starting step number $i" } val currentSolution = if (fast) { //Matrix values in the point of weight computation newtonianStep(freeParameters, eqvalues) } else { //Matrix values in a current point newtonianStep(par, eqvalues) } // здесь должен стоять учет границ параметров logger?.log { "Parameter values after step are: \n\t$currentSolution" } eqvalues = getEqValues(currentSolution.freeParameters) val currentDis = Float64L2Norm.norm(eqvalues)// discrepancy after the step logger?.log { "The discrepancy after step is: $currentDis." } if (currentDis >= dis && i > 1) { //Check if one step is made flag = true logger?.log { "The discrepancy does not decrease. Stopping iteration." } } else if (abs(dis - currentDis) <= tolerance) { flag = true par = currentSolution.freeParameters logger?.log { "Relative discrepancy tolerance threshold is reached. Stopping iteration." } } else { par = currentSolution.freeParameters dis = currentDis } if (i >= maxSteps) { flag = true logger?.log { "Maximum number of iterations reached. Stopping iteration." } } } return QoWeight(problem, par) } private fun QoWeight.covariance(): NamedMatrix<Double> { val logger = problem.getFeature<OptimizationLog>() logger?.log { """ Starting errors estimation using quasi-optimal weights method. The starting weight is: $allParameters """.trimIndent() } val covar = solver.inverse(getEqDerivValues()) //TODO fix eigenvalues check // val decomposition = EigenDecomposition(covar.matrix) // var valid = true // for (lambda in decomposition.realEigenvalues) { // if (lambda <= 0) { // logger?.log { "The covariance matrix is not positive defined. Error estimation is not valid" } // valid = false // } // } logger?.log { "Covariance matrix:" + "\n" + NamedMatrix.toStringWithSymbols(covar, this) } return covar.named(symbols) } override suspend fun optimize(problem: XYFit): XYFit { val qowRuns = problem.getFeature<QowRuns>()?.runs ?: 2 val iterations = problem.getFeature<OptimizationIterations>()?.maxIterations ?: 50 val freeParameters: Map<Symbol, Double> = problem.getFeature<OptimizationParameters>()?.let { op -> problem.startPoint.filterKeys { it in op.symbols } } ?: problem.startPoint var qow = QoWeight(problem, freeParameters) var res = qow.newtonianRun(maxSteps = iterations) repeat(qowRuns - 1) { qow = QoWeight(problem, res.freeParameters) res = qow.newtonianRun(maxSteps = iterations) } val covariance = res.covariance() return res.problem.withFeature(OptimizationResult(res.freeParameters), OptimizationCovariance(covariance)) } }
91
Kotlin
55
645
6c1a5e62bff541cca8065e4ab4c97d02a29d685a
9,946
kmath
Apache License 2.0
polyline/src/main/java/com/utsman/geolib/polyline/data/PolylineDrawMode.kt
utsmannn
334,631,862
false
null
/* * Created on 3/2/21 12:58 AM * Copyright (c) <NAME> 2021 All rights reserved. */ package com.utsman.geolib.polyline.data sealed class PolylineDrawMode { object Normal : PolylineDrawMode() object Curved : PolylineDrawMode() object Lank : PolylineDrawMode() }
0
Kotlin
12
98
10d6f591b54c386d16bc643028759ae0f8fe8ac6
277
geolib
Apache License 2.0
shared/src/commonMain/kotlin/com/tomczyn/linkding/features/home/HomeScreenTag.kt
tomczyn
599,241,128
false
null
package com.tomczyn.linkding.features.home data class HomeScreenTag( val name: String, val numberOfBookmarks: Int, )
0
Kotlin
0
0
fd72c0057fb10fe2130af21c4a08947068fcad13
126
linkding-mobile
MIT License
sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt
mike-burns
315,937,144
false
null
package io.sentry.android.core import android.content.Context import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import io.sentry.DiagnosticLogger import io.sentry.ILogger import io.sentry.SentryEvent import io.sentry.SentryLevel import io.sentry.SentryOptions import io.sentry.android.core.DefaultAndroidEventProcessor.ANDROID_ID import io.sentry.android.core.DefaultAndroidEventProcessor.EMULATOR import io.sentry.android.core.DefaultAndroidEventProcessor.KERNEL_VERSION import io.sentry.android.core.DefaultAndroidEventProcessor.PROGUARD_UUID import io.sentry.android.core.DefaultAndroidEventProcessor.ROOTED import io.sentry.protocol.SdkVersion import io.sentry.protocol.SentryThread import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DefaultAndroidEventProcessorTest { private lateinit var context: Context private class Fixture { val buildInfo = mock<IBuildInfoProvider>() val options = SentryOptions().apply { isDebug = true setLogger(mock()) sdkVersion = SdkVersion().apply { name = "test" version = "1.2.3" } } } private val fixture = Fixture() @BeforeTest fun `set up`() { context = ApplicationProvider.getApplicationContext() } @Test fun `when instance is created, application context reference is stored`() { val sut = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) assertEquals(sut.context, context) } @Test fun `when null context is provided, invalid argument is thrown`() { val clazz = Class.forName("io.sentry.android.core.DefaultAndroidEventProcessor") val ctor = clazz.getConstructor(Context::class.java, ILogger::class.java, IBuildInfoProvider::class.java) val params = arrayOf(null, mock<SentryOptions>(), null) assertFailsWith<IllegalArgumentException> { ctor.newInstance(params) } } @Test fun `when null options is provided, invalid argument is thrown`() { val clazz = Class.forName("io.sentry.android.core.DefaultAndroidEventProcessor") val ctor = clazz.getConstructor(Context::class.java, ILogger::class.java, IBuildInfoProvider::class.java) val params = arrayOf(mock<Context>(), null, null) assertFailsWith<IllegalArgumentException> { ctor.newInstance(params) } } @Test fun `when null buildInfo is provided, invalid argument is thrown`() { val clazz = Class.forName("io.sentry.android.core.DefaultAndroidEventProcessor") val ctor = clazz.getConstructor(Context::class.java, ILogger::class.java, IBuildInfoProvider::class.java) val params = arrayOf(null, null, mock<IBuildInfoProvider>()) assertFailsWith<IllegalArgumentException> { ctor.newInstance(params) } } @Test fun `When hint is not Cached, data should be applied`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) var event = SentryEvent().apply { } // refactor and mock data later on event = processor.process(event, null) assertNotNull(event.user) assertNotNull(event.contexts.app) assertEquals("test", event.debugMeta.images[0].uuid) assertNotNull(event.dist) } @Test fun `Current should be true if it comes from main thread`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) val sentryThread = SentryThread().apply { id = Looper.getMainLooper().thread.id } var event = SentryEvent().apply { threads = mutableListOf(sentryThread) } // refactor and mock data later on event = processor.process(event, null) assertTrue(event.threads.first().isCurrent) } @Test fun `Current should be false if it its not the main thread`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) val sentryThread = SentryThread().apply { id = 10L } var event = SentryEvent().apply { threads = mutableListOf(sentryThread) } // refactor and mock data later on event = processor.process(event, null) assertFalse(event.threads.first().isCurrent) } @Test fun `When hint is Cached, data should not be applied`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) var event = SentryEvent().apply { } // refactor and mock data later on event = processor.process(event, CachedEvent()) assertNull(event.user) assertNull(event.contexts.app) assertNull(event.debugMeta) assertNull(event.release) assertNull(event.dist) } @Test fun `Executor service should be called on ctor`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo) val contextData = processor.contextData.get() assertNotNull(contextData) assertEquals("test", (contextData[PROGUARD_UUID] as Array<*>)[0]) assertNotNull(contextData[ROOTED]) assertNotNull(contextData[ANDROID_ID]) assertNotNull(contextData[KERNEL_VERSION]) assertNotNull(contextData[EMULATOR]) } @Test fun `Processor won't throw exception`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo, mock()) processor.process(SentryEvent(), null) verify((fixture.options.logger as DiagnosticLogger).logger, never())!!.log(eq(SentryLevel.ERROR), any<String>(), any()) } @Test fun `Processor won't throw exception when theres a hint`() { val processor = DefaultAndroidEventProcessor(context, fixture.options.logger, fixture.buildInfo, mock()) processor.process(SentryEvent(), CachedEvent()) verify((fixture.options.logger as DiagnosticLogger).logger, never())!!.log(eq(SentryLevel.ERROR), any<String>(), any()) } }
1
null
1
1
8f9b3923f6ae79bdbaedfbce6a8f4df5e9158150
6,690
sentry-java
MIT License
demo/src/main/java/ovh/plrapps/mapcompose/demo/viewmodels/CalloutVM.kt
p-lr
359,208,603
false
null
package ovh.plrapps.mapcompose.demo.viewmodels import android.app.Application import android.content.Context import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.lifecycle.AndroidViewModel import ovh.plrapps.mapcompose.api.* import ovh.plrapps.mapcompose.demo.R import ovh.plrapps.mapcompose.demo.providers.makeTileStreamProvider import ovh.plrapps.mapcompose.demo.ui.widgets.Callout import ovh.plrapps.mapcompose.ui.state.MapState class CalloutVM(application: Application) : AndroidViewModel(application) { private val appContext: Context by lazy { getApplication<Application>().applicationContext } private val tileStreamProvider = makeTileStreamProvider(appContext) /* Define the markers data (id and position) */ private val markers = listOf( MarkerInfo("Callout #1", 0.45, 0.6), MarkerInfo("Callout #2", 0.24, 0.1), MarkerInfo(TAP_TO_DISMISS_ID, 0.4, 0.3) ) val state: MapState by mutableStateOf( MapState(4, 4096, 4096, tileStreamProvider).apply { /* Add all markers */ for (marker in markers) { addMarker(marker.id, marker.x, marker.y) { Icon( painter = painterResource(id = R.drawable.map_marker), contentDescription = null, modifier = Modifier.size(50.dp), tint = Color(0xCC2196F3) ) } } scale = 0f /** * On marker click, add a callout. If the id is [TAP_TO_DISMISS_ID], set auto-dismiss * to false. For this particular id, we programmatically remove the callout on tap. */ onMarkerClick { id, x, y -> var shouldAnimate by mutableStateOf(true) addCallout( id, x, y, absoluteOffset = Offset(0f, -130f), autoDismiss = id != TAP_TO_DISMISS_ID, clickable = id == TAP_TO_DISMISS_ID ) { Callout(x, y, title = id, shouldAnimate) { shouldAnimate = false } } } /** * Register a click listener on callouts. We don't need to remove the other callouts * because they automatically dismiss on touch down. */ onCalloutClick { id, _, _ -> if (id == TAP_TO_DISMISS_ID) removeCallout(TAP_TO_DISMISS_ID) } } ) } private data class MarkerInfo(val id: String, val x: Double, val y: Double) private const val TAP_TO_DISMISS_ID = "Tap me to dismiss"
6
null
7
96
e65762b45cc7418cbae54e0673405d109da7aadd
3,094
MapCompose
Apache License 2.0
src/commonMain/kotlin/csense/kotlin/extensions/collections/generic/CollectionBounds.kt
csense-oss
136,911,995
false
null
@file:Suppress("MemberVisibilityCanBePrivate") package csense.kotlin.extensions.collections.generic import csense.kotlin.annotations.numbers.* import csense.kotlin.extensions.* import csense.kotlin.extensions.primitives.* import kotlin.jvm.* public sealed interface CollectionBounds { public fun inBoundsEndNotInBounds(index: Int): Boolean public fun inBoundsEndInBounds(index: Int): Boolean public companion object { @Suppress("MissingTestFunction") //plugin bug public fun from(collectionLength: Int): CollectionBounds = when { collectionLength.isNegative -> CollectionBoundsAlwaysOutOfBounds collectionLength.isZero -> CollectionBoundsZeroBoundsChecker else -> CollectionBoundsChecker(collectionLength) } } } public fun CollectionBounds(collectionLength: Int): CollectionBounds = CollectionBounds.from(collectionLength) public fun CollectionBounds.outOfBoundsEndOutOfBounds(index: Int): Boolean { return !inBoundsEndNotInBounds(index) } public fun CollectionBounds.outOfBoundsEndInBounds(index: Int): Boolean { return !inBoundsEndInBounds(index) } public fun CollectionBounds.inBounds(index: Int, isEndInBounds: Boolean): Boolean { return isEndInBounds.map( ifTrue = ::inBoundsEndInBounds, ifFalse = ::inBoundsEndNotInBounds ).invoke(index) } public fun CollectionBounds.outOfBounds(index: Int, isEndOutOfBonds: Boolean): Boolean { return isEndOutOfBonds.map( ifTrue = ::outOfBoundsEndOutOfBounds, ifFalse = ::outOfBoundsEndInBounds ).invoke(index) } public object CollectionBoundsAlwaysOutOfBounds : CollectionBounds { override fun inBoundsEndNotInBounds(index: Int): Boolean { return false } override fun inBoundsEndInBounds(index: Int): Boolean { return false } } public object CollectionBoundsZeroBoundsChecker : CollectionBounds { override fun inBoundsEndNotInBounds(index: Int): Boolean { return false } override fun inBoundsEndInBounds(index: Int): Boolean { return index == 0 } } @JvmInline public value class CollectionBoundsChecker internal constructor( @IntLimit(from = 1) public val collectionLength: Int ) : CollectionBounds { override fun inBoundsEndNotInBounds(index: Int): Boolean { return index < collectionLength && index.isPositiveOrZero } override fun inBoundsEndInBounds(index: Int): Boolean { return index <= collectionLength && index.isPositiveOrZero } } public inline val Collection<*>.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val CharSequence.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = length) public inline val Map<*, *>.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) //region array types public inline val Array<*>.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val BooleanArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val ByteArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val CharArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val DoubleArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val FloatArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val IntArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val LongArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) public inline val ShortArray.isIndex: CollectionBounds get() = CollectionBounds(collectionLength = size) //endregion
1
Kotlin
0
2
49113dd6b2cb1e18992d07faa1e0305d18f766f4
3,892
csense-kotlin
MIT License
demo-transactions/src/main/kotlin/io/holixon/cqrshexagonaldemo/demoparent/transactions/command/application/usecase/DepositUsecase.kt
holixon
747,608,283
false
{"Kotlin": 69299, "Shell": 72}
package io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.usecase import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.inbound.account.DepositAccountInPort import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.outbound.account.AccountService import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.application.port.outbound.eventing.EventingOutAdapter import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.account.Amount import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.account.Iban import io.holixon.cqrshexagonaldemo.demoparent.transactions.command.domain.model.event.MoneyDepositedEvent import io.holixon.cqrshexagonaldemo.demoparent.transactions.shared.framework.Usecase import mu.KLogging import java.math.BigDecimal @Usecase class DepositUsecase( private val accountService: AccountService, private val eventingOutAdapter: EventingOutAdapter ) : DepositAccountInPort { companion object : KLogging() override fun deposit(iban: Iban, amount: Amount) { logger().info { "deposit $amount to account ${iban.value}" } require(amount.value >= BigDecimal.ZERO) { logger().error { "Amount must be positive" } } val account = accountService.findAccount(iban) val updatedAccount = accountService.deposit(account, amount) eventingOutAdapter.publishEvent( MoneyDepositedEvent( updatedAccount.iban, updatedAccount.balance, System.currentTimeMillis() ) ) logger().info { "updated account $updatedAccount" } } }
3
Kotlin
0
0
e634c14ca89f3de72f53ae6680c8ca12c539d6a7
1,764
cqrs-meets-hexagonal
Apache License 2.0
languages/javalang/builder-renderer/java-builder-client/src/main/kotlin/io/vrap/codegen/languages/javalang/client/builder/producers/JavaModelDraftBuilderFileProducer.kt
commercetools
136,635,215
false
{"Kotlin": 1401769, "RAML": 92051, "Groovy": 37966, "Java": 12163, "PHP": 5795, "JavaScript": 5731, "Shell": 3692, "TypeScript": 2505, "Dockerfile": 303}
package io.vrap.codegen.languages.javalang.client.builder.producers import io.vrap.codegen.languages.extensions.hasSubtypes import io.vrap.codegen.languages.extensions.isPatternProperty import io.vrap.codegen.languages.extensions.toComment import io.vrap.codegen.languages.java.base.JavaBaseTypes import io.vrap.codegen.languages.java.base.JavaSubTemplates import io.vrap.codegen.languages.java.base.extensions.* import io.vrap.rmf.codegen.firstUpperCase import io.vrap.rmf.codegen.di.AllObjectTypes import io.vrap.rmf.codegen.io.TemplateFile import io.vrap.rmf.codegen.rendering.FileProducer import io.vrap.rmf.codegen.rendering.utils.escapeAll import io.vrap.rmf.codegen.rendering.utils.keepIndentation import io.vrap.rmf.codegen.types.VrapArrayType import io.vrap.rmf.codegen.types.VrapObjectType import io.vrap.rmf.codegen.types.VrapTypeProvider import io.vrap.rmf.raml.model.types.* import io.vrap.rmf.raml.model.types.Annotation import javax.lang.model.SourceVersion class JavaModelDraftBuilderFileProducer constructor(override val vrapTypeProvider: VrapTypeProvider, @AllObjectTypes private val allObjectTypes: List<ObjectType>) : JavaObjectTypeExtensions, JavaEObjectTypeExtensions, FileProducer { override fun produceFiles(): List<TemplateFile> { return allObjectTypes.filter { !it.isAbstract() && !it.deprecated() }.map { render(it) } .plus(allObjectTypes.filter { it.isAbstract() && it.discriminator != null }.map { renderAbstract(it) }) } fun render(type: ObjectType): TemplateFile { val vrapType = vrapTypeProvider.doSwitch(type).toJavaVType() as VrapObjectType val extends = listOf("Builder<${vrapType.simpleClassName}>".escapeAll()) .plus( when (val ex = type.getAnnotation("java-builder-implements") ) { is Annotation -> { (ex.value as StringInstance).value.escapeAll() } else -> null } ) .filterNotNull() val content : String = """ |package ${vrapType.`package`}; | |${type.imports()} |import ${vrapType.`package`}.${vrapType.simpleClassName}; |import javax.annotation.Nullable; |import java.util.*; |import java.util.function.Function; |import java.time.ZonedDateTime; |import io.vrap.rmf.base.client.Builder; |import io.vrap.rmf.base.client.utils.Generated; | |/** | * ${vrapType.simpleClassName}Builder | * \<hr\> | <${type.builderComment().escapeAll()}> | */ |<${JavaSubTemplates.generatedAnnotation}>${if (type.markDeprecated() ) """ |@Deprecated""" else ""} |public class ${vrapType.simpleClassName}Builder implements ${extends.joinToString(", ")} { | | <${type.fields().escapeAll()}> | | <${type.assignments().escapeAll()}> | | <${type.getters().escapeAll()}> | | /** | * builds ${vrapType.simpleClassName} with checking for non-null required values | * @return ${vrapType.simpleClassName} | */ | public ${vrapType.simpleClassName} build() { | <${type.requiredChecks().escapeAll()}> | <${type.buildMethodBody().escapeAll()}> | } | | /** | * builds ${vrapType.simpleClassName} without checking for non-null required values | * @return ${vrapType.simpleClassName} | */ | public ${vrapType.simpleClassName} buildUnchecked() { | <${type.buildMethodBody().escapeAll()}> | } | | <${type.staticOfMethod().escapeAll()}> | | <${type.templateMethod()}> | | <${type.getAnnotation("java-builder-mixin")?.value?.value?.let { (it as String).escapeAll()} ?: ""}> |} """.trimMargin().keepIndentation() return TemplateFile( relativePath = "${vrapType.`package`}.${vrapType.simpleClassName}Builder".replace(".", "/") + ".java", content = content ) } fun renderAbstract(type: ObjectType): TemplateFile { val vrapType = vrapTypeProvider.doSwitch(type).toJavaVType() as VrapObjectType val extends = emptyList<String>() .plus( when (val ex = type.getAnnotation("java-builder-implements") ) { is Annotation -> { (ex.value as StringInstance).value.escapeAll() } else -> null } ) .filterNotNull() val content : String = """ |package ${vrapType.`package`}; | |${type.imports()} |import ${vrapType.`package`}.${vrapType.simpleClassName}; |import javax.annotation.Nullable; |import java.util.*; |import java.util.function.Function; |import java.time.ZonedDateTime; |import io.vrap.rmf.base.client.Builder; |import io.vrap.rmf.base.client.utils.Generated; | |/** | * ${vrapType.simpleClassName}Builder | */ |<${JavaSubTemplates.generatedAnnotation}>${if (type.markDeprecated() ) """ |@Deprecated""" else ""} |public class ${vrapType.simpleClassName}Builder${if (extends.isNotEmpty()) { " implements ${extends.joinToString(separator = ", ")}" } else ""} { | | <${type.subTypeBuilders().escapeAll()}> | | <${type.staticOfMethod().escapeAll()}> | | <${type.getAnnotation("java-builder-mixin")?.value?.value?.let { (it as String).escapeAll()} ?: ""}> |} """.trimMargin().keepIndentation() return TemplateFile( relativePath = "${vrapType.`package`}.${vrapType.simpleClassName}Builder".replace(".", "/") + ".java", content = content ) } private fun ObjectType.subTypeBuilders() : String { if (this.hasSubtypes()) { return this.subTypes.plus(this.subTypes.flatMap { it.subTypes }).distinctBy { it.name } .asSequence() .filterIsInstance<ObjectType>() .filter { it.getAnnotation("deprecated") == null } .filter { it.discriminatorValue != null } .sortedBy { anyType -> anyType.name } .map { val vrapSubType = vrapTypeProvider.doSwitch(it) as VrapObjectType """ |public ${vrapSubType.`package`.toJavaPackage()}.${vrapSubType.simpleClassName}Builder ${it.discriminatorValue.lowerCamelCase()}Builder() { | return ${vrapSubType.`package`.toJavaPackage()}.${vrapSubType.simpleClassName}Builder.of(); |} """.trimMargin() } .joinToString(separator = "\n") } return "" } private fun ObjectType.fields() = this.allProperties .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .map { it.toField() } .joinToString(separator = "\n\n") private fun Property.toField() : String { val vrapType = this.type.toVrapType() return if(this.isPatternProperty()){ """ |${this.deprecationAnnotation()} |${if(!this.required) "@Nullable" else ""} |private Map<String, ${vrapType.fullClassName()}> values = new HashMap<>(); """.escapeAll().trimMargin().keepIndentation() } else if(this.name.equals("interface")) { """ |${this.deprecationAnnotation()} |${if (!this.required) "@Nullable" else ""} |private ${vrapType.fullClassName()} _interface; """.trimMargin() }else{ """ |${this.deprecationAnnotation()} |${if(!this.required) "@Nullable" else ""} |private ${vrapType.fullClassName()} ${this.name}; """.escapeAll().trimMargin().keepIndentation() } } private fun ObjectType.assignments() : String { val vrapType = vrapTypeProvider.doSwitch(this).toJavaVType() as VrapObjectType return this.allProperties .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .map { assignment(it, vrapType) }.joinToString(separator = "\n\n") } private fun assignment(property: Property, type: VrapObjectType) : String { val propertyType = property.type; val propType = propertyType.toVrapType() return if(property.isPatternProperty()) { """ |/** |${propertyType.toComment(" * assign pattern properties to the builder")} | * @param values properties to be set | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder values(${if (!property.required) "@Nullable" else ""} final Map<String, ${propType.fullClassName()}> values){ | this.values = values; | return this; |} | |/** |${propertyType.toComment(" * assign a pattern property to the builder")} | * @param key property name | * @param value property value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder addValue(final String key, final ${propType.fullClassName()} value) { | if (this.values == null) { | values = new HashMap<>(); | } | values.put(key, value); | return this; |} """.escapeAll().trimMargin().keepIndentation() } else if (propType is VrapArrayType) { var propertyName = property.name val propItemType = (property.type as ArrayType).items if(SourceVersion.isKeyword(propertyName)) { propertyName = "_$propertyName" } """ |/** |${propertyType.toComment(" * set values to the $propertyName")} | * @param $propertyName value to be set | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder $propertyName(${if (!property.required) "@Nullable" else ""} final ${propType.itemType.fullClassName()} ...$propertyName) { | this.$propertyName = new ArrayList<>(Arrays.asList($propertyName)); | return this; |} | |/** |${propertyType.toComment(" * set value to the $propertyName")} | * @param $propertyName value to be set | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder $propertyName(${if (!property.required) "@Nullable" else ""} final ${propType.fullClassName()} $propertyName) { | this.$propertyName = $propertyName; | return this; |} | |/** |${propertyType.toComment(" * add values to the $propertyName")} | * @param $propertyName value to be set | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder plus${propertyName.firstUpperCase()}(${if (!property.required) "@Nullable" else ""} final ${propType.itemType.fullClassName()} ...$propertyName) { | if (this.$propertyName == null) { | this.$propertyName = new ArrayList<>(); | } | this.$propertyName.addAll(Arrays.asList($propertyName)); | return this; |} | |${if (propItemType is ObjectType && propItemType.isAbstract() && propItemType.discriminator != null) """ |/** |${propertyType.toComment(" * add a value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder plus${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, Builder<? extends ${propType.itemType.fullClassName()}>> builder) { | if (this.$propertyName == null) { | this.$propertyName = new ArrayList<>(); | } | this.$propertyName.add(builder.apply(${propType.itemType.fullClassName()}Builder.of()).build()); | return this; |} | |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder with${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, Builder<? extends ${propType.itemType.fullClassName()}>> builder) { | this.$propertyName = new ArrayList<>(); | this.$propertyName.add(builder.apply(${propType.itemType.fullClassName()}Builder.of()).build()); | return this; |} """ else ""} |${if (propItemType is ObjectType && !propItemType.isAbstract() && propType.simpleName() != JavaBaseTypes.objectType.simpleName()) """ |/** |${propertyType.toComment(" * add the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder plus${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, ${propType.itemType.fullClassName()}Builder> builder) { | if (this.$propertyName == null) { | this.$propertyName = new ArrayList<>(); | } | this.$propertyName.add(builder.apply(${propType.itemType.fullClassName()}Builder.of()).build()); | return this; |} | |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder with${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, ${propType.itemType.fullClassName()}Builder> builder) { | this.$propertyName = new ArrayList<>(); | this.$propertyName.add(builder.apply(${propType.itemType.fullClassName()}Builder.of()).build()); | return this; |} | |/** |${propertyType.toComment(" * add the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder add${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, ${propType.itemType.fullClassName()}> builder) { | return plus${property.name.firstUpperCase()}(builder.apply(${propType.itemType.fullClassName()}Builder.of())); |} | |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder set${property.name.firstUpperCase()}(Function<${propType.itemType.fullClassName()}Builder, ${propType.itemType.fullClassName()}> builder) { | return $propertyName(builder.apply(${propType.itemType.fullClassName()}Builder.of())); |} """ else ""} """.trimMargin() } else { var propertyName = property.name var checkedPropertyType = if (propertyType.isInlineType) propertyType.type else propertyType if(SourceVersion.isKeyword(propertyName)) { propertyName = "_$propertyName" } """ |${if (checkedPropertyType is ObjectType && !checkedPropertyType.isAbstract() && propType.simpleName() != JavaBaseTypes.objectType.simpleName()) """ |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder $propertyName(Function<${propType.fullClassName()}Builder, ${propType.fullClassName()}Builder> builder) { | this.$propertyName = builder.apply(${propType.fullClassName()}Builder.of()).build(); | return this; |} | |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder with${propertyName.firstUpperCase()}(Function<${propType.fullClassName()}Builder, ${propType.fullClassName()}> builder) { | this.$propertyName = builder.apply(${propType.fullClassName()}Builder.of()); | return this; |} """ else ""} |/** |${propertyType.toComment(" * set the value to the $propertyName")} | * @param $propertyName value to be set | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder $propertyName(${if (!property.required) "@Nullable" else ""} final ${propType.fullClassName()} $propertyName) { | this.$propertyName = $propertyName; | return this; |} | |${if (checkedPropertyType is ObjectType && checkedPropertyType.isAbstract() && checkedPropertyType.discriminator != null) """ |/** |${propertyType.toComment(" * set the value to the $propertyName using the builder function")} | * @param builder function to build the $propertyName value | * @return Builder | */ |${property.deprecationAnnotation()} |public ${type.simpleClassName}Builder $propertyName(Function<${propType.fullClassName()}Builder, Builder<? extends ${propType.fullClassName()}>> builder) { | this.$propertyName = builder.apply(${propType.fullClassName()}Builder.of()).build(); | return this; |} """ else ""} """.trimMargin() } } private fun ObjectType.getters() : String { return this.allProperties .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .map { it.getter() } .joinToString(separator = "\n\n") } private fun Property.getter() : String { val propertyType = this.type; val vrapType = this.type.toVrapType() return if(this.isPatternProperty()){ """ |/** |${propertyType.toComment(" * values of pattern properties")} | * @return pattern properties | */ |${this.deprecationAnnotation()} |${if(!this.required) "@Nullable" else ""} |public Map<String, ${vrapType.fullClassName()}> getValues(){ | return this.values; |} """.escapeAll().trimMargin().keepIndentation() } else if(this.name.equals("interface")) { """ |/** |${propertyType.toComment(" * value of interface")} | * @return interface | */ | |${this.deprecationAnnotation()} |${if (!this.required) "@Nullable" else ""} |public ${vrapType.fullClassName()} getInterface(){ | return this._interface; |} """.escapeAll().trimMargin().keepIndentation() }else{ """ |/** |${propertyType.toComment(" * value of ${this.name}}")} | * @return ${this.name} | */ |${this.deprecationAnnotation()} |${if(!this.required) "@Nullable" else ""} |public ${vrapType.fullClassName()} get${this.name.firstUpperCase()}(){ | return this.${this.name}; |} """.escapeAll().trimMargin().keepIndentation() } } private fun ObjectType.requiredChecks() : String { val vrapType = vrapTypeProvider.doSwitch(this).toJavaVType() as VrapObjectType return this.allProperties .asSequence() .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .filterNot { it.isPatternProperty() } .filter { it.required } .map { if(it.name.equals("interface")) { "Objects.requireNonNull(_interface, ${vrapType.simpleClassName}.class + \": interface is missing\");" } else { "Objects.requireNonNull(${it.name}, ${vrapType.simpleClassName}.class + \": ${it.name} is missing\");" } } .joinToString(separator = "\n") } private fun ObjectType.buildMethodBody() : String { val vrapType = vrapTypeProvider.doSwitch(this).toJavaVType() as VrapObjectType val constructorArguments = this.allProperties .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .joinToString(separator = ", ") { if (it.isPatternProperty()) { "values" } else if (it.name.equals("interface")) { "_interface" } else { it.name } } return "return new ${vrapType.simpleClassName}Impl($constructorArguments);" } private fun ObjectType.staticOfMethod() : String { val vrapType = vrapTypeProvider.doSwitch(this).toJavaVType() as VrapObjectType return """ |/** | * factory method for an instance of ${vrapType.simpleClassName}Builder | * @return builder | */ |public static ${vrapType.simpleClassName}Builder of() { | return new ${vrapType.simpleClassName}Builder(); |} """.trimMargin().keepIndentation() } private fun ObjectType.templateMethod(): String { val vrapType = vrapTypeProvider.doSwitch(this).toJavaVType() as VrapObjectType val fieldsAssignment : String = this.allProperties .filterNot { it.deprecated() } .filter { it.name != this.discriminator() } .joinToString(separator = "\n") { if (it.isPatternProperty()) { "builder.values = template.values();" } else if (it.name.equals("interface")) { "builder._interface = template.getInterface();" } else { "builder.${it.name} = template.get${it.name.upperCamelCase()}();" } } return """ |/** | * create builder for ${vrapType.simpleClassName} instance | * @param template instance with prefilled values for the builder | * @return builder | */ |public static ${vrapType.simpleClassName}Builder of(final ${vrapType.simpleClassName} template) { | ${vrapType.simpleClassName}Builder builder = new ${vrapType.simpleClassName}Builder(); | <$fieldsAssignment> | return builder; |} """.escapeAll().trimMargin().keepIndentation() } private fun ObjectType.markDeprecated() : Boolean { val anno = this.getAnnotation("markDeprecated") return (anno != null && (anno.value as BooleanInstance).value) } private fun ObjectType.deprecated() : Boolean { val anno = this.getAnnotation("deprecated") return (anno != null && (anno.value as BooleanInstance).value) } }
23
Kotlin
6
14
2f8846e5dee3ced5f00613e2f6a382e5d818be4d
26,500
rmf-codegen
Apache License 2.0
app/src/main/java/com/mozhimen/app/abilityk/opencvk/OpenCVKMatchActivity.kt
mozhimen
353,952,154
false
null
package com.mozhimen.app.abilityk.opencvk import android.Manifest import android.annotation.SuppressLint import android.graphics.Bitmap import android.graphics.ImageFormat import android.os.Bundle import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.mozhimen.abilityk.cameraxk.annors.CameraXKFacing import com.mozhimen.abilityk.cameraxk.helpers.ImageConverter import com.mozhimen.abilityk.opencvk.OpenCVKMatch import com.mozhimen.abilityk.opencvk.OpenCVKTrans import com.mozhimen.abilityk.opencvk.setMat import com.mozhimen.app.R import com.mozhimen.app.databinding.ActivityOpencvkMatchBinding import com.mozhimen.basick.basek.BaseKActivity import com.mozhimen.basick.basek.BaseKViewModel import com.mozhimen.basick.extsk.cropBitmap import com.mozhimen.basick.extsk.drawable2Bitmap import com.mozhimen.basick.utilk.UtilKBitmap import com.mozhimen.basick.utilk.UtilKRes import com.mozhimen.basick.utilk.UtilKScreen import com.mozhimen.componentk.permissionk.PermissionK import com.mozhimen.componentk.permissionk.annors.PermissionKAnnor import com.mozhimen.opencvk.OpenCVK import java.util.concurrent.locks.ReentrantLock @PermissionKAnnor(permissions = [Manifest.permission.CAMERA]) class OpenCVKMatchActivity : BaseKActivity<ActivityOpencvkMatchBinding, BaseKViewModel>(R.layout.activity_opencvk_match) { private val _templateMat by lazy { OpenCVKTrans.bitmap2Mat(UtilKRes.getDrawable(R.mipmap.opencvk_contrast_test)!!.drawable2Bitmap()) } override fun initData(savedInstanceState: Bundle?) { PermissionK.initPermissions(this) { if (it) { initView(savedInstanceState) } else { PermissionK.applySetting(this) } } } override fun initView(savedInstanceState: Bundle?) { require(OpenCVK.initSDK()) { "opencv init fail" } initCamera() } private fun initCamera() { vb.opencvkMatchPreview.initCamera(this, CameraXKFacing.BACK) vb.opencvkMatchPreview.setImageAnalyzer(_frameAnalyzer) vb.opencvkMatchPreview.startCamera() } private val _frameAnalyzer: ImageAnalysis.Analyzer by lazy { object : ImageAnalysis.Analyzer { private val _reentrantLock = ReentrantLock() @SuppressLint("UnsafeOptInUsageError") override fun analyze(image: ImageProxy) { try { _reentrantLock.lock() val bitmap: Bitmap = if (image.format == ImageFormat.YUV_420_888) { ImageConverter.yuv2Bitmap(image)!! } else { ImageConverter.jpeg2Bitmap(image) } val rotateBitmap = UtilKBitmap.rotateBitmap(bitmap, 90) val ratio: Double = vb.opencvkMatchQrscan.getRectSize().toDouble() / UtilKScreen.getScreenWidth().toDouble() val cropBitmap = rotateBitmap.cropBitmap( (ratio * rotateBitmap.width).toInt(), (ratio * rotateBitmap.width).toInt(), ((1 - ratio) * rotateBitmap.width / 2).toInt(), ((rotateBitmap.height - ratio * rotateBitmap.width) / 2).toInt() ) val srcMat = OpenCVKTrans.bitmap2Mat(cropBitmap) val resultMat = OpenCVKMatch.templateMatch(srcMat, _templateMat) Thread.sleep(100) try { vb.opencvkMatchImg.setMat(resultMat) } catch (e: Exception) { e.printStackTrace() } finally { srcMat.release() resultMat.release() } } finally { _reentrantLock.unlock() } image.close() } } } override fun onDestroy() { super.onDestroy() _templateMat.release() } }
0
Kotlin
0
1
3dd109aff154bff96379cde86e6e4632967cca40
4,100
SwiftMK
Apache License 2.0
ui-app/src/androidMain/kotlin/com/alexvanyo/composelife/ui/app/entrypoints/PreviewEntryPoint.kt
alexvanyo
375,146,193
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.alexvanyo.composelife.ui.app.entrypoints import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import app.cash.sqldelight.driver.android.AndroidSqliteDriver import com.alexvanyo.composelife.algorithm.GameOfLifeAlgorithm import com.alexvanyo.composelife.algorithm.NaiveGameOfLifeAlgorithm import com.alexvanyo.composelife.algorithm.di.GameOfLifeAlgorithmProvider import com.alexvanyo.composelife.clock.di.ClockProvider import com.alexvanyo.composelife.data.CellStateRepositoryImpl import com.alexvanyo.composelife.data.di.CellStateRepositoryProvider import com.alexvanyo.composelife.database.CellState import com.alexvanyo.composelife.database.CellStateIdAdapter import com.alexvanyo.composelife.database.ComposeLifeDatabase import com.alexvanyo.composelife.dispatchers.ComposeLifeDispatchers import com.alexvanyo.composelife.dispatchers.DefaultComposeLifeDispatchers import com.alexvanyo.composelife.dispatchers.di.ComposeLifeDispatchersProvider import com.alexvanyo.composelife.model.FlexibleCellStateSerializer import com.alexvanyo.composelife.preferences.ComposeLifePreferences import com.alexvanyo.composelife.preferences.CurrentShape import com.alexvanyo.composelife.preferences.LoadedComposeLifePreferences import com.alexvanyo.composelife.preferences.TestComposeLifePreferences import com.alexvanyo.composelife.preferences.di.ComposeLifePreferencesProvider import com.alexvanyo.composelife.preferences.di.LoadedComposeLifePreferencesProvider import com.alexvanyo.composelife.random.di.RandomProvider import com.alexvanyo.composelife.ui.app.ComposeLifeAppInjectEntryPoint import com.alexvanyo.composelife.ui.app.InteractiveCellUniverseInjectEntryPoint import com.alexvanyo.composelife.ui.app.InteractiveCellUniverseLocalEntryPoint import com.alexvanyo.composelife.ui.app.InteractiveCellUniverseOverlayInjectEntryPoint import com.alexvanyo.composelife.ui.app.InteractiveCellUniverseOverlayLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.CellUniverseActionCardInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.AlgorithmImplementationUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.AlgorithmImplementationUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.CellShapeConfigUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.CellShapeConfigUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.CellStatePreviewUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DarkThemeConfigUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DarkThemeConfigUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DisableAGSLUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DisableAGSLUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DisableOpenGLUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.DisableOpenGLUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.FullscreenSettingsScreenInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.FullscreenSettingsScreenLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.InlineSettingsScreenInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.InlineSettingsScreenLocalEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.SettingUiInjectEntryPoint import com.alexvanyo.composelife.ui.app.action.settings.SettingUiLocalEntryPoint import com.alexvanyo.composelife.ui.app.cells.CellWindowLocalEntryPoint import com.alexvanyo.composelife.ui.app.cells.InteractableCellsLocalEntryPoint import com.alexvanyo.composelife.ui.app.cells.NonInteractableCellsLocalEntryPoint import com.alexvanyo.composelife.ui.app.component.GameOfLifeProgressIndicatorInjectEntryPoint import com.alexvanyo.composelife.ui.app.component.GameOfLifeProgressIndicatorLocalEntryPoint import kotlinx.datetime.Clock import kotlin.random.Random /** * The full super-interface implementing all entry points for rendering * previews in this module. */ internal interface PreviewEntryPoint : AlgorithmImplementationUiInjectEntryPoint, AlgorithmImplementationUiLocalEntryPoint, CellShapeConfigUiInjectEntryPoint, CellShapeConfigUiLocalEntryPoint, CellStatePreviewUiLocalEntryPoint, CellWindowLocalEntryPoint, CellUniverseActionCardInjectEntryPoint, ComposeLifeAppInjectEntryPoint, DarkThemeConfigUiInjectEntryPoint, DarkThemeConfigUiLocalEntryPoint, DisableAGSLUiInjectEntryPoint, DisableAGSLUiLocalEntryPoint, DisableOpenGLUiInjectEntryPoint, DisableOpenGLUiLocalEntryPoint, FullscreenSettingsScreenInjectEntryPoint, FullscreenSettingsScreenLocalEntryPoint, GameOfLifeProgressIndicatorInjectEntryPoint, GameOfLifeProgressIndicatorLocalEntryPoint, InlineSettingsScreenInjectEntryPoint, InlineSettingsScreenLocalEntryPoint, InteractableCellsLocalEntryPoint, InteractiveCellUniverseInjectEntryPoint, InteractiveCellUniverseLocalEntryPoint, InteractiveCellUniverseOverlayInjectEntryPoint, InteractiveCellUniverseOverlayLocalEntryPoint, NonInteractableCellsLocalEntryPoint, SettingUiInjectEntryPoint, SettingUiLocalEntryPoint /** * Provides fake implementations for the entry points passed to [content] as context receivers. * * This is useful for providing dependencies to previews where the full dependency graph isn't available. */ @Suppress("LongParameterList") @Composable internal fun WithPreviewDependencies( dispatchers: ComposeLifeDispatchers = DefaultComposeLifeDispatchers(), gameOfLifeAlgorithm: GameOfLifeAlgorithm = NaiveGameOfLifeAlgorithm(dispatchers), loadedComposeLifePreferences: LoadedComposeLifePreferences = LoadedComposeLifePreferences.Defaults, composeLifePreferences: ComposeLifePreferences = TestComposeLifePreferences.Loaded( algorithmChoice = loadedComposeLifePreferences.algorithmChoice, currentShapeType = loadedComposeLifePreferences.currentShape.type, roundRectangleConfig = when (loadedComposeLifePreferences.currentShape) { is CurrentShape.RoundRectangle -> loadedComposeLifePreferences.currentShape as CurrentShape.RoundRectangle }, darkThemeConfig = loadedComposeLifePreferences.darkThemeConfig, disableAGSL = loadedComposeLifePreferences.disableAGSL, disableOpenGL = loadedComposeLifePreferences.disableOpenGL, ), random: Random = Random(1), clock: Clock = Clock.System, content: @Composable context(PreviewEntryPoint) () -> Unit, ) { val driver = AndroidSqliteDriver( schema = ComposeLifeDatabase.Schema, context = LocalContext.current, name = null, ) val composeLifeDatabase = ComposeLifeDatabase( driver = driver, cellStateAdapter = CellState.Adapter( idAdapter = CellStateIdAdapter(), ), ) val cellStateQueries = composeLifeDatabase.cellStateQueries val dispatchersProvider = object : ComposeLifeDispatchersProvider { override val dispatchers = dispatchers } val algorithmProvider = object : GameOfLifeAlgorithmProvider { override val gameOfLifeAlgorithm = gameOfLifeAlgorithm } val preferencesProvider = object : ComposeLifePreferencesProvider { override val composeLifePreferences = composeLifePreferences } val cellStateRepositoryProvider = object : CellStateRepositoryProvider { override val cellStateRepository = CellStateRepositoryImpl( flexibleCellStateSerializer = FlexibleCellStateSerializer(dispatchers), cellStateQueries = cellStateQueries, dispatchers = dispatchers, ) } val loadedPreferencesProvider = object : LoadedComposeLifePreferencesProvider { override val preferences: LoadedComposeLifePreferences = loadedComposeLifePreferences } val randomProvider = object : RandomProvider { override val random = random } val clockProvider = object : ClockProvider { override val clock = clock } val entryPoint = object : PreviewEntryPoint, ComposeLifeDispatchersProvider by dispatchersProvider, GameOfLifeAlgorithmProvider by algorithmProvider, ComposeLifePreferencesProvider by preferencesProvider, CellStateRepositoryProvider by cellStateRepositoryProvider, LoadedComposeLifePreferencesProvider by loadedPreferencesProvider, RandomProvider by randomProvider, ClockProvider by clockProvider {} content(entryPoint) }
37
null
7
99
64595b8d36c559a70ca52d578069fe4df8d170c7
9,318
composelife
Apache License 2.0
src/main/kotlin/io/groax/impl/webhook/WebhookUtil.kt
Wenaly
487,277,543
false
null
package io.groax.impl.webhook import io.groax.api.webhook.* import java.io.IOException import java.net.URL import javax.net.ssl.HttpsURLConnection class WebhookUtil(private val url: String) { private var content: String? = null private var username: String? = null private var avatarUrl: String? = null private var tts = false private val embeds: MutableList<EmbedObject> = ArrayList() fun setContent(content: String?) { this.content = content } fun setUsername(username: String?) { this.username = username } fun setAvatarUrl(avatarUrl: String?) { this.avatarUrl = avatarUrl } fun setTts(tts: Boolean) { this.tts = tts } fun addEmbed(embed: EmbedObject) { embeds.add(embed) } @Throws(IOException::class) fun execute() { if (content == null && embeds.isEmpty()) { throw IllegalArgumentException("Set content or add at least one EmbedObject") } val json = JSONObject() json.put("content", content) json.put("username", username) json.put("avatar_url", avatarUrl) json.put("tts", tts) if (!embeds.isEmpty()) { val embedObjects: MutableList<JSONObject> = ArrayList() for (embed: EmbedObject in embeds) { val jsonEmbed = JSONObject() jsonEmbed.put("title", embed.title) jsonEmbed.put("description", embed.description) jsonEmbed.put("url", embed.url) if (embed.color != null) { val color = embed.color var rgb = color!!.red rgb = (rgb shl 8) + color.green rgb = (rgb shl 8) + color.blue jsonEmbed.put("color", rgb) } val footer: Footer? = embed.footer val image = embed.image val thumbnail: Thumbnail? = embed.thumbnail val author: Author? = embed.author val fields = embed.fields if (footer != null) { val jsonFooter = JSONObject() jsonFooter.put("text", footer.text) jsonFooter.put("icon_url", footer.iconUrl) jsonEmbed.put("footer", jsonFooter) } if (image != null) { val jsonImage = JSONObject() jsonImage.put("url", image.url) jsonEmbed.put("image", jsonImage) } if (thumbnail != null) { val jsonThumbnail = JSONObject() jsonThumbnail.put("url", thumbnail.url) jsonEmbed.put("thumbnail", jsonThumbnail) } if (author != null) { val jsonAuthor = JSONObject() jsonAuthor.put("name", author.name) jsonAuthor.put("url", author.url) jsonAuthor.put("icon_url", author.iconUrl) jsonEmbed.put("author", jsonAuthor) } val jsonFields: MutableList<JSONObject> = ArrayList() for (field: Field in fields) { val jsonField = JSONObject() jsonField.put("name", field.name) jsonField.put("value", field.value) jsonField.put("inline", field.isInline) jsonFields.add(jsonField) } jsonEmbed.put("fields", jsonFields.toTypedArray()) embedObjects.add(jsonEmbed) } json.put("embeds", embedObjects.toTypedArray()) } val url = URL(url) val connection = url.openConnection() as HttpsURLConnection connection.addRequestProperty("Content-Type", "application/json") connection.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_") connection.doOutput = true connection.requestMethod = "POST" val stream = connection.outputStream stream.write(json.toString().toByteArray()) stream.flush() stream.close() connection.inputStream.close() connection.disconnect() } }
0
null
0
0
489f9c4164bd891828b431b18f1cca69f19eb9b9
4,274
Project1022
MIT License
app/src/main/java/com/karna/mycards/presentation/login_with_pin/LoginWithPinScreen.kt
karnasurendra
794,693,409
false
{"Kotlin": 85804}
package com.karna.mycards.presentation.login_with_pin import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column 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.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.karna.mycards.R import com.karna.mycards.presentation.add_edit_card.components.CommonOnlyNumberTextField import com.karna.mycards.presentation.add_edit_card.components.CommonTextField import com.karna.mycards.presentation.set_pin.SetPinEvent import com.karna.mycards.presentation.set_pin.SetPinViewModel import com.karna.mycards.presentation.util.Screen import kotlinx.coroutines.flow.collectLatest @Composable fun LoginWithPinScreen( navController: NavController, viewModel: LoginWithPinViewModel = hiltViewModel() ) { val pinState = viewModel.pin.value val snackBarHostState = remember { SnackbarHostState() } LaunchedEffect(key1 = true) { viewModel.eventFlow.collectLatest { event -> when (event) { is LoginWithPinViewModel.UIEvent.Login -> { // OnSuccess Take to Cards List screen navController.navigate(Screen.CardsScreen.route){ popUpTo(0) { inclusive = true } } } is LoginWithPinViewModel.UIEvent.ShowSnackBar -> { snackBarHostState.showSnackbar(event.message) } } } } Scaffold( modifier = Modifier .fillMaxSize(), floatingActionButton = { FloatingActionButton( onClick = { // Login PIN viewModel.onEvent(LoginWithPinEvent.DoLogin) }, containerColor = MaterialTheme.colorScheme.primary ) { Icon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = "Next" ) } }, snackbarHost = { SnackbarHost(hostState = snackBarHostState) }) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .background( brush = Brush.verticalGradient( colors = listOf( MaterialTheme.colorScheme.primaryContainer, MaterialTheme.colorScheme.secondaryContainer ) ) ) .padding(paddingValues) .padding(start = 15.dp, end = 15.dp, bottom = 30.dp) ) { Spacer(modifier = Modifier.height(30.dp)) Text( text = stringResource(id = R.string.login_with_pin), style = MaterialTheme.typography.titleLarge ) Spacer(modifier = Modifier.height(30.dp)) CommonOnlyNumberTextField( modifier = Modifier.fillMaxWidth(), text = pinState.text, hint = pinState.hint, onValueChange = { viewModel.onEvent(LoginWithPinEvent.OnPinEntered(it)) }, singleLine = true, maxLength = 4, textStyle = MaterialTheme.typography.labelMedium, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions() ) } } }
0
Kotlin
0
1
4f5af198217c5c09e5c3728144de028da6025072
4,910
Android-Compose-MVVM-MyCards
MIT License
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/window/DialogScreenshotTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import android.os.Build import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.preferredSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.GOLDEN_UI import androidx.compose.ui.Modifier import androidx.compose.ui.background import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.AmbientDensity import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class DialogScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_UI) @Test fun dialogWithNoElevation() { rule.setContent { Dialog(onDismissRequest = {}) { Box( Modifier .graphicsLayer(shape = RoundedCornerShape(percent = 15), clip = true) .preferredSize(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden(screenshotRule, "dialogWithNoElevation") } @Test fun dialogWithElevation() { rule.setContent { Dialog(onDismissRequest = {}) { val elevation = with(AmbientDensity.current) { 16.dp.toPx() } Box( Modifier .graphicsLayer( shadowElevation = elevation, shape = RoundedCornerShape(percent = 15), clip = true ) .preferredSize(200.dp) .background(Color(0xFFA896B0)) ) } } rule.onNode(isDialog()) .captureToImage() .assertAgainstGolden(screenshotRule, "dialogWithElevation") } }
29
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,153
androidx
Apache License 2.0
src/main/kotlin/org/ktlib/Application.kt
ktlib-org
713,606,396
false
{"Kotlin": 102035}
package org.ktlib import io.github.oshai.kotlinlogging.KotlinLogging /** * This is the entry point for an application. * * Usually it's called from the main function like this: * ``` * fun main() = Application { * // Additional app initialization done here * } * ``` * * These configuration properties can be set: * - applicationName the name of the application */ object Application { private val initStart = System.currentTimeMillis() val name: String init { Environment.init() BootstrapRunner.init() name = config("applicationName", "") } operator fun invoke(init: () -> Any? = {}) { val logger = KotlinLogging.logger {} init() logger.info { "Application initialized in ${nowMillis() - initStart}ms" } } }
0
Kotlin
0
0
e09e0d6fd4af839cebfd1313cfd9c68c43eaf189
801
core
Apache License 2.0
app/src/main/java/com/siddapps/android/todo/ui/homepage/HomepagePresenterImpl.kt
hasansidd
113,695,435
false
null
package com.siddapps.android.todo.ui.homepage import com.siddapps.android.todo.model.repository.TaskRepository import javax.inject.Inject class HomepagePresenterImpl @Inject constructor(private val taskRepository: TaskRepository) : HomepagePresenter { private lateinit var homepageView: HomepageView override fun setView(homepageView: HomepageView) { this.homepageView = homepageView } }
0
Kotlin
1
0
5b6ec46e84c5e8efdb3a6f55f399a080b9a06317
411
ToDo
MIT License
app/src/main/java/com/example/formapp/domain/use_cases/Login/LoginUseCase.kt
fgarridofi
743,682,977
false
{"Kotlin": 224638, "JavaScript": 7398}
package com.example.formapp.domain.use_cases.Login import com.example.formapp.data.Result import com.example.formapp.domain.model.LoginModel2 import com.example.formapp.domain.repository.UserRepository import javax.inject.Inject class LoginUseCase @Inject constructor( private val repository: UserRepository) { suspend operator fun invoke( email: String, password: String): Result<Unit> { val loginModel2 = LoginModel2(email, password) return repository.authenticateUser(loginModel2) } }
0
Kotlin
0
1
9cfd8de17550e60b8776f8200e93362b024cedc2
515
car-navigation-mobile-app
MIT License
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/data/managers/connection/ConnectionEventManager.kt
sceyt
549,073,085
false
{"Kotlin": 2361738, "Java": 107894}
package com.sceyt.chatuikit.data.managers.connection import com.sceyt.chat.ChatClient import com.sceyt.chat.models.ConnectionState import com.sceyt.chat.models.SceytException import com.sceyt.chat.sceyt_listeners.ClientListener import com.sceyt.chat.wrapper.ClientWrapper import com.sceyt.chatuikit.data.managers.connection.event.ConnectionStateData import com.sceyt.chatuikit.extensions.TAG import com.sceyt.chatuikit.persistence.extensions.safeResume import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine object ConnectionEventManager { val connectionState get() = ClientWrapper.getConnectionState() ?: ConnectionState.Disconnected val isConnected get() = connectionState == ConnectionState.Connected private val onChangedConnectStatusFlow_: MutableSharedFlow<ConnectionStateData> = MutableSharedFlow( extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) val onChangedConnectStatusFlow = onChangedConnectStatusFlow_.asSharedFlow() private val onTokenWillExpire_: MutableSharedFlow<Long> = MutableSharedFlow( extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) val onTokenWillExpire = onTokenWillExpire_.asSharedFlow() private val onTokenExpired_: MutableSharedFlow<Unit> = MutableSharedFlow( extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) val onTokenExpired = onTokenExpired_.asSharedFlow() init { ChatClient.getClient().addClientListener(TAG, object : ClientListener { override fun onConnectionStateChanged(state: ConnectionState?, exception: SceytException?) { onChangedConnectStatusFlow_.tryEmit(ConnectionStateData(state, exception)) } override fun onTokenWillExpire(expireTime: Long) { onTokenWillExpire_.tryEmit(expireTime) } override fun onTokenExpired() { onTokenExpired_.tryEmit(Unit) } }) } suspend fun awaitToConnectSceyt(): Boolean { if (isConnected) return true onChangedConnectStatusFlow.firstOrNull { it.state == ConnectionState.Connected } return connectionState == ConnectionState.Connected } suspend fun awaitToConnectSceytWithTimeout(timeout: Long): Boolean { if (isConnected) return true val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) return suspendCancellableCoroutine { continuation -> onChangedConnectStatusFlow .onSubscription { scope.launch { delay(timeout) continuation.safeResume(isConnected) scope.cancel() } } .onEach { if (it.state == ConnectionState.Connected) { continuation.safeResume(true) scope.cancel() } }.launchIn(scope) } } }
1
Kotlin
1
2
aa03d3d9f046243cd1bbb98bd5e9d5abcfeae822
3,579
sceyt-chat-android-uikit
MIT License
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/api/tweets/UserTimeline.kt
MeilCli
51,423,644
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 3, "XML": 22, "Kotlin": 303, "Checksums": 6}
package com.twitter.meil_mitu.twitter4hk.aclog.api.tweets import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.aclog.AbsAclogGet import com.twitter.meil_mitu.twitter4hk.aclog.converter.IAclogStatusConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import java.util.* class UserFavorites<TAclogStatus>( oauth: AbsOauth, protected val json: IAclogStatusConverter<TAclogStatus>) : AbsAclogGet<ArrayList<TAclogStatus>>(oauth) { var authorization: Boolean = false override val isAuthorization = authorization var userId: Long? by longParam("user_id") var screenName: String? by stringParam("screen_name") var count: Int? by intParam("count") var page: Int? by intParam("page") var reactions: Int? by intParam("reactions") override val url = "$host/api/tweets/user_favorites.json" override val allowOauthType = OauthType.oauthEcho @Throws(Twitter4HKException::class) override fun call(): ArrayList<TAclogStatus> { return json.toStatusList(oauth.get(this)) } }
0
Kotlin
0
0
818e42ea417c326e3d50024decce4c7e70641a73
1,153
Twitter4HK
MIT License
src/main/kotlin/dev/cbyrne/kdiscordipc/manager/impl/VoiceSettingsManager.kt
caoimhebyrne
379,862,700
false
{"Kotlin": 61658}
package dev.cbyrne.kdiscordipc.manager.impl import dev.cbyrne.kdiscordipc.KDiscordIPC import dev.cbyrne.kdiscordipc.core.event.DiscordEvent import dev.cbyrne.kdiscordipc.core.event.impl.VoiceSettingsUpdateEvent import dev.cbyrne.kdiscordipc.core.packet.outbound.impl.GetVoiceSettingsPacket import dev.cbyrne.kdiscordipc.core.packet.outbound.impl.SetVoiceSettingsPacket import dev.cbyrne.kdiscordipc.data.voiceSettings.VoiceSettings import dev.cbyrne.kdiscordipc.manager.Manager import dev.cbyrne.kdiscordipc.core.packet.inbound.impl.GetVoiceSettingsPacket as InboundGetVoiceSettingsPacket import dev.cbyrne.kdiscordipc.core.packet.inbound.impl.SetVoiceSettingsPacket as InboundSetVoiceSettingsPacket class VoiceSettingsManager(override val ipc: KDiscordIPC) : Manager() { var currentVoiceSettings: VoiceSettings? = null private set override suspend fun init() { ipc.on<VoiceSettingsUpdateEvent> { currentVoiceSettings = this.data } } suspend fun getVoiceSettings(): VoiceSettings { val response: InboundGetVoiceSettingsPacket = ipc.sendPacket(GetVoiceSettingsPacket()) return response.data } suspend fun setVoiceSettings(settings: SetVoiceSettingsPacket.VoiceSettingArguments) { ipc.sendPacket<InboundSetVoiceSettingsPacket>(SetVoiceSettingsPacket(args = settings)) } suspend fun subscribeToVoiceSettingsUpdate() = ipc.subscribe(DiscordEvent.VoiceSettingsUpdate) }
2
Kotlin
8
37
b136b267d146544c49d80b4c9a046d66324a601b
1,462
KDiscordIPC
MIT License
kraftverk-core/src/main/kotlin/io/kraftverk/core/binding/Bindings.kt
jogro
211,348,610
false
null
/* * Copyright 2019 <NAME> * Licensed under MIT: https://github.com/jogro/kraftverk/blob/master/LICENSE */ package io.kraftverk.core.binding import io.kraftverk.core.internal.binding.BeanDelegate import io.kraftverk.core.internal.binding.BindingDelegate import io.kraftverk.core.internal.binding.ValueDelegate /** * A Bean is a [Binding] that can be declared within a Kraftverk managed module. * * The primary purpose of a Bean is to serve as a configurable factory that produces injectable singleton * instances of type [T]. * * A Bean is basically a wrapper around a lambda expression of type () -> T. This lambda is guaranteed to * be run only ONCE, thus supplying a singleton instance. The lambda can only be called upon in the context of a * [BeanDeclaration][io.kraftverk.core.declaration.BeanDeclaration] by invoking the bean as a function * (operator invoke extension). * * See the [bean][io.kraftverk.core.module.Module.bean] method on how to declare a Bean. */ sealed class Bean<out T : Any> : Binding<T>() { companion object } /** * A Value is a [Binding] that can be declared within a Kraftverk managed module. * * Values provide access to properties and environment variables that have been defined within the * [environment][io.kraftverk.core.env.Environment]. * * The following methods can be used to declare a Value. * - [value][io.kraftverk.core.module.Module.value] * - [string][io.kraftverk.core.module.string] * - [int][io.kraftverk.core.module.int] * - [long][io.kraftverk.core.module.long], * - [boolean][io.kraftverk.core.module.boolean] * - [port][io.kraftverk.core.module.port]. */ sealed class Value<out T : Any> : Binding<T>() { companion object } /** * A Binding is a [Bean] or [Value]. */ sealed class Binding<out T : Any> /* Internals */ internal class BeanImpl<T : Any>(val delegate: BeanDelegate<T>) : Bean<T>() internal class ValueImpl<T : Any>(val delegate: ValueDelegate<T>) : Value<T>() internal val <T : Any> Bean<T>.delegate: BeanDelegate<T> get() = when (this) { is BeanImpl<T> -> delegate } internal val <T : Any> Value<T>.delegate: ValueDelegate<T> get() = when (this) { is ValueImpl<T> -> delegate } internal val <T : Any> Binding<T>.delegate: BindingDelegate<T> get() = when (this) { is ValueImpl<T> -> delegate is BeanImpl<T> -> delegate }
0
Kotlin
0
2
66a2cb9254f2fe83a845e384c75e7a87a100b7a5
2,401
kraftverk
MIT License
app/src/main/kotlin/it/vfsfitvnm/vimusic/service/PlaybackExceptions.kt
Sagnik0684
861,208,877
false
{"Kotlin": 713513}
package it.vfsfitvnm.vimusic.service import androidx.media3.common.PlaybackException class PlayableFormatNotFoundException : PlaybackException(null, null, ERROR_CODE_REMOTE_ERROR) class UnplayableException : PlaybackException(null, null, ERROR_CODE_REMOTE_ERROR) class LoginRequiredException : PlaybackException(null, null, ERROR_CODE_REMOTE_ERROR) class VideoIdMismatchException : PlaybackException(null, null, ERROR_CODE_REMOTE_ERROR)
0
Kotlin
0
0
d068ae496559b4f7cc7152e38de3483a12b0b8f0
442
BuzzVibe
MIT License
app/src/main/java/com/example/sook/fragment/Sook9Fragment.kt
foodinsect
801,560,790
false
{"Kotlin": 49165}
package com.example.sook.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.sook.PageChangeCallback import com.example.sook.databinding.ActivitySook9Binding class Sook9Fragment : Fragment() { private var binding: ActivitySook9Binding? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = ActivitySook9Binding.inflate(inflater, container, false) val view = binding!!.root // 홈 화면 전환 버튼 binding!!.home.setOnClickListener { (activity as? PageChangeCallback)?.changePage(0) // sookActivity5로 이동 } // 상품특가 화면 전환 버튼 binding!!.event.setOnClickListener { (activity as? PageChangeCallback)?.changePage(1) // sookActivity6로 이동 } // 식단 화면 전환 버튼 binding!!.food.setOnClickListener { (activity as? PageChangeCallback)?.changePage(2) // sookActivity7로 이동 } // 커뮤니티 화면 전환 버튼 binding!!.pt.setOnClickListener { (activity as? PageChangeCallback)?.changePage(5) // sookActivity10으로 이동 } // 키즈존 화면 전환 버튼 binding!!.kidzone.setOnClickListener { (activity as? PageChangeCallback)?.changePage(6) // sookActivity11로 이동 } // 탭바 홈 화면 전환 버튼 binding!!.taphome.setOnClickListener { (activity as? PageChangeCallback)?.changePage(0) // sookActivity5로 이동 } binding!!.taphome1.setOnClickListener { (activity as? PageChangeCallback)?.changePage(0) // sookActivity5로 이동 } binding!!.tapevent.setOnClickListener { (activity as? PageChangeCallback)?.changePage(1) // sookActivity5로 이동 } binding!!.tapevent1.setOnClickListener { (activity as? PageChangeCallback)?.changePage(1) // sookActivity5로 이동 } // 탭바 식단 화면 전환 버튼 binding!!.tapfood.setOnClickListener { (activity as? PageChangeCallback)?.changePage(2) // sookActivity7로 이동 } binding!!.tapfood1.setOnClickListener { (activity as? PageChangeCallback)?.changePage(2) // sookActivity7로 이동 } // 탭바 커뮤니티 화면 전환 버튼 binding!!.tappt.setOnClickListener { (activity as? PageChangeCallback)?.changePage(5) // sookActivity10으로 이동 } binding!!.tappt1.setOnClickListener { (activity as? PageChangeCallback)?.changePage(5) // sookActivity10으로 이동 } return view } override fun onDestroyView() { super.onDestroyView() binding = null } }
0
Kotlin
0
0
f705736e9dec890e1cab591f4987ed8c9ecc1a39
2,766
Android-App-prontend
MIT License
UsingPocketSphinxForVoiceRecognition/app/src/main/java/github/nisrulz/example/usingpocketsphinxforvoicerecognition/GoogleRecognitionListener.kt
nisrulz
52,518,462
false
null
package github.nisrulz.example.usingpocketsphinxforvoicerecognition import android.os.Bundle import android.speech.RecognitionListener import android.speech.SpeechRecognizer import android.util.Log import edu.cmu.pocketsphinx.SpeechRecognizer as PocketSpeechRecognizer class GoogleRecognitionListener( private val pocketSphinxRecognizer: PocketSpeechRecognizer, private val onResultListener: OnResultListener, private val searchKeyword: String, ) : RecognitionListener { private val TAG = GoogleRecognitionListener::class.java.simpleName override fun onBeginningOfSpeech() {} override fun onEndOfSpeech() {} override fun onReadyForSpeech(params: Bundle) {} override fun onRmsChanged(rmsdB: Float) {} override fun onBufferReceived(buffer: ByteArray) {} override fun onError(error: Int) { Log.e(TAG, "onError:$error") pocketSphinxRecognizer.startListening(searchKeyword) } override fun onPartialResults(partialResults: Bundle) {} override fun onResults(results: Bundle) { if (results.containsKey(SpeechRecognizer.RESULTS_RECOGNITION)) { val heard = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) ?: arrayListOf() val scores = results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES) for (i in heard.indices) { val confidence = scores?.get(i) ?: 0f val onResultHeardWord = heard[i] Log.d(TAG, "onResultHeard: $onResultHeardWord confidence: $confidence") } //send list of words to activity onResultListener.onResult(heard) } pocketSphinxRecognizer.startListening(searchKeyword) } override fun onEvent(eventType: Int, params: Bundle) {} }
7
null
668
1,738
3ca3cffbfc1d1f8e64681ff8b16269884aa4bc00
1,795
android-examples
Apache License 2.0
adt-ui/src/main/java/com/android/tools/adtui/validation/validators/PositiveIntegerValidator.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.adtui.validation.validators import com.android.tools.adtui.validation.Validator /** * A validator that returns valid when the integer value it is testing against is positive. * Note that 0 is not a positive integer. */ class PositiveIntegerValidator @JvmOverloads constructor(severity: Validator.Severity = Validator.Severity.ERROR, message: String) : Validator<Int> { private val invalidResult = Validator.Result(severity, message) override fun validate(value: Int): Validator.Result = if (value > 0) Validator.Result.OK else invalidResult }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,202
android
Apache License 2.0
goblin-transport-client/src/main/java/org/goblinframework/transport/client/channel/TransportClientState.kt
xiaohaiz
206,246,434
false
{"Java": 807217, "Kotlin": 650572, "FreeMarker": 27779, "JavaScript": 968}
package org.goblinframework.transport.client.channel enum class TransportClientState { CONNECTING, // 初始化状态 CONNECT_FAILED, // 建立连接失败,服务不可用或者建连超时 CONNECTED, // 已经完成了建连,但是还没有握手 HANDSHAKE_FAILED, // 握手失败 HANDSHAKED, // 握手成功,可用状态 DISCONNECTED, // 异常导致的连接中断 HEARTBEAT_LOST, // 心跳丢失 SHUTDOWN // 进入关闭阶段,不再接受新的状态变更 }
0
Java
6
9
b1db234912ceb23bdd81ac66a3bf61933b717d0b
397
goblinframework
Apache License 2.0
platform/projectModel-api/src/com/intellij/configurationStore/StreamProvider.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import org.jetbrains.annotations.ApiStatus.Internal import java.io.InputStream @Internal interface StreamProvider { /** * Whether it is enabled. */ val enabled: Boolean get() = true /** * Whether it is exclusive and cannot be used alongside another provider. * * Doesn't imply [enabled], callers should check [enabled] also if needed. */ val isExclusive: Boolean val saveStorageDataOnReload: Boolean get() = true /** * Called only on `write` */ fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean = true fun write(fileSpec: String, content: ByteArray, roamingType: RoamingType = RoamingType.DEFAULT) /** * `true` if provider is applicable for file. */ fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT, consumer: (InputStream?) -> Unit): Boolean /** * `true` if provider is fully responsible and local sources must be not used. */ fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean /** * Delete file or directory * * `true` if provider is fully responsible and local sources must be not used. */ fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean /** * Check whether the file shouldn't be stored anymore and delete it if it shouldn't. */ fun deleteIfObsolete(fileSpec: String, roamingType: RoamingType) { } fun getInstanceOf(aClass: Class<out StreamProvider>): StreamProvider = throw UnsupportedOperationException() } @Internal object DummyStreamProvider : StreamProvider { override val isExclusive: Boolean get() = true override fun write(fileSpec: String, content: ByteArray, roamingType: RoamingType) { } override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { return false } override fun processChildren( path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean, ): Boolean = true override fun delete(fileSpec: String, roamingType: RoamingType): Boolean = true }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
2,572
intellij-community
Apache License 2.0
app/src/main/kotlin/io/github/wykopmobilny/ui/modules/profile/ProfilePagerAdapter.kt
otwarty-wykop-mobilny
374,160,630
false
null
package io.github.wykopmobilny.ui.modules.profile import android.content.res.Resources import android.util.SparseArray import android.view.ViewGroup import androidx.fragment.app.Fragment import io.github.wykopmobilny.R import io.github.wykopmobilny.ui.modules.profile.actions.ActionsFragment import io.github.wykopmobilny.ui.modules.profile.links.LinksFragment import io.github.wykopmobilny.ui.modules.profile.microblog.MicroblogFragment import io.github.wykopmobilny.ui.settings.android.R as SettingsR class ProfilePagerAdapter( val resources: Resources, fragmentManager: androidx.fragment.app.FragmentManager, ) : androidx.fragment.app.FragmentPagerAdapter(fragmentManager) { val registeredFragments = SparseArray<Fragment>() override fun getItem(position: Int): Fragment = when (position) { 0 -> ActionsFragment.newInstance() 1 -> LinksFragment.newInstance() else -> MicroblogFragment.newInstance() } override fun getCount() = 3 override fun instantiateItem(container: ViewGroup, position: Int): Any { val fragment = super.instantiateItem(container, position) as Fragment registeredFragments.put(position, fragment) return fragment } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { registeredFragments.removeAt(position) super.destroyItem(container, position, `object`) } override fun getPageTitle(position: Int): CharSequence { super.getPageTitle(position) return when (position) { 0 -> resources.getString(R.string.actions) 1 -> resources.getString(R.string.links) else -> resources.getString(SettingsR.string.mikroblog) } } }
13
null
4
47
85b54b736f5fbcd6f62305779ed7ae2085c3b136
1,743
wykop-android
MIT License
tools/simulator/src/test/kotlin/io/libp2p/simulate/delay/AccurateBandwidthTest.kt
libp2p
189,293,403
false
null
package io.libp2p.simulate.delay import io.libp2p.core.pubsub.Topic import io.libp2p.simulate.Bandwidth import io.libp2p.simulate.delay.AccurateBandwidthTracker.Message import io.libp2p.simulate.gossip.* import io.libp2p.simulate.gossip.router.SimGossipRouterBuilder import io.libp2p.simulate.topology.AllToAllTopology import org.assertj.core.api.Assertions.assertThat import org.assertj.core.data.Offset import org.junit.jupiter.api.Test import kotlin.time.Duration.Companion.seconds class AccurateBandwidthTest { @Test fun testCalcDeliverTimes1() { val bandwidth = Bandwidth(1000) val msgs = listOf( Message(1000, 200_000), Message(1000, 200_000) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(202_000, Offset.offset(2)) assertThat(t[1]).isCloseTo(202_000, Offset.offset(2)) } @Test fun testCalcDeliverTimes2() { val bandwidth = Bandwidth(1000) val msgs = listOf( Message(1000, 200_000), Message(1000, 200_500) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(201_500, Offset.offset(2)) assertThat(t[1]).isCloseTo(202_000, Offset.offset(2)) } @Test fun testCalcDeliverTimes3() { val bandwidth = Bandwidth(1000) val msgs = listOf( Message(1000, 200_000), Message(50, 200_500) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(201_050, Offset.offset(2)) assertThat(t[1]).isCloseTo(200_600, Offset.offset(2)) } @Test fun testCalcDeliverTimes4() { val bandwidth = Bandwidth(1000) val msgs = listOf( Message(1000, 200_000), Message(1, 200_500) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(201_002, Offset.offset(2)) assertThat(t[1]).isCloseTo(200_502, Offset.offset(2)) } @Test fun testCalcDeliverTimes5() { val bandwidth = Bandwidth(1_000_000) val msgs = listOf( Message(1, 200_000), Message(1, 200_000) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(200_000, Offset.offset(2)) assertThat(t[1]).isCloseTo(200_000, Offset.offset(2)) } @Test fun testCalcDeliverTimes6() { val bandwidth = Bandwidth(1_000_000) val msgs = listOf( Message(1, 200_000), Message(1, 200_000), Message(1, 200_000), Message(1, 200_000), Message(1, 200_000) ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(200_000, Offset.offset(2)) assertThat(t[1]).isCloseTo(200_000, Offset.offset(2)) assertThat(t[2]).isCloseTo(200_000, Offset.offset(2)) assertThat(t[3]).isCloseTo(200_000, Offset.offset(2)) assertThat(t[4]).isCloseTo(200_000, Offset.offset(2)) } @Test fun testCalcDeliverTimes7() { val bandwidth = Bandwidth(1_000) val msgs = listOf( Message(1000, 200_000), Message(1000, 200_000), Message(1000, 201_900), Message(10, 202_900), ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(202_050, Offset.offset(2)) assertThat(t[1]).isCloseTo(202_050, Offset.offset(2)) assertThat(t[2]).isCloseTo(203_010, Offset.offset(2)) assertThat(t[3]).isCloseTo(202_920, Offset.offset(2)) } @Test fun testCalcDeliverTimes8() { val bandwidth = Bandwidth(1_000_000) val msgs = listOf( Message(924956, 70_000), Message(924956, 70_000), Message(924956, 70_000), Message(1130435, 72_774), ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(72_775, Offset.offset(2)) assertThat(t[1]).isCloseTo(72_775, Offset.offset(2)) assertThat(t[2]).isCloseTo(72_775, Offset.offset(2)) assertThat(t[3]).isCloseTo(73_905, Offset.offset(2)) } @Test fun testCalcDeliverTimes9() { val bandwidth = Bandwidth(1_000_000) val msgs = listOf( Message(900_000, 10_000), Message(900_000, 10_000), Message(1_100_000, 11_800), ) val t = AccurateBandwidthTracker.calcDeliverTimes(bandwidth, msgs) assertThat(t[0]).isCloseTo(11_800, Offset.offset(2)) assertThat(t[1]).isCloseTo(11_800, Offset.offset(2)) assertThat(t[2]).isCloseTo(12_900, Offset.offset(2)) } val topic = Topic("aaa") val simConfig = GossipSimConfig( totalPeers = 2, topics = listOf(topic), topology = AllToAllTopology(), ) val gossipParams = Eth2DefaultGossipParams val gossipScoreParams = Eth2DefaultScoreParams val gossipRouterCtor = { _: Int -> SimGossipRouterBuilder().also { it.params = gossipParams it.scoreParams = gossipScoreParams // it.serialize = true } } val simPeerModifier = { _: Int, _: GossipSimPeer -> // peer.pubsubLogs = { true } } val simNetwork = GossipSimNetwork(simConfig, gossipRouterCtor, simPeerModifier).also { println("Creating peers...") it.createAllPeers() } val peer0 = simNetwork.peers[0]!! val peer1 = simNetwork.peers[1]!! @Test fun `test smaller inbound bandwidth preserves sequential message delivery`() { peer0.outboundBandwidth = AccurateBandwidthTracker(Bandwidth(150000), peer0.simExecutor, peer0.currentTime, "[0]-out") peer1.inboundBandwidth = AccurateBandwidthTracker(Bandwidth(100000), peer1.simExecutor, peer1.currentTime, "[1]-in") println("Connecting peers...") simNetwork.connectAllPeers() println("Creating simulation...") val simulation = GossipSimulation(simConfig, simNetwork) simulation.forwardTime(5.seconds) simulation.publishMessage(0, 200000, topic) simulation.publishMessage(0, 100000, topic) simulation.forwardTime(1.seconds) simulation.publishMessage(0, 200000, topic) simulation.forwardTime(10.seconds) run { val deliveryResults = simulation.gatherPubDeliveryStats() assertThat(deliveryResults.deliveries).hasSize(3) assertThat(deliveryResults.deliveries[0].deliveryDelay).isCloseTo(2000, Offset.offset(100)) assertThat(deliveryResults.deliveries[1].deliveryDelay).isCloseTo(3000, Offset.offset(100)) } } }
33
null
76
272
1cde874089d45f90e2f6ca20f39a77b69cd7e66e
6,933
jvm-libp2p
Apache License 2.0
src/main/kotlin/no/nav/pensjon/simulator/core/domain/regler/to/BeregnAfpPrivatRequest.kt
navikt
753,551,695
false
{"Kotlin": 1536207, "Java": 48078, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.domain.regler.to import no.nav.pensjon.simulator.core.domain.regler.beregning2011.BeregningsResultatAfpPrivat import no.nav.pensjon.simulator.core.domain.regler.krav.Kravhode import no.nav.pensjon.simulator.core.domain.regler.vedtak.VilkarsVedtak import java.util.* class BeregnAfpPrivatRequest( var kravhode: Kravhode? = null, var vilkarsvedtakListe: ArrayList<VilkarsVedtak> = arrayListOf(), var virkFom: Date? = null, var ft: Double = 0.0, var justeringsbelop: Int = 0, var referansebelop: Int = 0, var ftKompensasjonstillegg: Double = 0.0, var sisteAfpPrivatBeregning: BeregningsResultatAfpPrivat? = null, var virkFomAfpPrivatUttak: Date? = null ) : ServiceRequest() { override fun virkFom(): Date? = this.virkFom override fun persons(): String = "" }
1
Kotlin
0
0
55436a278f64b54ca61437cd09ba27993ac40067
841
pensjonssimulator
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[189]旋转数组.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import java.util.Collections.reverse //给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 // // 示例 1: // // 输入: [1,2,3,4,5,6,7] 和 k = 3 //输出: [5,6,7,1,2,3,4] //解释: //向右旋转 1 步: [7,1,2,3,4,5,6] //向右旋转 2 步: [6,7,1,2,3,4,5] //向右旋转 3 步: [5,6,7,1,2,3,4] // // // 示例 2: // // 输入: [-1,-100,3,99] 和 k = 2 //输出: [3,99,-1,-100] //解释: //向右旋转 1 步: [99,-1,-100,3] //向右旋转 2 步: [3,99,-1,-100] // // 说明: // // // 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。 // 要求使用空间复杂度为 O(1) 的 原地 算法。 // // Related Topics 数组 // 👍 834 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun rotate(nums: IntArray, k: Int): Unit { //暴力破解 手动首位交换 时间复杂度 O(n*k) var temp =0 var pre = 0 for (i in 0 until k){ pre = nums[nums.size-1] for (j in nums.indices){ temp = nums[j] nums[j] = pre pre = temp } } /**=======================================================*/ //方法二 新数组保存偏移位置 i = (i+k)%nums.size //在赋值回原数组 时间复杂度 O(n) var tempNums = IntArray(nums.size) for (i in nums.indices){ tempNums[(i+k)%nums.size] = nums[i] } //赋值回原数组 for(i in nums.indices){ nums[i] = tempNums[i] } /**=======================================================*/ //方法三 全部反转后 前K个反转 后 n-k 个反转 // 时间复杂度 O(n) 空间复杂度 O(1) var k1 = k % nums.size //反转全部 reverse(nums, 0, nums.size-1); //翻转前K个 reverse(nums, 0, k1-1); //翻转 nums.length -k 个 reverse(nums, k1, nums.size-1); } //数组翻转 fun reverse(nums: IntArray, start: Int, end: Int) { var start = start var end = end while (start < end) { val temp = nums[start] nums[start] = nums[end] nums[end] = temp start++ end-- } } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,000
MyLeetCode
Apache License 2.0
src/main/kotlin/com/getyourguide/paparazzi/actions/ActualSizeAction.kt
getyourguide
558,799,421
false
{"Kotlin": 53549}
package com.getyourguide.paparazzi.actions import com.getyourguide.paparazzi.service.service import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent /** * Action to show the snapshots in their actual size */ class ActualSizeAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { e.project?.service?.zoomActualSize() } override fun update(e: AnActionEvent) { val project = e.project ?: return e.presentation.isEnabled = project.service.settings.isFitToWindow } override fun getActionUpdateThread() = ActionUpdateThread.EDT }
9
Kotlin
8
158
c062d36f549f598a28b663f41638ad1c73870105
700
paparazzi-plugin
Apache License 2.0
src/main/kotlin/com/bridgecrew/results/LicenseCheckovResult.kt
bridgecrewio
644,310,885
false
{"Kotlin": 295470}
package com.bridgecrew.results class LicenseCheckovResult( checkType: CheckType, filePath: String, resource: String, name: String, id: String, severity: Severity, description: String?, guideline: String?, absoluteFilePath: String, fileLineRange: List<Int>, fixDefinition: String?, codeBlock: List<List<Object>>, val policy: String?, val licenseType: String?, val approvedSPDX: Boolean) : BaseCheckovResult( category = Category.LICENSES, checkType, filePath, resource, name, id, severity, description, guideline, absoluteFilePath, fileLineRange, fixDefinition, codeBlock) {}
12
Kotlin
0
1
96a8e6f41ec878a72f621f70e4bfa9df2321dfeb
910
prisma-cloud-jetbrains-ide
Apache License 2.0
compiler/testData/diagnostics/tests/inference/capturedTypes/capturedTypeSubstitutedIntoOppositeProjection.kt
JakeWharton
99,388,807
true
null
// !DIAGNOSTICS: -UNUSED_PARAMETER // !CHECK_TYPE fun <T> foo1(a1: Array<in T>, a2: Array<T>): T = null!! fun test1(a1: Array<Int>, a2: Array<out Int>) { foo1(a1, a2) checkType { _<Int>() } } fun <T> foo2(a1: Array<T>, a2: Array<out T>): T = null!! fun test2(a1: Array<in Int>, a2: Array<Int>) { foo2(a1, a2) checkType { _<Any?>() } }
181
Kotlin
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
346
kotlin
Apache License 2.0
platform/object-serializer/src/VersionedFile.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serialization import com.intellij.util.ParameterizedTypeImpl import com.intellij.util.io.move import com.intellij.util.io.safeOutputStream import net.jpountz.lz4.LZ4FrameInputStream import net.jpountz.lz4.LZ4FrameOutputStream import java.io.IOException import java.io.InputStream import java.lang.reflect.Type import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.StandardOpenOption private const val fileBufferSize = 32 * 1024 internal const val LZ4_MAGIC = 0x184D2204 private val versionedFileDefaultWriteConfiguration = defaultWriteConfiguration.copy(filter = SkipNullAndEmptySerializationFilter) /** * [isCompressed] doesn't matter for read operation - all supported formats will be detected automatically. */ data class VersionedFile @JvmOverloads constructor(val file: Path, val version: Int, private val isCompressed: Boolean = true) { @Throws(IOException::class) @JvmOverloads fun <T> writeList(data: Collection<T>, itemClass: Class<T>, configuration: WriteConfiguration = versionedFileDefaultWriteConfiguration) { file.safeOutputStream().use { val out = if (isCompressed) LZ4FrameOutputStream(it, LZ4FrameOutputStream.BLOCKSIZE.SIZE_4MB) else it ObjectSerializer.instance.serializer.writeVersioned(data, out, version, configuration, ParameterizedTypeImpl(data.javaClass, itemClass)) } } @Throws(IOException::class, SerializationException::class) @JvmOverloads @Suppress("UNCHECKED_CAST") fun <T> readList(itemClass: Class<T>, configuration: ReadConfiguration = ReadConfiguration(), renameToCorruptedOnError: Boolean = true): List<T>? = readAndHandleErrors(ArrayList::class.java, configuration, ParameterizedTypeImpl(ArrayList::class.java, itemClass), renameToCorruptedOnError) as List<T>? @Throws(IOException::class, SerializationException::class) @JvmOverloads fun <T : Any> read(objectClass: Class<T>, beanConstructed: BeanConstructed? = null): T? = readAndHandleErrors(objectClass, ReadConfiguration(beanConstructed = beanConstructed)) private fun <T : Any> readAndHandleErrors(objectClass: Class<T>, configuration: ReadConfiguration, originalType: Type? = null, renameToCorruptedOnError: Boolean = true): T? = readPossiblyCompressedIonFile(file) { input -> val result = try { ObjectSerializer.instance.serializer.readVersioned(objectClass, input, file, version, configuration, originalType) } catch (e: Exception) { if (renameToCorruptedOnError) { renameSilentlyToCorrupted() } // in tests log will throw error, renameSilentlyToCorrupted is called before LOG.error(e) return null } if (result == null && renameToCorruptedOnError) { renameSilentlyToCorrupted() } return result } private fun renameSilentlyToCorrupted() { try { file.move(file.parent.resolve("${file.fileName}.corrupted")) } catch (e: Exception) { LOG.debug(e) } } } internal inline fun <T : Any> readPossiblyCompressedIonFile(file: Path, consumer: (InputStream) -> T?): T? { val channel = try { Files.newByteChannel(file, setOf(StandardOpenOption.READ)) } catch (e: NoSuchFileException) { return null } catch (e: IOException) { LOG.error(e) return null } channel.use { val lz4Magic = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN) channel.read(lz4Magic) channel.position(0) var input = Channels.newInputStream(channel) input = when (lz4Magic.getInt(0)) { LZ4_MAGIC -> LZ4FrameInputStream(input) else -> input.buffered(fileBufferSize) } return consumer(input) } }
214
null
4829
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
4,073
intellij-community
Apache License 2.0
src/test/kotlin/Exercici3Test.kt
alortegama
743,857,349
false
{"Kotlin": 7592}
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeAll import kotlin.math.exp class Exercici3Test { @Test fun `Quan el text esta buit, retorna 0`() { val result = contarVocals("") assertEquals(0, result) } @Test fun `Quan el text no te vocals, retorna 0`() { val result = contarVocals("bcdfg") assertEquals(0, result) } @Test fun `Quan el text te nomes una vocal, retorna 1`() { val result = contarVocals("a") assertEquals(1, result) } @Test fun `Quan el text te totes les vocals, retorna el número de vocals`() { val result = contarVocals("aeiou") assertEquals(5, result) } @Test fun `Quan el text te una vocal majuscula, la compta`() { val result = contarVocals("A") assertEquals(1, result) } @Test fun `Donada una frase comuna, retorna el recompte correcte de vocals`() { val result = contarVocals("Aquesta és una prova unitària.") assertEquals(14, result) } }
0
Kotlin
0
0
b2ff73bd60051a78870bc746e0ce9cc89433bd3f
1,102
Prova-avaluada-kotlin
MIT License
domain/src/main/java/com/worldsnas/domain/mappers/server/ReviewServerRepoMapper.kt
worldsnas
178,716,293
false
{"Kotlin": 397002, "Java": 240871}
package com.worldsnas.domain.mappers.server import com.worldsnas.domain.model.repomodel.ReviewRepoModel import com.worldsnas.domain.model.servermodels.ReviewServerModel import com.worldsnas.panther.Mapper import javax.inject.Inject class ReviewServerRepoMapper @Inject constructor( ): Mapper<ReviewServerModel, ReviewRepoModel> { override fun map(item: ReviewServerModel): ReviewRepoModel = ReviewRepoModel( 0, item.author, item.content, item.id, item.url ) }
1
Kotlin
8
57
c7d084d2cf2c4f9486337fe347d5d6b8b5806e0a
541
AIO
Apache License 2.0
core/src/main/kotlin/com/kroegerama/kgen/poet/ModelFilesGenerator.kt
kroegerama
237,459,003
false
{"Kotlin": 116380}
package com.kroegerama.kgen.poet import com.kroegerama.kgen.OptionSet import com.kroegerama.kgen.language.asClassFileName import com.kroegerama.kgen.language.asTypeName import com.kroegerama.kgen.model.ModelTreeNode import com.kroegerama.kgen.openapi.OpenAPIAnalyzer import com.kroegerama.kgen.openapi.SchemaType import com.squareup.kotlinpoet.* import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.oas.models.media.ArraySchema import io.swagger.v3.oas.models.media.MapSchema interface IModelFilesGenerator { fun getModelFiles(): List<FileSpec> } class ModelFilesGenerator( openAPI: OpenAPI, options: OptionSet, analyzer: OpenAPIAnalyzer ) : IModelFilesGenerator, IPoetGeneratorSchemaHandler by PoetGeneratorSchemaHandler(openAPI, options, analyzer), IPoetGeneratorBase by PoetGeneratorBase(openAPI, options, analyzer) { override fun getModelFiles() = getPrimitivesFile() + getEnumsFile() + getObjectFiles() + getUnnamedObjectFiles() private fun getPrimitivesFile(): List<FileSpec> { val namedPrimitives = getNamedPrimitives() val aliases = getTypeAliases() return if (namedPrimitives.size + aliases.size == 0) emptyList() else listOf( prepareFileSpec(options.modelPackage, "\$Named") { namedPrimitives.forEach { (tSpec, fSpec) -> addType(tSpec) addFunction(fSpec) } aliases.forEach { ta -> addTypeAlias(ta) } } ) } private fun getEnumsFile() = getEnums().let { enums -> if (enums.isEmpty()) { emptyList() } else { listOf( prepareFileSpec(options.modelPackage, "\$Enums") { enums.forEach { enum -> addType(enum) } } ) } } private fun getUnnamedObjectFiles(): List<FileSpec> = analyzer.objectTree.unknown.map { schemaInfo -> val name = schemaInfo.name val schema = schemaInfo.schema prepareFileSpec(options.modelPackage, name.asClassFileName()) { val className = ClassName(options.modelPackage, name.asTypeName()) val type = schema.asTypeSpec(className) {} addType(type) } } private fun getObjectFiles(): List<FileSpec> = analyzer.objectTree.nodes.map { (schemaInfo, children) -> val name = schemaInfo.name val schema = schemaInfo.schema prepareFileSpec(options.modelPackage, name.asClassFileName()) { val className = ClassName(options.modelPackage, name.asTypeName()) val rootType = if (schemaInfo.schemaType == SchemaType.OneOf) { schema.asSealedTypeSpec(className) { addChildren(className, children) } } else { schema.asTypeSpec(className) { addChildren(className, children) } } addType(rootType) } } private fun TypeSpec.Builder.addChildren( parentCn: ClassName, items: MutableSet<ModelTreeNode> ) { items.forEach { (schemaInfo, children) -> val name = schemaInfo.name val schema = schemaInfo.schema val className = ClassName(options.modelPackage, name.asTypeName()) //only use Objects and Enums as child classes/enums (see OpenApiAnalyzer#buildModelTree) val type = when (val type = schemaInfo.schemaType) { SchemaType.Object -> schema.asTypeSpec(className) { val discriminator = schemaInfo.discriminator if (discriminator != null) { addAnnotation(poetAnnotation(PoetConstants.SEALED_TYPE_LABEL) { addMember("\"$discriminator\"") }) superclass(parentCn) } addChildren(className, children) } SchemaType.Enum -> schema.asEnumSpec(className) else -> throw IllegalStateException("Type $type not allowed in ModelTree") } addType(type) } } private fun getNamedPrimitives(): List<Pair<TypeSpec, FunSpec>> = mutableListOf<Pair<TypeSpec, FunSpec>>().apply { if (options.useInlineClass) { analyzer.namedPrimitives.forEach { schemaInfo -> val schema = schemaInfo.schema val name = ClassName(options.modelPackage, schemaInfo.name.asTypeName()) add(schema.createNamedPrimitive(name)) } } } private fun getTypeAliases(): List<TypeAliasSpec> = mutableListOf<TypeAliasSpec>().apply { with(analyzer) { if (!options.useInlineClass) { namedPrimitives.forEach { schemaInfo -> val schema = schemaInfo.schema val name = schemaInfo.name add(schema.createPrimitiveTypeAlias(name)) } } namedArrays.forEach { schemaInfo -> val schema = schemaInfo.schema val name = schemaInfo.name add((schema as ArraySchema).createArrayTypeAlias(name)) } namedMaps.forEach { schemaInfo -> val schema = schemaInfo.schema val name = schemaInfo.name add((schema as MapSchema).createMapTypeAlias(name)) } } } private fun getEnums(): List<TypeSpec> = mutableListOf<TypeSpec>().apply { with(analyzer.enums) { forEach { schemaInfo -> val schema = schemaInfo.schema val name = schemaInfo.name val className = ClassName(options.modelPackage, name.asTypeName()) add(schema.asEnumSpec(className)) } } } }
4
Kotlin
4
22
d332c54989c73ed80cbb40b75c22d8589f5ac0eb
6,015
openapi-kgen
Apache License 2.0
src/orchid/java/com/eden/orchid/starter/ReplaceFunction.kt
jmfayard
223,139,165
false
null
package com.eden.orchid.starter import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.options.annotations.Option /** * This is an example Function, added as a custom component for this site only. A Function is can be used as part of an * Pebble expression when precompiling markup. TemplateFunctions can also accept their first parameter piped in as a * Pebble filter. * * To create a Function, you'll need to: * * 1) Make a subclass of `TemplateFunction` * - `public class ReplaceFunction extends TemplateFunction` * - `super("replace", false)` * - return the order of parameters set on the tag. The first one is typically "input" * - override `apply()` and return the function result * 2) Register that subclass in your custom Module * - in `OrchidStarterModule`: `addToSet(TemplateFunction.class, ReplaceFunction.class)` */ data class ReplaceFunction( @Option var input: String = "", @Option var find: String = "", @Option var replace: String = "" ) : TemplateFunction("replace", false) { override fun parameters(): Array<String> = arrayOf("input", "find", "replace") override fun apply(): String = when { input.isBlank() -> "" else -> input.replace(find.toRegex(), replace) } }
0
Kotlin
0
0
d1ba4e39ceb7227de0b0694286c1b48b7a7c418b
1,267
website-builtwithgradle
MIT License
analysis/symbol-light-classes/src/org/jetbrains/kotlin/light/classes/symbol/methods/SymbolLightConstructor.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.light.classes.symbol.methods import com.intellij.psi.* import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.symbols.KaConstructorSymbol import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.light.classes.symbol.annotations.GranularAnnotationsBox import org.jetbrains.kotlin.light.classes.symbol.annotations.SymbolAnnotationsProvider import org.jetbrains.kotlin.light.classes.symbol.classes.SymbolLightClassBase import org.jetbrains.kotlin.light.classes.symbol.classes.SymbolLightClassForEnumEntry import org.jetbrains.kotlin.light.classes.symbol.modifierLists.GranularModifiersBox import org.jetbrains.kotlin.light.classes.symbol.modifierLists.SymbolLightMemberModifierList import org.jetbrains.kotlin.light.classes.symbol.modifierLists.with import java.util.* internal class SymbolLightConstructor( ktAnalysisSession: KaSession, constructorSymbol: KaConstructorSymbol, containingClass: SymbolLightClassBase, methodIndex: Int, argumentsSkipMask: BitSet? = null, ) : SymbolLightMethod<KaConstructorSymbol>( ktAnalysisSession = ktAnalysisSession, functionSymbol = constructorSymbol, lightMemberOrigin = null, containingClass = containingClass, methodIndex = methodIndex, argumentsSkipMask = argumentsSkipMask, ) { private val _name: String? = containingClass.name override fun getName(): String = _name ?: "" override fun isConstructor(): Boolean = true override fun isOverride(): Boolean = false override fun hasTypeParameters(): Boolean = false override fun getTypeParameterList(): PsiTypeParameterList? = null override fun getTypeParameters(): Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY private val _modifierList: PsiModifierList by lazyPub { val initialValue = if (this.containingClass is SymbolLightClassForEnumEntry) { GranularModifiersBox.VISIBILITY_MODIFIERS_MAP.with(PsiModifier.PACKAGE_LOCAL) } else { emptyMap() } SymbolLightMemberModifierList( containingDeclaration = this, modifiersBox = GranularModifiersBox( initialValue = initialValue, computer = ::computeModifiers, ), annotationsBox = GranularAnnotationsBox( annotationsProvider = SymbolAnnotationsProvider( ktModule = ktModule, annotatedSymbolPointer = functionSymbolPointer, ) ), ) } private fun computeModifiers(modifier: String): Map<String, Boolean>? { if (modifier !in GranularModifiersBox.VISIBILITY_MODIFIERS) return null return GranularModifiersBox.computeVisibilityForMember(ktModule, functionSymbolPointer) } override fun getModifierList(): PsiModifierList = _modifierList override fun getReturnType(): PsiType? = null }
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,163
kotlin
Apache License 2.0
app/src/main/java/tartho/example/vetdrugs/adapter/MedicineAdapter.kt
tartho77
667,487,550
false
null
package tartho.example.vetdrugs.adapter import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import tartho.example.vetdrugs.DrugsModel import tartho.example.vetdrugs.DrugsPopup import tartho.example.vetdrugs.DrugsRepository import tartho.example.vetdrugs.MainActivity import tartho.example.vetdrugs.R import tartho.example.vetdrugs.ui.home.HomeFragment class MedicineAdapter(val context: MainActivity, private val DrugsList:List<DrugsModel>, private val layoutID: Int) : RecyclerView.Adapter<MedicineAdapter.ViewHolder>() { //Boîte pour ranger tout les composants à contrôler class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val medicineCategoryImage = view.findViewById<ImageView>(R.id.image_item) val drugsName: TextView? = view.findViewById(R.id.item_drugs_name) val molecularName: TextView? = view.findViewById(R.id.item_molecular_name) val drugsCategoryName: TextView? = view.findViewById(R.id.item_category_name) val starIcon = view.findViewById<ImageView>(R.id.star_icon) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(layoutID, parent, false) return ViewHolder(view) } override fun getItemCount(): Int = DrugsList.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { //Récupérer les informations du médicament spécifique val currentDrugs = DrugsList[position] //Récupérer le repository val repo =DrugsRepository() // Récupérer l'image à partir du lien Glide.with(context).load(Uri.parse(currentDrugs.imageUrl)) .into(holder.medicineCategoryImage) //Mettre à jours nom du médicaments et autres informations holder.drugsName?.text = currentDrugs.name_drugs holder.molecularName?.text = currentDrugs.name_molecular holder.drugsCategoryName?.text = currentDrugs.drugs_category //Vérifier si le médicament à été liké if (currentDrugs.liked) { holder.starIcon.setImageResource(R.drawable.ic_star) } else { holder.starIcon.setImageResource(R.drawable.ic_unstar) } //rajouter une interraction sur l'étoile holder.starIcon.setOnClickListener{ //Inverse le bouton like ou unlike currentDrugs.liked= !currentDrugs.liked //Mettre à jour l'objet Drugs repo.updateDrugs(currentDrugs) } //Interaction lors du clic sur un médicament holder.itemView.setOnClickListener{ //Afficher la popup DrugsPopup(this,currentDrugs).show() } } }
0
Kotlin
0
0
dfe544a4b93c5170df2d9852b5054ddf90bb363e
2,919
Vet-Drugs
Apache License 2.0
src/main/java/org/stevenlowes/tools/lifxcontroller/commands/request/light/RequestSetInfrared.kt
stevenwaterman
126,380,593
true
{"Kotlin": 53966}
package org.stevenlowes.tools.lifxcontroller.commands.request.light import org.stevenlowes.tools.lifxcontroller.commands.request.RequestCommand import org.stevenlowes.tools.lifxcontroller.values.Level data class RequestSetInfrared(val brightness: Level = Level.MIN) : RequestCommand(122) { override val payloadBytes: ByteArray = brightness.byteArray }
0
Kotlin
0
0
7b17808a6ca08e7efc7cefe937be1a5d0eb4f4b5
358
LifxCommander_v1.0
MIT License
app/src/main/java/com/sunilson/quizcreator/presentation/mainActivity/di/FragmentBuilder.kt
sunilson
140,581,390
false
{"Kotlin": 213913, "HTML": 4769}
package com.sunilson.quizcreator.presentation.mainActivity.di import com.sunilson.quizcreator.application.di.scopes.FragmentScope import com.sunilson.quizcreator.presentation.mainActivity.fragments.allQuestionsFragment.AllQuestionsFragment import com.sunilson.quizcreator.presentation.mainActivity.fragments.categoriesFragment.CategoriesFragment import com.sunilson.quizcreator.presentation.mainActivity.fragments.createQuizFragment.CreateQuizFragment import com.sunilson.quizcreator.presentation.mainActivity.fragments.statisticsFragment.StatisticsFragment import com.sunilson.quizcreator.presentation.mainActivity.fragments.tutorialFragment.TutorialFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FragmentBuilder { @ContributesAndroidInjector @FragmentScope abstract fun contributeHomeFragment(): StatisticsFragment @ContributesAndroidInjector @FragmentScope abstract fun contributeAllQuestionFragment(): AllQuestionsFragment @ContributesAndroidInjector @FragmentScope abstract fun contributeQuizFragment(): CreateQuizFragment @ContributesAndroidInjector @FragmentScope abstract fun contributeCategoryFragment(): CategoriesFragment @ContributesAndroidInjector @FragmentScope abstract fun contributeTutorialragment(): TutorialFragment }
0
Kotlin
0
0
2cb6310afda510cae8d437f96a03cc2f0cf6915b
1,359
quiz-creator
MIT License
bridgesample/src/main/java/com/livefront/bridgesample/scenario/activity/NonBridgeLargeDataActivity.kt
livefront
94,903,404
false
null
package com.livefront.bridgesample.scenario.activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.os.Parcelable import android.view.MenuItem import com.evernote.android.state.State import com.livefront.bridgesample.R import com.livefront.bridgesample.base.NonBridgeBaseActivity import com.livefront.bridgesample.util.handleHomeAsBack import com.livefront.bridgesample.util.setHomeAsUpToolbar import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.activity_large_data.bitmapGeneratorView import kotlinx.android.synthetic.main.basic_toolbar.toolbar class NonBridgeLargeDataActivity : NonBridgeBaseActivity() { @State var savedBitmap: Bitmap? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_large_data) setHomeAsUpToolbar(toolbar, R.string.non_bridge_large_data_screen_title) bitmapGeneratorView.apply { setHeaderText(R.string.non_bridge_large_data_header) generatedBitmap = savedBitmap onBitmapGeneratedListener = { savedBitmap = it } if (getArguments(this@NonBridgeLargeDataActivity).infiniteBackstack) { onNavigateButtonClickListener = { startActivity( getNavigationIntent( this@NonBridgeLargeDataActivity, getArguments(this@NonBridgeLargeDataActivity) ) ) } } } } override fun onOptionsItemSelected(item: MenuItem) = handleHomeAsBack(item) { super.onOptionsItemSelected(item) } companion object { private const val ARGUMENTS_KEY = "arguments" fun getArguments( activity: NonBridgeLargeDataActivity ): NonBridgeLargeDataActivityArguments = activity .intent .getParcelableExtra(ARGUMENTS_KEY)!! fun getNavigationIntent( context: Context, arguments: NonBridgeLargeDataActivityArguments ) = Intent(context, NonBridgeLargeDataActivity::class.java).apply { putExtra(ARGUMENTS_KEY, arguments) } } } @Parcelize data class NonBridgeLargeDataActivityArguments( val infiniteBackstack: Boolean = false ) : Parcelable
4
Java
25
246
657f8a6646f99232ea4c9362202dbf387662fb55
2,478
bridge
Apache License 2.0
telegram/src/main/kotlin/com/mazekine/telegram/dispatcher/handlers/ChannelHandler.kt
xestrum
222,923,452
true
{"Kotlin": 268485}
package com.mazekine.telegram.dispatcher.handlers import com.mazekine.telegram.HandleUpdate import com.mazekine.telegram.entities.Update class ChannelHandler(handleUpdate: HandleUpdate) : Handler(handleUpdate) { override val groupIdentifier: String get() = "channel" override fun checkUpdate(update: Update): Boolean { return update.channelPost != null || update.editedChannelPost != null } }
0
Kotlin
0
0
bcd448ff688edb11ff4495f729eb09210f768203
424
mazekine-telegram-bot
Apache License 2.0
src/behaivorDesignPattern/strategy/PaymentCredit.kt
dja1369
807,056,411
false
{"Kotlin": 29080}
package src.behaivorDesignPattern.strategy class PaymentCredit: Payment{ override fun pay(amount: Int): String { return "Paid $amount using credit card" } }
0
Kotlin
0
0
8c9a410eb7c8e51b8953cecf77103b0e6318e937
173
aboutDesignPattern
MIT License
app/src/main/java/com/wechantloup/gamelistoptimization/ui/game/EditGameScreen.kt
Pilou44
414,594,767
false
{"Kotlin": 132942}
package com.wechantloup.gamelistoptimization.game import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.TopAppBar import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import coil.compose.AsyncImage import com.wechantloup.gamelistoptimization.R import com.wechantloup.gamelistoptimization.compose.BackButton import com.wechantloup.gamelistoptimization.compose.FullScreenLoader import com.wechantloup.gamelistoptimization.model.Game import com.wechantloup.gamelistoptimization.theme.Dimens @Composable fun EditGameScreen( viewModel: GameViewModel, onBackPressed: () -> Unit, ) { val state = viewModel.stateFlow.collectAsState() EditGameScreen( game = requireNotNull(state.value.game), image = state.value.image, isLoaderVisible = state.value.showLoader, onBackPressed = onBackPressed, onGameChanged = viewModel::onGameChanged, saveGame = viewModel::saveGame, scrapGame = viewModel::scrapGame, ) } @Composable private fun EditGameScreen( game: Game, image: String?, isLoaderVisible: Boolean, onBackPressed: () -> Unit, onGameChanged: (Game) -> Unit, saveGame: (() -> Unit) -> Unit, scrapGame: () -> Unit, ) { var modified by remember { mutableStateOf(false) } val saveAndGoBack: () -> Unit = { if (modified) saveGame(onBackPressed) else onBackPressed() } BackHandler { saveAndGoBack() } val scaffoldState = rememberScaffoldState() Scaffold( scaffoldState = scaffoldState, topBar = { TopAppBar( title = { Text( text = stringResource(R.string.app_name) ) }, backgroundColor = MaterialTheme.colors.surface, navigationIcon = { BackButton(onBackPressed = saveAndGoBack) }, actions = { Button(onClick = { modified = true scrapGame() }) { Text(text = "Scrap") } }, ) } ) { paddingValues -> FullScreenLoader( modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding()), isVisible = isLoaderVisible, ) { Row( modifier = Modifier .fillMaxSize() .padding(Dimens.spacingS) ) { Column(modifier = Modifier.fillMaxWidth(0.6f)) { TextField( modifier = Modifier.padding(Dimens.spacingS), value = game.name ?: game.path, onValueChange = { onGameChanged(game.copy(name = it)) modified = true }, label = { Text(stringResource(R.string.game_name)) }, ) TextField( modifier = Modifier.padding(Dimens.spacingS), value = game.developer ?: "", onValueChange = { onGameChanged(game.copy(developer = it)) modified = true }, label = { Text(stringResource(R.string.game_developer)) }, ) TextField( modifier = Modifier.padding(Dimens.spacingS), value = game.publisher ?: "", onValueChange = { onGameChanged(game.copy(publisher = it)) modified = true }, label = { Text(stringResource(R.string.game_publisher)) }, ) TextField( modifier = Modifier.padding(Dimens.spacingS), value = game.desc ?: "", onValueChange = { onGameChanged(game.copy(desc = it)) modified = true }, label = { Text(stringResource(R.string.game_desc)) }, ) } AsyncImage( modifier = Modifier .padding(Dimens.spacingS), model = image, contentDescription = game.name, ) } } } }
0
Kotlin
0
0
b49d5228d2ef796b4aff0f7afb87b2bbc5ca168d
5,414
GameListOptimization
Apache License 2.0
src/com/darkgravity/khexgrid/render/ShapeRendererLayer.kt
dmccabe
128,491,462
false
null
package com.darkgravity.khexgrid.render import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer /** * @author Dan McCabe */ abstract class ShapeRendererLayer(val shapeRenderer: ShapeRenderer) : LayerAdapter() { override fun preRender(batch: PolygonSpriteBatch) { shapeRenderer.projectionMatrix = batch.projectionMatrix shapeRenderer.updateMatrices() shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) } override fun postRender(batch: PolygonSpriteBatch) = shapeRenderer.end() }
0
null
4
18
e73e086175fcb5c21855e3f32acff1930911f7c5
575
khexgrid
Apache License 2.0
plugin-bsp/src/main/kotlin/org/jetbrains/plugins/bsp/magicmetamodel/impl/workspacemodel/impl/updaters/transformers/JavaModuleToDummyJavaModulesTransformerHACK.kt
JetBrains
826,262,028
false
null
package org.jetbrains.plugins.bsp.impl.magicmetamodel.impl.workspacemodel.impl.updaters.transformers import com.intellij.openapi.module.StdModuleTypes import com.intellij.platform.workspace.jps.entities.ModuleTypeId import com.intellij.platform.workspace.jps.entities.SourceRootTypeId import org.jetbrains.plugins.bsp.impl.magicmetamodel.extensions.allSubdirectoriesSequence import org.jetbrains.plugins.bsp.impl.magicmetamodel.impl.workspacemodel.JavaModule import org.jetbrains.plugins.bsp.impl.magicmetamodel.impl.workspacemodel.JavaSourceRoot import org.jetbrains.plugins.bsp.impl.utils.replaceDots import org.jetbrains.plugins.bsp.impl.utils.shortenTargetPath import org.jetbrains.plugins.bsp.workspacemodel.entities.ContentRoot import org.jetbrains.plugins.bsp.workspacemodel.entities.GenericModuleInfo import org.jetbrains.plugins.bsp.workspacemodel.entities.ResourceRoot import java.io.File import java.nio.file.Path import kotlin.io.path.Path import kotlin.io.path.isDirectory import kotlin.io.path.notExists import kotlin.io.path.pathString public data class DummySourceRootWithPackagePrefix(val sourcePath: Path, val packagePrefix: String = "") /** * This is a HACK for letting single source Java files to be resolved normally * Should remove soon and replace with a more robust solution */ public class JavaModuleToDummyJavaModulesTransformerHACK(private val projectBasePath: Path) : WorkspaceModelEntityPartitionTransformer<JavaModule, JavaModule> { internal companion object { val DUMMY_JAVA_SOURCE_MODULE_ROOT_TYPE = SourceRootTypeId("java-source") val DUMMY_JAVA_RESOURCE_MODULE_ROOT_TYPE = SourceRootTypeId("java-resource") } override fun transform(inputEntity: JavaModule): List<JavaModule> { val dummyJavaModuleSourceRoots = calculateDummyJavaSourceRoots(inputEntity.sourceRoots) val dummyJavaModuleNames = calculateDummyJavaModuleNames(dummyJavaModuleSourceRoots, projectBasePath) val dummyJavaResourcePath = calculateDummyResourceRootPath(inputEntity, dummyJavaModuleSourceRoots, projectBasePath) return dummyJavaModuleSourceRoots .zip(dummyJavaModuleNames) .mapNotNull { calculateDummyJavaSourceModule( name = it.second, sourceRootWithPackagePrefix = it.first, javaModule = inputEntity, resourceRootPath = dummyJavaResourcePath, ) }.distinctBy { it.genericModuleInfo.name } } private fun calculateDummyJavaSourceModule( name: String, sourceRootWithPackagePrefix: DummySourceRootWithPackagePrefix, javaModule: JavaModule, resourceRootPath: Path? = null, ) = if (name.isEmpty()) { null } else { JavaModule( genericModuleInfo = GenericModuleInfo( name = name, type = ModuleTypeId(StdModuleTypes.JAVA.id), modulesDependencies = listOf(), librariesDependencies = javaModule.genericModuleInfo.librariesDependencies, isDummy = true, languageIds = listOf("java", "scala", "kotlin"), ), baseDirContentRoot = ContentRoot(path = sourceRootWithPackagePrefix.sourcePath), sourceRoots = listOf( JavaSourceRoot( sourcePath = sourceRootWithPackagePrefix.sourcePath, generated = false, packagePrefix = sourceRootWithPackagePrefix.packagePrefix, rootType = DUMMY_JAVA_SOURCE_MODULE_ROOT_TYPE, ), ), resourceRoots = if (resourceRootPath != null) { listOf( ResourceRoot( resourcePath = resourceRootPath, rootType = DUMMY_JAVA_RESOURCE_MODULE_ROOT_TYPE, ), ) } else { listOf() }, moduleLevelLibraries = listOf(), jvmJdkName = javaModule.jvmJdkName, kotlinAddendum = javaModule.kotlinAddendum, javaAddendum = javaModule.javaAddendum, ) } } internal fun calculateDummyResourceRootPath( entity: JavaModule, dummySources: List<DummySourceRootWithPackagePrefix>, projectBasePath: Path, ): Path? { val resourceRoots = entity.resourceRoots if (entity.resourceRoots.isEmpty()) return null val moduleRoot = entity.baseDirContentRoot?.path ?: return null fun Path.reversedPaths() = allSubdirectoriesSequence().toList().reversed().asSequence() fun Sequence<Path>.findCommonParentsWith(list: Sequence<Path>): Sequence<Path> { val lastCommon = zip(list) { a, b -> a == b }.lastIndexOf(true) return take(lastCommon + 1) } fun <T> List<T>.foldPathsToCommonParent(list: Sequence<Path>, operation: (T) -> Sequence<Path>) = fold(list) { acc, element -> acc.findCommonParentsWith(operation(element)) } fun Path.isDescendantOf(ancestor: Path) = toAbsolutePath().startsWith(ancestor.toAbsolutePath()) fun getImmediateChildFromAncestorOrNull(path: Path, ancestor: Path): Path? = if (path == ancestor || !path.isDescendantOf(ancestor)) { null } else { ancestor.resolve(path.toAbsolutePath().getName(ancestor.toAbsolutePath().nameCount)) } val firstResourcePaths = resourceRoots.first().resourcePath.reversedPaths() // We calculate common parent among all module resources val commonResourcesPaths = resourceRoots.foldPathsToCommonParent(firstResourcePaths) { it.resourcePath.reversedPaths() } val resourcesRootPath = if (dummySources.isNotEmpty()) { // We try to calculate common paths parent between sources and resources and checks if it's still inside module root val firstSourcePaths = dummySources.first().sourcePath.reversedPaths() val commonSourcePaths = dummySources.foldPathsToCommonParent(firstSourcePaths) { it.sourcePath.reversedPaths() } val commonRoot = commonResourcesPaths.findCommonParentsWith(commonSourcePaths).last() if (commonRoot.isDescendantOf(moduleRoot)) { getImmediateChildFromAncestorOrNull(commonResourcesPaths.last(), commonRoot) } else { null } } else { // If they are no sources present, we just take the immediate child of module root with all the resources inside if (commonResourcesPaths.last() == moduleRoot) { moduleRoot } else { getImmediateChildFromAncestorOrNull(commonResourcesPaths.last(), moduleRoot) } } // We will take the path if it's inside projectBasePath return resourcesRootPath?.takeIf { path -> resourceRoots.none { it.resourcePath == path } && path.isDescendantOf(projectBasePath) } } internal fun calculateDummyJavaSourceRoots(sourceRoots: List<JavaSourceRoot>): List<DummySourceRootWithPackagePrefix> = sourceRoots .asSequence() .filter { !it.generated } .mapNotNull { restoreSourceRootFromPackagePrefix(it) }.distinct() .toList() private fun restoreSourceRootFromPackagePrefix(sourceRoot: JavaSourceRoot): DummySourceRootWithPackagePrefix? { if (sourceRoot.sourcePath.notExists() || sourceRoot.sourcePath.isDirectory()) return null val packagePrefixPath = sourceRoot.packagePrefix.replace('.', File.separatorChar) val sourceParent = sourceRoot.sourcePath.parent.pathString val sourceRootString = sourceParent.removeSuffix(packagePrefixPath) val sourceRootPath = Path(sourceRootString) if (sourceParent == sourceRootString) return DummySourceRootWithPackagePrefix(sourceRootPath, sourceRoot.packagePrefix) return DummySourceRootWithPackagePrefix(sourceRootPath) } internal fun calculateDummyJavaModuleNames( dummyJavaModuleSourceRoots: List<DummySourceRootWithPackagePrefix>, projectBasePath: Path, ): List<String> = dummyJavaModuleSourceRoots.map { calculateDummyJavaModuleName(it.sourcePath, projectBasePath) } internal fun calculateDummyJavaModuleName(sourceRoot: Path, projectBasePath: Path): String { val absoluteSourceRoot = sourceRoot.toAbsolutePath().toString() val absoluteProjectBasePath = projectBasePath.toAbsolutePath().toString() return absoluteSourceRoot .substringAfter(absoluteProjectBasePath) .trim { it == File.separatorChar } .replaceDots() .replace(File.separator, ".") .addIntelliJDummySuffix() .shortenTargetPath() } private fun String.addIntelliJDummySuffix() = "$this-intellij-generated"
7
null
18
45
1d79484cfdf8fc31d3a4b214655e857214071723
8,187
hirschgarten
Apache License 2.0
libraries/core/src/main/java/app/chamich/library/core/extensions/EditTextExt.kt
Coinfo
278,306,465
false
{"Kotlin": 136112, "Ruby": 866}
/* * Copyright (c) 2020 Chamich Apps. All rights reserved. */ package app.chamich.library.core.extensions import android.widget.EditText /** * Returns the {@see EditText} text as Long if conversion succeed; otherwise 0 */ val EditText.asLong get() = try { if (!this.hasText) 0L else this.text.toString().toLong() } catch (e: NumberFormatException) { 0L } val EditText.asInt get() = try { if (!this.hasText) 0 else this.text.toString().toInt() } catch (e: NumberFormatException) { 0 } /** * Returns the {@see EditText} text as String */ val EditText.asString get() = this.text.toString() val EditText.hasText get() = !this.text.isNullOrBlank()
0
Kotlin
3
16
581bf4e4ff7e9cb5067bdf25e4e340b56ebaab92
719
Perfectus
Apache License 2.0
example/src/main/java/com/bohregard/example/ui/AnimatedTextFieldUi.kt
bohregard
284,123,182
false
{"Kotlin": 177825}
package com.bohregard.example.ui import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.bohregard.animatedtextfield.AnimatedTextField import com.bohregard.example.R @Composable fun AnimatedTextFieldUi() { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(horizontal = 20.dp) ) { var enabled by remember { mutableStateOf(true) } Button(onClick = { enabled = !enabled }) { Text(text = if (enabled) "Disabled" else "Enable") } var text by remember { mutableStateOf("") } AnimatedTextField( enabled = enabled, leadingIcon = R.drawable.ic_person, maxCharacters = 12, onClear = { text = "" }, onValueChange = { text = it }, placeholder = "Placeholder", text = text ) } } }
0
Kotlin
0
0
de7011b118bbd97ec9d5a7acd9bb66e0c02519cc
1,469
Compose-Companion
MIT License
app/src/main/java/com/orange/ods/app/ui/modules/emptystate/EmptyStateDemoScreen.kt
Orange-OpenSource
440,548,737
false
null
/* * Software Name: Orange Design System * SPDX-FileCopyrightText: Copyright (c) Orange SA * SPDX-License-Identifier: MIT * * This software is distributed under the MIT license, * the text of which is available at https://opensource.org/license/MIT/ * or see the "LICENSE" file for more details. * * Software description: Android library of reusable graphical components */ package com.orange.ods.app.ui.modules.emptystate import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import com.orange.ods.app.R import com.orange.ods.app.ui.components.utilities.clickOnElement import com.orange.ods.app.ui.utilities.DrawableManager.getDrawableResIdForCurrentTheme import com.orange.ods.compose.module.emptystate.OdsEmptyStateView @Composable fun EmptyStateDemoScreen(viewModel: EmptyStateCustomizationViewModel) { val context = LocalContext.current val elementClicked = stringResource(id = R.string.module_emptyState_button_customization) val illustrationRes = getDrawableResIdForCurrentTheme(viewModel.usage.illustrationRes) OdsEmptyStateView( title = stringResource(id = viewModel.usage.titleRes), text = if (viewModel.text) stringResource(id = viewModel.usage.textRes) else null, button = if (viewModel.button) { OdsEmptyStateView.Button(text = stringResource(id = viewModel.usage.buttonLabelRes)) { clickOnElement(context, elementClicked) } } else { null }, image = OdsEmptyStateView.Image(painter = painterResource(id = illustrationRes)) ) }
74
null
9
17
60c9c9fdc91e4c0598fd4279df5154599cf246de
1,675
ods-android
MIT License
paris-processor/src/main/java/com/airbnb/paris/processor/framework/AndroidClassNames.kt
katzvelraj
150,662,499
true
{"Gradle": 10, "Ruby": 1, "Markdown": 5, "INI": 4, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "XML": 44, "Java": 33, "Kotlin": 116, "Java Properties": 1}
package com.airbnb.paris.processor.framework internal object AndroidClassNames { val ATTRIBUTE_SET = "android.util.AttributeSet".className() val R = "android.R".className() val CONTEXT = "android.content.Context".className() val RESOURCES = "android.content.res.Resources".className() val VIEW = "android.view.View".className() val TEXT_VIEW = "android.widget.TextView".className() val ANY_RES = "android.support.annotation.AnyRes".className() val ARRAY_RES = "android.support.annotation.ArrayRes".className() val BOOL_RES = "android.support.annotation.BoolRes".className() val COLOR_INT = "android.support.annotation.ColorInt".className() val COLOR_RES = "android.support.annotation.ColorRes".className() val DIMEN_RES = "android.support.annotation.DimenRes".className() val DIMENSION = "android.support.annotation.Dimension".className() val DRAWABLE_RES = "android.support.annotation.DrawableRes".className() val FRACTION_RES = "android.support.annotation.FractionRes".className() val INTEGER_RES = "android.support.annotation.IntegerRes".className() val NULLABLE = "android.support.annotation.Nullable".className() val PX = "android.support.annotation.Px".className() val STRING_RES = "android.support.annotation.StringRes".className() val STYLE_RES = "android.support.annotation.StyleRes".className() val UI_THREAD = "android.support.annotation.UiThread".className() }
1
Kotlin
1
1
ba6cb89597e6632dddec065b4cb4eb266fe0a6d8
1,459
paris
Apache License 2.0
compiler/testData/klibABI/removeFunction/lib1/l1.kt
JetBrains
3,432,266
false
null
fun foo(): String = "FAIL1" fun exp_foo() = "FAIL2"
132
Kotlin
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
54
kotlin
Apache License 2.0
app/src/main/java/com/sample/openweathermap/ui/home/HomeFragment.kt
johnwahba84
251,644,591
false
null
package com.sample.openweathermap.ui.home import com.sample.openweathermap.BR import com.sample.openweathermap.R import com.sample.openweathermap.databinding.HomeFragmentBinding import com.sample.openweathermap.ui.base.BaseFragment class HomeFragment : BaseFragment<HomeFragmentBinding, HomeViewModel>() { override val bindingVariable: Int get() = BR.viewModel override val layoutId: Int get() = R.layout.home_fragment override val viewModel: Class<HomeViewModel> get() = HomeViewModel::class.java }
0
Kotlin
1
2
795ae47b6681d43c21df2e6e470c9e14a680e18b
541
weather-sample
Apache License 2.0
src/main/kotlin/com/deflatedpickle/heatfromfire/HeatAreaAffectEntity.kt
DeflatedPickle
441,885,686
false
{"Kotlin": 6738, "Java": 847}
/* Copyright (c) 2021-2022 DeflatedPickle under the MIT license */ package com.deflatedpickle.heatfromfire import com.google.common.collect.Lists import net.minecraft.entity.AreaEffectCloudEntity import net.minecraft.entity.Entity import net.minecraft.entity.EntityType import net.minecraft.entity.LivingEntity import net.minecraft.entity.effect.StatusEffectInstance import net.minecraft.particle.ParticleTypes import net.minecraft.sound.SoundCategory import net.minecraft.sound.SoundEvents import net.minecraft.world.World class HeatAreaAffectEntity( entityType: EntityType<HeatAreaAffectEntity>, world: World, ) : AreaEffectCloudEntity(entityType, world) { constructor( world: World, x: Double, y: Double, z: Double, ) : this(HeatFromFire.HEAT_AREA_EFFECT, world) { this.setPosition(x, y, z) } override fun tick() { if (age >= waitTime + duration) { discard() return } affectedEntities.entries.removeIf { (_, value): Map.Entry<Entity?, Int> -> age >= value } val i = Lists.newArrayList<StatusEffectInstance>() for (j in potion.effects) { i.add(StatusEffectInstance(j.effectType, j.duration / 4, j.amplifier, j.isAmbient, j.shouldShowParticles())) } i.addAll(effects) affectedEntities.clear() val g = world.getNonSpectatingEntities(LivingEntity::class.java, this.boundingBox) for (h in g) { var f = this.radius var q: Double var k: Double var r: Double if (affectedEntities.containsKey(h) || !h.isAffectedBySplashPotions || ( h.x - this.x.also { k = it } ) * k + (h.z - this.z.also { q = it }) * q.also { r = it } > (f * f).toDouble() ) continue affectedEntities[h] = age + reapplicationDelay for (n in i) { if (n.effectType.isInstant) { n.effectType.applyInstantEffect(this, owner, h, n.amplifier, 0.5) continue } h.addStatusEffect(StatusEffectInstance(n), this) } if (radiusOnUse != 0.0f) { if (radiusOnUse.let { f += it; f } < 0.5f) { discard() return } this.radius = f } if (durationOnUse == 0) continue duration += durationOnUse if (duration > 0) continue discard() return } if (random.nextInt(4) == 0) { val d = pos.getX() + random.nextDouble() val e = pos.getY() - 1.0 val f = pos.getZ() + random.nextDouble() world.addImportantParticle(ParticleTypes.SMOKE, d, e, f, 0.0, 0.0, 0.0) world.playSound( d, e, f, SoundEvents.ENTITY_BLAZE_BURN, SoundCategory.BLOCKS, 0.2f + random.nextFloat() * 0.2f, 0.9f + random.nextFloat() * 0.15f, false ) } } }
0
Kotlin
0
1
7103ebd4fd70a9fd42ea2ae4514d2fd2264b4522
3,169
HeatFromFire
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/iotanalytics/CfnPipelineDeviceShadowEnrichPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.iotanalytics import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.iotanalytics.CfnPipeline /** * An activity that adds information from the AWS IoT Device Shadows service to a message. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.iotanalytics.*; * DeviceShadowEnrichProperty deviceShadowEnrichProperty = DeviceShadowEnrichProperty.builder() * .attribute("attribute") * .name("name") * .roleArn("roleArn") * .thingName("thingName") * // the properties below are optional * .next("next") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html) */ @CdkDslMarker public class CfnPipelineDeviceShadowEnrichPropertyDsl { private val cdkBuilder: CfnPipeline.DeviceShadowEnrichProperty.Builder = CfnPipeline.DeviceShadowEnrichProperty.builder() /** @param attribute The name of the attribute that is added to the message. */ public fun attribute(attribute: String) { cdkBuilder.attribute(attribute) } /** @param name The name of the 'deviceShadowEnrich' activity. */ public fun name(name: String) { cdkBuilder.name(name) } /** @param next The next activity in the pipeline. */ public fun next(next: String) { cdkBuilder.next(next) } /** @param roleArn The ARN of the role that allows access to the device's shadow. */ public fun roleArn(roleArn: String) { cdkBuilder.roleArn(roleArn) } /** * @param thingName The name of the IoT device whose shadow information is added to the message. */ public fun thingName(thingName: String) { cdkBuilder.thingName(thingName) } public fun build(): CfnPipeline.DeviceShadowEnrichProperty = cdkBuilder.build() }
4
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
2,244
awscdk-dsl-kotlin
Apache License 2.0
architecture/src/androidMain/kotlin/observable/Subject.kt
splendo
191,371,940
false
null
/* Copyright 2022 Splendo Consulting B.V. The Netherlands 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. */ @file:JvmName("AndroidObservable") package com.splendo.kaluga.architecture.observable import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.asLiveData import com.splendo.kaluga.architecture.observable.ObservableOptional.Value import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext /** * The [Observer] that observes the observable value. */ val <R : T, T, OO : ObservableOptional<R>> BasicSubject<R, T, OO>.liveDataObserver: Observer<T> get() = Observer<T> { this.post(it) } private fun <B, R : T, T, OO : ObservableOptional<R>> B.mutableLiveData(): MutableLiveData<R> where B : BasicSubject<R, T, OO>, B : WithMutableState<R> { val mediatorLiveData = MediatorLiveData<R>() mediatorLiveData.addSource(stateFlow.asLiveData()) { value -> mediatorLiveData.postValue(value) } return mediatorLiveData } /** * Observes [LiveData] using an [Observer] on a [CoroutineScope] * @param coroutineScope The [CoroutineScope] on which to observe. * @param observer The [Observer] to observe the [LiveData] */ fun <T> LiveData<T>.observeOnCoroutine( coroutineScope: CoroutineScope, observer: Observer<T>, ) { // Live Data mutations should only ever be done from the main thread, so we don't (any longer) allow passing a context coroutineScope.launch(Dispatchers.Main.immediate) { val currentValue = value if (currentValue != null) observer.onChanged(currentValue) // due to slight delay in launch we could miss value changes observeForever(observer) awaitCancellation() }.invokeOnCompletion { removeObserver(observer) } } /** * An abstract class that extends [AbstractBaseSubject]. * @param T the type of value to expect. * @param R the type of result to expect. Must be a subclass of [T]. * @param OO the type of [ObservableOptional] to store the result in. * @param observation The [Observation] to handle observing the value. * @param stateFlowToBind A function to get the [StateFlow] that will automatically call [SuspendableSetter.set] when a new value is posted after [BasicSubject.post] has been called. */ actual abstract class BaseSubject<R : T, T, OO : ObservableOptional<R>> actual constructor( observation: Observation<R, T, OO>, stateFlowToBind: suspend () -> StateFlow<R?>, ) : AbstractBaseSubject<R, T, OO>(observation, stateFlowToBind) { private var coroutineScope: CoroutineScope? = null private val mutableLiveDataDelegate = lazy { createLiveData().also { coroutineScope?.let { coroutineScope -> it.observeOnCoroutine(coroutineScope, observer = liveDataObserver()) } } } /** * The [MutableLiveData] synchronizing the value of the subject. */ val mutableLiveData by mutableLiveDataDelegate protected abstract fun createLiveData(): MutableLiveData<R> /** * Gets an [Observer] to observe changes to this subject. */ abstract fun liveDataObserver(): Observer<R> final override fun bind(coroutineScope: CoroutineScope, context: CoroutineContext) { super.bind(coroutineScope, context) this.coroutineScope = coroutineScope if (mutableLiveDataDelegate.isInitialized()) { mutableLiveData.observeOnCoroutine(coroutineScope, observer = liveDataObserver()) } } } /** * An abstract class extending [AbstractBaseUninitializedSubject]. * @param T the type of value to expect. * @param observation The [ObservationUninitialized] to handle value being observed */ actual abstract class BaseUninitializedSubject<T> actual constructor( observation: ObservationUninitialized<T>, ) : AbstractBaseUninitializedSubject<T>(observation) { override fun createLiveData(): MutableLiveData<T> { val mediatorLiveData = MediatorLiveData<T>() mediatorLiveData.addSource(stateFlow.asLiveData()) { value -> mediatorLiveData.postValue(value) } return mediatorLiveData } override fun liveDataObserver() = Observer<T> { value -> value?.let { post(it) } } } /** * Abstract class implementing [AbstractBaseInitializedSubject] * @param T the type of value to expect. * @param observation The [ObservationInitialized] to handle value being observed */ actual abstract class BaseInitializedSubject<T> actual constructor(observation: ObservationInitialized<T>) : AbstractBaseInitializedSubject<T>(observation) { override fun createLiveData(): MutableLiveData<T> = this.mutableLiveData() override fun liveDataObserver() = liveDataObserver /** * Constructor using an inital value. * @param initialValue The [Value] to use as the initial value. */ actual constructor( initialValue: Value<T>, ) : this (ObservationInitialized(initialValue)) } /** * An abstract class extending [AbstractBaseDefaultSubject]. * @param T the type of value to expect. * @param R the type of result to expect. Must be a subclass of [T] * @param observation The [ObservationUninitialized] to handle value being observed */ actual abstract class BaseDefaultSubject<R : T?, T> actual constructor( observation: ObservationDefault<R, T?>, ) : AbstractBaseDefaultSubject<R, T>(observation) { override fun createLiveData(): MutableLiveData<R> = this.mutableLiveData() override fun liveDataObserver() = Observer<R> { post(it) } /** * Constructor * @param defaultValue The default [Value] of [R] to return if the current value is [ObservableOptional.Nothing] or [ObservableOptional.Value] containing `null`. * @param initialValue The initial [Value] of [T]. */ actual constructor( defaultValue: Value<R>, initialValue: Value<T?>, ) : this(observation = ObservationDefault<R, T?>(defaultValue, initialValue)) }
87
null
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
6,741
kaluga
Apache License 2.0
src/main/kotlin/no/nav/familie/baks/mottak/søknad/SøknadSpråkvelgerService.kt
navikt
221,166,975
false
{"Kotlin": 490956, "Java": 28936, "Dockerfile": 165}
package no.nav.familie.baks.mottak.søknad import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.convertValue import no.nav.familie.baks.mottak.søknad.barnetrygd.BarnetrygdSøknadObjectMapperModule import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.SøknadV7 import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.SøknadV8 import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.VersjonertSøknad import no.nav.familie.baks.mottak.søknad.kontantstøtte.KontantstøtteObjectMapperModule import no.nav.familie.baks.mottak.søknad.kontantstøtte.domene.KontantstøtteSøknadV3 import no.nav.familie.baks.mottak.søknad.kontantstøtte.domene.KontantstøtteSøknadV4 import no.nav.familie.baks.mottak.søknad.kontantstøtte.domene.VersjonertKontantstøtteSøknad import org.springframework.stereotype.Service import no.nav.familie.kontrakter.felles.objectMapper as getObjectMapper @Service class SøknadSpråkvelgerService { fun konverterBarnetrygdSøknadTilMapForSpråk(versjonertSøknad: VersjonertSøknad, språk: String): Map<String, Any> { val objectMapperForSpråk = hentObjectMapperForSpråk(språk) val barnetrygdSøknadMapForSpråk = objectMapperForSpråk.convertValue<MutableMap<String, Any>>( when (versjonertSøknad) { is SøknadV7 -> versjonertSøknad.søknad is SøknadV8 -> versjonertSøknad.søknad }, ) barnetrygdSøknadMapForSpråk["teksterUtenomSpørsmål"] = when (versjonertSøknad) { is SøknadV7 -> versjonertSøknad.søknad.teksterUtenomSpørsmål is SøknadV8 -> versjonertSøknad.søknad.teksterUtenomSpørsmål }.mapValues { it.value[språk] } return barnetrygdSøknadMapForSpråk } fun konverterKontantstøtteSøknadTilMapForSpråk( versjonertSøknad: VersjonertKontantstøtteSøknad, språk: String, ): Map<String, Any> { val objectMapperForSpråk = hentObjectMapperForSpråk(språk) val kontantstøtteSøknadMapForSpråk = objectMapperForSpråk.convertValue<MutableMap<String, Any>>( when (versjonertSøknad) { is KontantstøtteSøknadV3 -> versjonertSøknad.kontantstøtteSøknad is KontantstøtteSøknadV4 -> versjonertSøknad.kontantstøtteSøknad }, ) return kontantstøtteSøknadMapForSpråk } fun hentObjectMapperForSpråk(språk: String): ObjectMapper { return getObjectMapper.registerModules( BarnetrygdSøknadObjectMapperModule(språk), KontantstøtteObjectMapperModule(språk), ) } }
2
Kotlin
0
2
bfac42357de00b5f0c7685b7d952fc97cf4eb3eb
2,592
familie-baks-mottak
MIT License
app/src/main/java/com/example/ayurveda/Map.kt
ImeshPasinda
691,128,876
false
{"Kotlin": 197079}
package com.example.ayurveda import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.example.ayurveda.databinding.ActivityMapBinding import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.Marker import com.squareup.picasso.Picasso class Map : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var binding: ActivityMapBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMapBinding.inflate(layoutInflater) setContentView(binding.root) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val latitude = intent.getDoubleExtra("latitude", 0.0) // 0.0 is the default value if not found val longitude = intent.getDoubleExtra("longitude", 0.0) val docAddress = intent.getStringExtra("docAddress") val docNameEn = intent.getStringExtra("docNameEn") val avatarUrl = intent.getStringExtra("avatarUrl") // Add a marker in your desired location val location = LatLng(latitude, longitude) // Create a BitmapDescriptor from the image resource val markerBitmap = BitmapFactory.decodeResource(resources, R.drawable.mapmarker) val resizedMarkerBitmap = Bitmap.createScaledBitmap(markerBitmap, 100, 100, false) val markerIcon = BitmapDescriptorFactory.fromBitmap(resizedMarkerBitmap) val markerOptions = MarkerOptions() .position(location) .title(docNameEn) .snippet(docAddress) .icon(markerIcon) .anchor(0.5f, 0.5f) // Center the marker on the specified position // Add the marker to the map val marker = mMap.addMarker(markerOptions) // Set a custom info window adapter for the marker mMap.setInfoWindowAdapter(object : GoogleMap.InfoWindowAdapter { override fun getInfoWindow(marker: Marker): View? { // Return null to use the default info window return null } override fun getInfoContents(marker: Marker): View { // Inflate your custom info window layout val view = layoutInflater.inflate(R.layout.mapcardview, null) // Find the ImageView and TextView in the layout val avatarImageView = view.findViewById<ImageView>(R.id.avatarMap) val descriptionTextView = view.findViewById<TextView>(R.id.doctorDesMap) val titleTextView = view.findViewById<TextView>(R.id.doctorNameMap) // Set the image and description Picasso.get().load(avatarUrl).into(avatarImageView) descriptionTextView.text = marker.snippet titleTextView.text = marker.title return view } }) // Set the default zoom level val zoomLevel = 10f mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel)) } }
0
Kotlin
2
0
f6bae07d00985e20c417272d528266671a3b9d2e
3,831
Ayurveda
MIT License
src/main/kotlin/net/casual/arcade/minigame/task/impl/SidebarTask.kt
CasualChampionships
621,955,934
false
null
package net.casual.arcade.gui.task import net.casual.arcade.gui.sidebar.ArcadeSidebar import net.casual.arcade.minigame.Minigame import net.casual.arcade.task.Task public open class SidebarTask( private val minigame: Minigame<*>, sidebar: ArcadeSidebar ): Task { init { this.minigame.ui.setSidebar(sidebar) } override fun run() { this.minigame.ui.removeSidebar() } }
1
null
1
2
01bad4fba0eb3ea13acef4cec7432c5d6877968f
409
arcade
MIT License
browser-kotlin/src/jsMain/kotlin/web/authn/AuthenticationExtensionsClientInputs.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.authn import kotlinx.js.JsPlainObject @JsPlainObject external interface AuthenticationExtensionsClientInputs { val appid: String? val credProps: Boolean? val hmacCreateSecret: Boolean? val minPinLength: Boolean? val prf: AuthenticationExtensionsPRFInputs? }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
337
types-kotlin
Apache License 2.0
kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/resolved/KSTypeReferenceResolvedImpl.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
/* * Copyright 2022 Google LLC * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.impl.symbol.kotlin.resolved import com.google.devtools.ksp.common.IdKeyTriple import com.google.devtools.ksp.common.KSObjectCache import com.google.devtools.ksp.impl.recordLookup import com.google.devtools.ksp.impl.symbol.kotlin.Deferrable import com.google.devtools.ksp.impl.symbol.kotlin.KSClassDeclarationImpl import com.google.devtools.ksp.impl.symbol.kotlin.KSTypeImpl import com.google.devtools.ksp.impl.symbol.kotlin.KSTypeParameterImpl import com.google.devtools.ksp.impl.symbol.kotlin.Restorable import com.google.devtools.ksp.impl.symbol.kotlin.analyze import com.google.devtools.ksp.impl.symbol.kotlin.annotations import com.google.devtools.ksp.impl.symbol.kotlin.render import com.google.devtools.ksp.impl.symbol.kotlin.toClassifierReference import com.google.devtools.ksp.impl.symbol.kotlin.toLocation import com.google.devtools.ksp.symbol.* import com.intellij.psi.PsiClass import com.intellij.psi.PsiTypeParameter import com.intellij.psi.impl.source.PsiClassReferenceType import org.jetbrains.kotlin.analysis.api.annotations.KaAnnotation import org.jetbrains.kotlin.analysis.api.types.* import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtTypeParameter class KSTypeReferenceResolvedImpl private constructor( private val ktType: KaType, override val parent: KSNode?, private val index: Int, private val additionalAnnotations: List<KaAnnotation> ) : KSTypeReference, Deferrable { companion object : KSObjectCache<IdKeyTriple<KaType, KSNode?, Int>, KSTypeReference>() { fun getCached( type: KaType, parent: KSNode? = null, index: Int = -1, additionalAnnotations: List<KaAnnotation> = emptyList() ): KSTypeReference = cache.getOrPut(IdKeyTriple(type, parent, index)) { KSTypeReferenceResolvedImpl(type, parent, index, additionalAnnotations) } } override val element: KSReferenceElement? by lazy { // FIXME: synthetic elements can have non-synthetic annotations via use-site targets if (parent == null || parent.origin == Origin.SYNTHETIC) { null } else { ktType.toClassifierReference(this) } } override fun resolve(): KSType { analyze { recordLookup(ktType, parent) } return KSTypeImpl.getCached(ktType) } override val annotations: Sequence<KSAnnotation> by lazy { ktType.annotations(this) + additionalAnnotations.asSequence().map { KSAnnotationResolvedImpl.getCached(it, this) } } override val origin: Origin = parent?.origin ?: Origin.SYNTHETIC override val location: Location by lazy { if (index <= -1) { parent?.location ?: NonExistLocation } else { when (parent) { is KSClassDeclarationImpl -> { when (val psi = parent.ktClassOrObjectSymbol.psi) { is KtClassOrObject -> psi.superTypeListEntries[index].toLocation() is PsiClass -> (psi as? PsiClassReferenceType)?.reference?.toLocation() ?: NonExistLocation else -> NonExistLocation } } is KSTypeParameterImpl -> { when (val psi = parent.ktTypeParameterSymbol.psi) { is KtTypeParameter -> parent.location is PsiTypeParameter -> (psi.extendsListTypes[index] as? PsiClassReferenceType) ?.reference?.toLocation() ?: NonExistLocation else -> NonExistLocation } } else -> NonExistLocation } } } override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitTypeReference(this, data) } override val modifiers: Set<Modifier> get() = if (ktType is KaFunctionType && ktType.isSuspend) { setOf(Modifier.SUSPEND) } else { emptySet() } override fun toString(): String { return ktType.render() } override fun defer(): Restorable? { TODO("Not yet implemented") } }
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
4,939
ksp
Apache License 2.0
cpg-core/src/main/kotlin/de/fraunhofer/aisec/cpg/passes/DynamicInvokeResolver.kt
Fraunhofer-AISEC
225,386,107
false
null
/* * Copyright (c) 2022, Fraunhofer AISEC. All rights reserved. * * 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 de.fraunhofer.aisec.cpg.passes import de.fraunhofer.aisec.cpg.IncompatibleSignature import de.fraunhofer.aisec.cpg.TranslationContext import de.fraunhofer.aisec.cpg.graph.AccessValues import de.fraunhofer.aisec.cpg.graph.Component import de.fraunhofer.aisec.cpg.graph.Node import de.fraunhofer.aisec.cpg.graph.declarations.FieldDeclaration import de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration import de.fraunhofer.aisec.cpg.graph.declarations.ParameterDeclaration import de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration import de.fraunhofer.aisec.cpg.graph.edge.FullDataflowGranularity import de.fraunhofer.aisec.cpg.graph.edge.Properties import de.fraunhofer.aisec.cpg.graph.pointer import de.fraunhofer.aisec.cpg.graph.statements.expressions.* import de.fraunhofer.aisec.cpg.graph.types.FunctionPointerType import de.fraunhofer.aisec.cpg.graph.types.FunctionType import de.fraunhofer.aisec.cpg.graph.types.ProblemType import de.fraunhofer.aisec.cpg.helpers.SubgraphWalker.ScopedWalker import de.fraunhofer.aisec.cpg.helpers.identitySetOf import de.fraunhofer.aisec.cpg.matchesSignature import de.fraunhofer.aisec.cpg.passes.configuration.DependsOn import java.util.* import java.util.function.Consumer /** * This [Pass] is responsible for resolving dynamic function invokes, i.e., [CallExpression] nodes * that contain a reference/pointer to a function and are being "called". A common example includes * C/C++ function pointers. * * This pass is intentionally split from the [SymbolResolver] because it depends on DFG edges. This * split allows the [SymbolResolver] to be run before any DFG passes, which in turn allow us to also * populate DFG passes for inferred functions. */ @DependsOn(SymbolResolver::class) @DependsOn(DFGPass::class) @DependsOn(ControlFlowSensitiveDFGPass::class, softDependency = true) class DynamicInvokeResolver(ctx: TranslationContext) : ComponentPass(ctx) { private lateinit var walker: ScopedWalker private var inferDfgForUnresolvedCalls = false override fun accept(component: Component) { inferDfgForUnresolvedCalls = config.inferenceConfiguration.inferDfgForUnresolvedSymbols walker = ScopedWalker(scopeManager) walker.registerHandler { node, _ -> handle(node) } for (tu in component.translationUnits) { walker.iterate(tu) } } private fun handle(node: Node?) { when (node) { is MemberCallExpression -> handleMemberCallExpression(node) is CallExpression -> handleCallExpression(node) } } /** * Resolves function pointers in a [CallExpression] node. As long as the [CallExpression.callee] * has a [FunctionPointerType], we should be able to resolve it. */ private fun handleCallExpression(call: CallExpression) { val callee = call.callee if ( callee?.type is FunctionPointerType || ((callee as? Reference)?.refersTo is ParameterDeclaration || (callee as? Reference)?.refersTo is VariableDeclaration) ) { handleCallee(call, callee) } } /** * Resolves function pointers in a [MemberCallExpression]. In this case the * [MemberCallExpression.callee] field is a binary operator on which [BinaryOperator.rhs] needs * to have a [FunctionPointerType]. */ private fun handleMemberCallExpression(call: MemberCallExpression) { val callee = call.callee if (callee is BinaryOperator && callee.rhs.type is FunctionPointerType) { handleCallee(call, callee.rhs) } } private fun handleCallee(call: CallExpression, expr: Expression) { // For now, we harmonize all types to the FunctionPointerType. In the future, we want to get // rid of FunctionPointerType and only deal with FunctionTypes. val pointerType: FunctionPointerType = when (val type = expr.type) { is FunctionType -> { when (val pointerType = type.pointer()) { is FunctionPointerType -> pointerType is ProblemType -> { log.warn("Function has unexpected type: ProblemType; ignore call") return } else -> { log.warn("Unexpected function type: ${pointerType}; ignore call") return } } } is FunctionPointerType -> type else -> { // some languages allow other types to derive from a function type, in this case // we need to look for a super type val superType = type.superTypes.singleOrNull() if (superType is FunctionType) { superType.pointer() as FunctionPointerType } else { return } } } val invocationCandidates = mutableListOf<FunctionDeclaration>() val work: Deque<Node> = ArrayDeque() val seen = identitySetOf<Node>() work.push(expr) while (work.isNotEmpty()) { val curr = work.pop() if (!seen.add(curr)) { continue } val isLambda = curr is VariableDeclaration && curr.initializer is LambdaExpression val currentFunction = if (isLambda) { ((curr as VariableDeclaration).initializer as LambdaExpression).function } else { curr } if (currentFunction is FunctionDeclaration) { // Even if it is a function declaration, the dataflow might just come from a // situation where the target of a fptr is passed through via a return value. Keep // searching if return type or signature don't match val functionPointerType = currentFunction.type.pointer() if ( isLambda && currentFunction.returnTypes.isEmpty() && currentFunction.matchesSignature(pointerType.parameters) != IncompatibleSignature ) { invocationCandidates.add(currentFunction) continue } else if (functionPointerType == pointerType) { invocationCandidates.add(currentFunction) // We have found a target. Don't follow this path any further, but still // continue the other paths that might be left, as we could have several // potential targets at runtime continue } } // Do not consider the base for member expressions, we have to know possible values of // the member (e.g. field). val prevDFGToPush = curr.prevDFGEdges .filter { it.granularity is FullDataflowGranularity } .map { it.start } .toMutableList() if (curr is MemberExpression && prevDFGToPush.isEmpty()) { // TODO: This is only a workaround! // If there is nothing found for MemberExpressions, we may have set the field // somewhere else but do not yet propagate this to this location (e.g. because it // happens in another function). In this case, we look at write-usages to the // field and use all of those. This is only a temporary workaround until someone // implements an interprocedural analysis (for example). (curr.refersTo as? FieldDeclaration) ?.usages ?.filter { it.access == AccessValues.WRITE || it.access == AccessValues.READWRITE } ?.let { prevDFGToPush.addAll(it) } // Also add the initializer of the field (if it exists) (curr.refersTo as? FieldDeclaration)?.initializer?.let { prevDFGToPush.add(it) } } prevDFGToPush.forEach(Consumer(work::push)) } call.invokes = invocationCandidates call.invokeEdges.forEach { it.addProperty(Properties.DYNAMIC_INVOKE, true) } // We have to update the dfg edges because this call could now be resolved (which was not // the case before). DFGPass(ctx).handleCallExpression(call, inferDfgForUnresolvedCalls) } override fun cleanup() { // Nothing to do } }
94
null
62
281
4b2d95b66ccd87ac7e97e1f23ace67265a533ab8
9,852
cpg
Apache License 2.0
Navitas-Plugin/src/main/kotlin/tooling/PowerProfileManager.kt
Stanislav-Sartasov
195,064,379
false
null
package tooling import domain.model.CpuCoreCluster import domain.model.PowerProfile class PowerProfileManager { // default profile initialization companion object { private const val defaultWifiOn = 0.1f private const val defaultWifiScan = 0.1f private const val defaultWifiActive = 0.1f private const val defaultBluetoothOn = 0.1f private const val defaultBluetoothActive = 0.1f private val defaultClusterFirst = CpuCoreCluster(4) private val defaultClusterSecond = CpuCoreCluster(4) // These values are taken from some device, so they are not default. // This is justified by the fact that this is the only way to calculate approximate values. init { defaultClusterFirst.speeds.add(400000) defaultClusterFirst.speeds.add(691200) defaultClusterFirst.speeds.add(806400) defaultClusterFirst.speeds.add(1017600) defaultClusterFirst.speeds.add(1190400) defaultClusterFirst.speeds.add(1305600) defaultClusterFirst.speeds.add(1382400) defaultClusterFirst.speeds.add(1401600) defaultClusterFirst.powers.add(45.21F) defaultClusterFirst.powers.add(53.6F) defaultClusterFirst.powers.add(58.13F) defaultClusterFirst.powers.add(69.04F) defaultClusterFirst.powers.add(93.88F) defaultClusterFirst.powers.add(101.37F) defaultClusterFirst.powers.add(105.93F) defaultClusterFirst.powers.add(109.05F) defaultClusterSecond.speeds.add(400000) defaultClusterSecond.speeds.add(883200) defaultClusterSecond.speeds.add(940800) defaultClusterSecond.speeds.add(998400) defaultClusterSecond.speeds.add(1056000) defaultClusterSecond.speeds.add(1113600) defaultClusterSecond.speeds.add(1190400) defaultClusterSecond.speeds.add(1248000) defaultClusterSecond.speeds.add(1305600) defaultClusterSecond.speeds.add(1382400) defaultClusterSecond.speeds.add(1612800) defaultClusterSecond.speeds.add(1747200) defaultClusterSecond.speeds.add(1804800) defaultClusterSecond.powers.add(77.22F) defaultClusterSecond.powers.add(110.86F) defaultClusterSecond.powers.add(118.68F) defaultClusterSecond.powers.add(122.8F) defaultClusterSecond.powers.add(127.32F) defaultClusterSecond.powers.add(133.2F) defaultClusterSecond.powers.add(144.33F) defaultClusterSecond.powers.add(159.41F) defaultClusterSecond.powers.add(164.03F) defaultClusterSecond.powers.add(172.87F) defaultClusterSecond.powers.add(232.71F) defaultClusterSecond.powers.add(258.17F) defaultClusterSecond.powers.add(275.35F) } private val defaultProfile = PowerProfile ( "Default Profile", arrayListOf(defaultClusterFirst, defaultClusterSecond), defaultWifiOn, defaultWifiScan, defaultWifiActive, defaultBluetoothOn, defaultBluetoothActive ) fun getDefaultProfile(): PowerProfile { return defaultProfile } } }
6
Kotlin
2
6
4695911381911c9dab53c0aebe584eb6327b75fd
3,368
Navitas-Framework
MIT License
app/src/main/java/com/example/androiddevchallenge/model/Dog.kt
sonatard
342,777,592
true
{"Kotlin": 33513}
/* * 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.model import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Female import androidx.compose.material.icons.filled.Male import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.tooling.preview.datasource.LoremIpsum import com.example.androiddevchallenge.R enum class Sex { FEMALE, MALE; fun icon(): ImageVector { return when (this) { MALE -> Icons.Filled.Male FEMALE -> Icons.Filled.Female } } } data class DogModel( val id: String, val name: String, val sex: Sex, val age: Int, // month val image: Int, val place: String = "USA", val description: String = LoremIpsum(70).values.toList().joinToString(" ").replace("\n", ""), val favorite: Boolean = false, ) { override fun toString(): String { return "$id: $name $age month $place $description $favorite " } } val dogList = listOf( DogModel( id = "1", name = "Abby", sex = Sex.FEMALE, age = 10, image = R.drawable.dog1, ), DogModel( id = "2", name = "Bruno", sex = Sex.FEMALE, age = 20, image = R.drawable.dog2, place = "Japan", ), DogModel( id = "3", name = "Hunter", sex = Sex.FEMALE, age = 30, image = R.drawable.dog3, ), DogModel( id = "4", name = "Otis", sex = Sex.FEMALE, age = 40, image = R.drawable.dog4, ), DogModel( id = "5", name = "Roscoe", sex = Sex.FEMALE, age = 50, image = R.drawable.dog5, ), DogModel( id = "6", name = "Abby", sex = Sex.FEMALE, age = 60, image = R.drawable.dog6, place = "Japan", ), DogModel( id = "7", name = "Jasper", sex = Sex.FEMALE, age = 70, image = R.drawable.dog7, place = "Japan", ), DogModel( id = "8", name = "Samson", sex = Sex.FEMALE, age = 80, image = R.drawable.dog8, place = "Japan", ), DogModel( id = "9", name = "Abby", sex = Sex.FEMALE, age = 90, image = R.drawable.dog9, place = "Japan", ), DogModel( id = "10", name = "Oliver", sex = Sex.FEMALE, age = 90, image = R.drawable.dog10, place = "Japan", ), DogModel( id = "10", name = "Copper", sex = Sex.FEMALE, age = 90, image = R.drawable.dog11, ), ) val dogMap = dogList.map { it.id to it }.toMap()
0
Kotlin
0
0
1ad55a1d4ea77959c097dabee78936fef3b99038
3,351
android-dev-challenge-compose
Apache License 2.0
app/src/main/java/com/julive/adapter_demo/video/VideoListActivity.kt
bagutree
378,672,502
false
null
package com.julive.adapter_demo.video import android.annotation.SuppressLint import android.os.Build import android.os.Bundle import android.util.Log import android.widget.ImageView import android.widget.TextView import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.* import com.julive.adapter.animators.findFirstCompletelyVisibleItemPosition import com.julive.adapter.animators.firstAnimation import com.julive.adapter.core.* import com.julive.adapter_demo.R import com.julive.adapter_demo.sorted.ModelVideoTest import com.shuyu.gsyvideoplayer.GSYVideoManager import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer import kotlinx.android.synthetic.main.activity_video_list.* import kotlinx.android.synthetic.main.item_test_video_view.view.* import org.jetbrains.anko.backgroundColorResource class VideoListActivity : AppCompatActivity() { private val mp4_a = "http://vfx.mtime.cn/Video/2019/03/19/mp4/190319212559089721.mp4"; private val mp4_b = "http://vfx.mtime.cn/Video/2019/03/13/mp4/190313094901111138.mp4"; private val gsyVideoOptionBuilder = GSYVideoOptionBuilder().apply { setIsTouchWiget(false) setVideoTitle("title") setCacheWithPlay(true) setRotateViewAuto(true) setLockLand(false) setShowFullAnimation(true) setReleaseWhenLossAudio(false) } @SuppressLint("NewApi") private val mListAdapter = listAdapter { (0..100).forEach { _ -> add( layoutViewModelDsl( R.layout.item_test_video_view, ModelVideoTest(mp4_b, mp4_a, -1) ) { val player = getView<StandardGSYVideoPlayer>(R.id.player) val title = getView<TextView>(R.id.tv_title) val subTitle = getView<TextView>(R.id.tv_subTitle) player.fullscreenButton.setOnClickListener { player.startWindowFullscreen(itemView.context, false, true) } player.isAutoFullWithSize = true onViewAttachedToWindow { firstAnimation() } onBindViewHolder { val model = getModel<ModelVideoTest>() if (it.isEmpty()) { title.text = "title$adapterPosition" subTitle.text = "sutTitle" gsyVideoOptionBuilder.apply { if (adapterPosition % 2 == 0) { setUrl(model?.url) } else { setUrl(model?.url2) } setPlayPosition(adapterPosition) setPlayTag(adapterPosition.toString()) setGSYVideoProgressListener { progress, secProgress, currentPosition, duration -> model?.seekOnStart = currentPosition.toLong() } setThumbImageView(ImageView(itemView.context).apply { backgroundColorResource = R.color.colorAccent layoutParams = player.layoutParams }) }.build(player) } it.takeIf { it.isNotEmpty() && it[0] == 1 }?.also { player.seekOnStart = model?.seekOnStart ?: -1 player.startPlayLogic() } } }) } } @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_video_list) // PlayerFactory.setPlayManager(Exo2PlayerManager::class.java) // exo缓存模式,支持m3u8,只支持exo // CacheFactory.setCacheManager(ExoPlayerCacheManager::class.java) //切换渲染模式 // GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL) mListAdapter.into(rv_list_video) var currentPlayingPosition = 0 rv_list_video.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) when (newState) { SCROLL_STATE_IDLE -> { val position = rv_list_video.findFirstCompletelyVisibleItemPosition() Log.d("ScrollChange", "position:$position") if (currentPlayingPosition != position) { currentPlayingPosition = position mListAdapter.notifyItemChanged(position, 1) } } } } }) rv_list_video.postDelayed({ mListAdapter.notifyItemChanged(currentPlayingPosition, 1) }, 1000) } override fun onBackPressed() { if (GSYVideoManager.backFromWindowFull(this)) { return } super.onBackPressed() } override fun onPause() { super.onPause() GSYVideoManager.onPause() } override fun onResume() { super.onResume() GSYVideoManager.onResume() } override fun onDestroy() { super.onDestroy() GSYVideoManager.releaseAllVideos() } }
0
null
25
4
5c6f6952ac2475616a7b12020c42d830b1ccb5b2
6,189
RecyclerViewAdapter
Apache License 2.0
app/src/main/java/dev/debaleen/foodrunner/adapter/FAQAdapter.kt
the-it-weirdo
279,097,648
false
null
package dev.debaleen.foodrunner.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import dev.debaleen.foodrunner.R import dev.debaleen.foodrunner.model.FAQModel class FAQAdapter( private val faqsList: ArrayList<FAQModel> ) : RecyclerView.Adapter<FAQAdapter.FAQViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FAQViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.faq_item, parent, false) return FAQViewHolder(view) } override fun getItemCount(): Int { return faqsList.size } override fun onBindViewHolder(holder: FAQViewHolder, position: Int) { val faq = faqsList[position] holder.bind(faq, position) } class FAQViewHolder(private val view: View) : RecyclerView.ViewHolder(view) { private val txtQuestion: TextView = view.findViewById(R.id.txtQuestion) private val txtAnswer: TextView = view.findViewById(R.id.txtAnswer) fun bind(faqUiModel: FAQModel, position: Int) { txtQuestion.text = view.context.getString( R.string.question_template, position + 1, faqUiModel.question ) txtAnswer.text = view.context.getString(R.string.answer_template, faqUiModel.answer) } } }
1
Kotlin
5
2
56b10c9904cabad0e313f5134d5b2131d53bfa5e
1,469
Foodzzy
MIT License
kobweb/src/main/kotlin/com/varabyte/kobweb/cli/create/freemarker/FreemarkerState.kt
varabyte
626,735,789
false
null
package com.varabyte.kobweb.cli.create.freemarker import com.varabyte.kobweb.cli.common.informInfo import com.varabyte.kobweb.cli.common.processing import com.varabyte.kobweb.cli.common.queryUser import com.varabyte.kobweb.cli.common.template.Instruction import com.varabyte.kobweb.cli.common.wildcardToRegex import com.varabyte.kobweb.cli.create.freemarker.methods.FileToPackageMethod import com.varabyte.kobweb.cli.create.freemarker.methods.FileToTitleMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsIntMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsNotEmptyMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsNumberMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsPackageMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsPositiveIntMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsPositiveNumberMethod import com.varabyte.kobweb.cli.create.freemarker.methods.IsYesNoMethod import com.varabyte.kobweb.cli.create.freemarker.methods.PackageToPathMethod import com.varabyte.kobweb.cli.create.freemarker.methods.YesNoToBoolMethod import com.varabyte.kobweb.common.error.KobwebException import com.varabyte.kobweb.common.path.toUnixSeparators import com.varabyte.kotter.runtime.Session import freemarker.cache.NullCacheStorage import freemarker.template.Configuration import freemarker.template.Template import freemarker.template.TemplateExceptionHandler import freemarker.template.TemplateMethodModelEx import java.io.File import java.io.FileWriter import java.io.StringReader import java.io.StringWriter import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.createDirectories import kotlin.io.path.isRegularFile import kotlin.io.path.name import kotlin.io.path.notExists private fun String.process(cfg: Configuration, model: Map<String, Any>): String { val reader = StringReader(this) val writer = StringWriter() Template("unused", reader, cfg).process(model, writer) return writer.buffer.toString() } class FreemarkerState(private val src: Path, private val dest: Path) { private val model = mutableMapOf( "projectFolder" to dest.name, // region Validators "isInt" to IsIntMethod(), // Added in 0.9.13 "isNotEmpty" to IsNotEmptyMethod(), "isNumber" to IsNumberMethod(), // Added in 0.9.13 "isPackage" to IsPackageMethod(), "isPositiveInt" to IsPositiveIntMethod(), // Added in 0.9.13 "isPositiveNumber" to IsPositiveNumberMethod(), // Added in 0.9.13 "isYesNo" to IsYesNoMethod(), // endregion // region Converters "fileToTitle" to FileToTitleMethod(), "fileToPackage" to FileToPackageMethod(), "packageToPath" to PackageToPathMethod(), "yesNoToBool" to YesNoToBoolMethod(), // endregion ) // See also: https://freemarker.apache.org/docs/pgui_quickstart_all.html private val cfg = Configuration(Configuration.VERSION_2_3_31).apply { setDirectoryForTemplateLoading(src.toFile()) // Kobweb doesn't serve templates - it just runs through files once. No need to cache. cacheStorage = NullCacheStorage() defaultEncoding = "UTF-8" templateExceptionHandler = TemplateExceptionHandler.RETHROW_HANDLER logTemplateExceptions = false wrapUncheckedExceptions = true fallbackOnNullLoopVariable = false } private fun Session.process(instructions: Iterable<Instruction>) { for (inst in instructions) { val useInstruction = inst.condition?.process(cfg, model)?.toBoolean() ?: true if (!useInstruction) continue when (inst) { is Instruction.Group -> { process(inst.instructions) } is Instruction.Inform -> { val message = inst.message.process(cfg, model) informInfo(message) } is Instruction.QueryVar -> { val default = inst.default?.process(cfg, model) val answer = queryUser(inst.prompt, default, validateAnswer = { value -> (model[inst.validation] as? TemplateMethodModelEx)?.exec(listOf(value))?.toString() }) val finalAnswer = inst.transform?.let { transform -> val modelWithValue = model.toMutableMap() modelWithValue["value"] = answer transform.process(cfg, modelWithValue) } ?: answer model[inst.name] = finalAnswer } is Instruction.DefineVar -> { model[inst.name] = inst.value.process(cfg, model) } is Instruction.ProcessFreemarker -> { processing("Processing templates") { val srcFile = src.toFile() val filesToProcess = mutableListOf<File>() srcFile.walkBottomUp().forEach { file -> if (file.extension == "ftl") { filesToProcess.add(file) } } filesToProcess.forEach { templateFile -> val template = cfg.getTemplate(templateFile.toRelativeString(srcFile)) FileWriter(templateFile.path.removeSuffix(".ftl")).use { writer -> template.process(model, writer) } templateFile.delete() } } } is Instruction.Move -> { val to = inst.to.process(cfg, model) processing(inst.description ?: "Moving \"${inst.from}\" to \"$to\"") { val matcher = inst.from.wildcardToRegex() val srcFile = src.toFile() val filesToMove = mutableListOf<File>() srcFile.walkBottomUp().forEach { file -> // Matcher expects *nix paths; make sure this check works on Windows if (matcher.matches(file.toRelativeString(srcFile).toUnixSeparators())) { filesToMove.add(file) } } val destPath = src.resolve(to) if (destPath.notExists()) { destPath.createDirectories() } else if (destPath.isRegularFile()) { throw KobwebException("Cannot move files into target that isn't a directory") } filesToMove.forEach { fileToMove -> Files.move(fileToMove.toPath(), destPath.resolve(fileToMove.name)) } } } is Instruction.Rename -> { val name = inst.name.process(cfg, model) processing(inst.description ?: "Renaming \"${inst.file}\" to \"$name\"") { val srcFile = src.toFile() val fileToRename = srcFile.resolve(inst.file) if (!fileToRename.exists()) { throw KobwebException("Cannot rename a file (${inst.file}) because it does not exist") } // If the rename isn't actually changing anything, technically we're done if (fileToRename.name != name) { val targetFile = fileToRename.resolveSibling(name) if (targetFile.exists()) { throw KobwebException("Cannot rename a file (${inst.file}) because the rename target ($targetFile) already exists") } fileToRename.renameTo(targetFile) } } } is Instruction.Delete -> { processing(inst.description ?: "Deleting \"${inst.files}\"") { val deleteMatcher = inst.files.wildcardToRegex() val srcFile = src.toFile() val filesToDelete = mutableListOf<File>() srcFile.walkBottomUp().forEach { file -> // Matcher expects *nix paths; make sure this check works on Windows val relativePath = file.toRelativeString(srcFile).toUnixSeparators() if (deleteMatcher.matches(relativePath)) { filesToDelete.add(file) } } filesToDelete.forEach { fileToDelete -> fileToDelete.deleteRecursively() } } } } } } fun execute(app: Session, instructions: List<Instruction>) { app.apply { process(instructions) processing("Nearly finished. Populating final project") { val srcFile = src.toFile() val files = mutableListOf<File>() srcFile.walkBottomUp().forEach { file -> if (file.isFile) { files.add(file) } } files.forEach { file -> val subPath = file.parentFile.toRelativeString(srcFile) val destPath = dest.resolve(subPath) if (destPath.notExists()) { destPath.createDirectories() } Files.copy(file.toPath(), destPath.resolve(file.name)) } } } } }
85
null
5
6
4fb69b039990d40842c3c827a4a1e0d023cad74b
10,011
kobweb-cli
Apache License 2.0
app/src/main/java/com/quantumcode/napets/ui/myProfile/view/HomeProfileFragment.kt
Tesis-IA
586,580,191
false
{"Kotlin": 116702}
package com.quantumcode.napets.ui.myProfile.view import com.quantumcode.napets.databinding.FragmentHomeProfileBinding import com.quantumcode.napets.ui.base.BaseFragment class HomeProfileFragment : BaseFragment<FragmentHomeProfileBinding>() { override fun getViewBinding() = FragmentHomeProfileBinding.inflate(layoutInflater) }
0
Kotlin
0
0
4be8ee7a77e48bc19a0c6eb59bb7fb67db451dab
334
napets-app
MIT License
libs/lifecycle/lifecycle-impl/src/main/kotlin/net/corda/lifecycle/impl/InternalLifecycleEvents.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.lifecycle.impl import net.corda.lifecycle.LifecycleEvent import net.corda.lifecycle.LifecycleStatus import net.corda.lifecycle.TimerEvent /** * Purely internal events for the lifecycle coordinator to process. These are used to ensure that state changes to the * coordinator always happen on an executor thread. As there should only ever be a single thread processing events at * any one time, this ensures there is no race condition in updating coordinator state. */ /** * Create a new timer. * * This takes the parameters of the `createTimer` function on the API and packages them for processing elsewhere. */ internal data class SetUpTimer( val key: String, val delay: Long, val timerEventGenerator: (String) -> TimerEvent ) : LifecycleEvent /** * Cancel a timer. */ internal data class CancelTimer(val key: String) : LifecycleEvent /** * Add a new registration for this coordinator to update with status changes. * * @param registration The new registration to keep updated */ internal data class NewRegistration(val registration: Registration) : LifecycleEvent /** * Remove a registration for this coordinator from the set to update with status changes. * * @param registration The registration to remove from the set to keep updated. */ internal data class CancelRegistration(val registration: Registration) : LifecycleEvent /** * Keep track of a registration this coordinator now has on some dependents. * * This is primarily used to update the coordinator of the current registration status on startup. * * @param registration The registration to track. */ internal data class TrackRegistration(val registration: Registration) : LifecycleEvent /** * Stop tracking a registration this coordinator had on some dependents. * * This is used to clean up registration tracking state when a registration is cancelled. * * @param registration The registration to stop tracking. */ internal data class StopTrackingRegistration(val registration: Registration) : LifecycleEvent /** * Indicates that the component has changed status, so this component can inform dependent components of the change. * * @param newStatus The new status this component has taken. * @param reason The reason this status was entered, for diagnostic purposes */ internal data class StatusChange(val newStatus: LifecycleStatus, val reason: String) : LifecycleEvent /** * Perform any state cleanup for the coordinator as it closes. */ internal class CloseCoordinator : LifecycleEvent
14
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
2,532
corda-runtime-os
Apache License 2.0
src/test/kotlin/de/hennihaus/bamdatamodel/testutils/FileTestUtil.kt
hennihaus
537,758,510
false
{"Kotlin": 22520}
package de.hennihaus.bamdatamodel.testutils fun getResourceAsText(path: String): String = object {}.javaClass.getResource(path)!!.readText()
1
Kotlin
0
0
4f1d7ddc6207bfeb93b8c869b6adc7444f59e8d9
142
bamdatamodel
Apache License 2.0
src/main/kotlin/com/terraformation/backend/nursery/db/BatchPhotoService.kt
terraware
323,722,525
false
null
package com.terraformation.backend.nursery.db import com.terraformation.backend.auth.currentUser import com.terraformation.backend.customer.event.OrganizationDeletionStartedEvent import com.terraformation.backend.customer.model.requirePermissions import com.terraformation.backend.db.FileNotFoundException import com.terraformation.backend.db.asNonNullable import com.terraformation.backend.db.default_schema.FileId import com.terraformation.backend.db.nursery.BatchId import com.terraformation.backend.db.nursery.tables.daos.BatchPhotosDao import com.terraformation.backend.db.nursery.tables.pojos.BatchPhotosRow import com.terraformation.backend.db.nursery.tables.references.BATCH_PHOTOS import com.terraformation.backend.file.FileService import com.terraformation.backend.file.SizedInputStream import com.terraformation.backend.file.model.NewFileMetadata import com.terraformation.backend.log.perClassLogger import com.terraformation.backend.nursery.event.BatchDeletionStartedEvent import jakarta.inject.Named import java.io.InputStream import java.time.InstantSource import org.jooq.Condition import org.jooq.DSLContext import org.jooq.impl.DSL import org.springframework.context.event.EventListener @Named class BatchPhotoService( private val batchPhotosDao: BatchPhotosDao, private val clock: InstantSource, private val dslContext: DSLContext, private val fileService: FileService, ) { private val log = perClassLogger() fun storePhoto(batchId: BatchId, data: InputStream, metadata: NewFileMetadata): FileId { requirePermissions { updateBatch(batchId) } val fileId = fileService.storeFile("batch", data, metadata) { fileId -> batchPhotosDao.insert( BatchPhotosRow( batchId = batchId, createdBy = currentUser().userId, createdTime = clock.instant(), fileId = fileId)) } log.info("Stored photo $fileId for batch $batchId") return fileId } fun readPhoto( batchId: BatchId, fileId: FileId, maxWidth: Int? = null, maxHeight: Int? = null ): SizedInputStream { checkFileExists(batchId, fileId) requirePermissions { readBatch(batchId) } return fileService.readFile(fileId, maxWidth, maxHeight) } fun listPhotos(batchId: BatchId): List<BatchPhotosRow> { requirePermissions { readBatch(batchId) } return dslContext .selectFrom(BATCH_PHOTOS) .where(BATCH_PHOTOS.BATCH_ID.eq(batchId)) .and(BATCH_PHOTOS.DELETED_TIME.isNull) .orderBy(BATCH_PHOTOS.ID) .fetchInto(BatchPhotosRow::class.java) } fun deletePhoto(batchId: BatchId, fileId: FileId) { checkFileExists(batchId, fileId) requirePermissions { updateBatch(batchId) } fileService.deleteFile(fileId) { dslContext .update(BATCH_PHOTOS) .set(BATCH_PHOTOS.DELETED_BY, currentUser().userId) .set(BATCH_PHOTOS.DELETED_TIME, clock.instant()) .setNull(BATCH_PHOTOS.FILE_ID) .where(BATCH_PHOTOS.BATCH_ID.eq(batchId)) .and(BATCH_PHOTOS.FILE_ID.eq(fileId)) .execute() } } /** Deletes all the photos from all the batches owned by an organization. */ @EventListener fun on(event: OrganizationDeletionStartedEvent) { purgeWhere(BATCH_PHOTOS.batches.ORGANIZATION_ID.eq(event.organizationId)) } /** Deletes all the photos from a batch when the batch is deleted. */ @EventListener fun on(event: BatchDeletionStartedEvent) { purgeWhere(BATCH_PHOTOS.BATCH_ID.eq(event.batchId)) } private fun checkFileExists(batchId: BatchId, fileId: FileId) { val fileExists = dslContext.fetchExists( DSL.selectOne() .from(BATCH_PHOTOS) .where(BATCH_PHOTOS.BATCH_ID.eq(batchId)) .and(BATCH_PHOTOS.FILE_ID.eq(fileId))) if (!fileExists) { throw FileNotFoundException(fileId) } } /** * Purges batch photos matching a condition. This removes the file, if any, and also deletes the * batch photo record from the database (as opposed to just marking it as deleted). */ private fun purgeWhere(condition: Condition) { with(BATCH_PHOTOS) { dslContext .select(ID.asNonNullable(), FILE_ID) .from(BATCH_PHOTOS) .where(condition) .fetch() .forEach { (batchPhotoId, fileId) -> if (fileId != null) { fileService.deleteFile(fileId) { batchPhotosDao.deleteById(batchPhotoId) } } else { // The photo file is already deleted, but we kept a record of its history. batchPhotosDao.deleteById(batchPhotoId) } } } } }
9
null
1
9
ab6fbb71381d0eda0684e9d06aa68004d9718b05
4,744
terraware-server
Apache License 2.0
server/src/main/kotlin/cz/martinforejt/piskvorky/server/features/game/mapper/GameMapper.kt
MFori
323,623,365
false
null
package cz.martinforejt.piskvorky.server.features.game.mapper import cz.martinforejt.piskvorky.api.model.GameInvitation import cz.martinforejt.piskvorky.api.model.Player import cz.martinforejt.piskvorky.api.utils.ApiUtils.formatApi import cz.martinforejt.piskvorky.domain.model.Invitation import cz.martinforejt.piskvorky.domain.model.User import cz.martinforejt.piskvorky.server.core.database.schema.GameInvitationEntity import cz.martinforejt.piskvorky.server.core.database.schema.GameInvitations import org.jetbrains.exposed.sql.ResultRow /** * Created by <NAME> on 03.01.2021. * <EMAIL> * * @author <NAME> */ fun ResultRow.asInvitationDO() = Invitation( userId1 = this[GameInvitations.user1].value, userId2 = this[GameInvitations.user2].value, author = this[GameInvitations.author], created = this[GameInvitations.created] ) fun GameInvitationEntity.toGameInvitation(userId: Int): GameInvitation { val rival = if (user1.id.value == userId) user2 else user1 return GameInvitation( userId = rival.id.value, email = rival.email, created = created.formatApi() ) } fun User.toPlayer(cross: Boolean) = Player( id = this.id, email = this.email, cross = cross )
0
Kotlin
0
0
8333fa53793a3ea1a9c83cfa821b5c4e8573ec4b
1,231
Piskvorky
Apache License 2.0
ktor-server/ktor-server-core/posix/src/io/ktor/server/engine/ApplicationEngineEnvironmentNix.kt
ktorio
40,136,600
false
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
// ktlint-disable filename /* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.engine import io.ktor.events.* import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.util.logging.* import io.ktor.utils.io.* import kotlin.coroutines.* /** * Engine environment configuration builder */ @KtorDsl public actual class ApplicationEnvironmentBuilder { /** * Application logger */ public actual var log: Logger = KtorSimpleLogger("io.ktor.server.Application") /** * Application config */ public actual var config: ApplicationConfig = MapApplicationConfig() /** * Build an application engine environment */ public actual fun build(): ApplicationEnvironment { return ApplicationEnvironmentImplNix(log, config) } } public class ApplicationEnvironmentImplNix( override val log: Logger, override val config: ApplicationConfig, @Deprecated( "Moved to Application", replaceWith = ReplaceWith("EmbeddedServer.monitor", "io.ktor.server.engine.EmbeddedServer"), level = DeprecationLevel.WARNING ) override val monitor: Events = Events() ) : ApplicationEnvironment
156
Kotlin
1051
12,926
f90f2edf11caca28a61dbe9973faae64c17a2842
1,289
ktor
Apache License 2.0
fsc/src/main/java/com/angcyo/bluetooth/fsc/laserpacker/command/ICommand.kt
angcyo
229,037,684
false
{"Kotlin": 3482606, "JavaScript": 5542, "HTML": 1598}
package com.angcyo.bluetooth.fsc.laserpacker.command import com.angcyo.bluetooth.fsc.IReceiveBeanAction import com.angcyo.bluetooth.fsc.ISendProgressAction import com.angcyo.bluetooth.fsc.ReceivePacket import com.angcyo.bluetooth.fsc.ReceiveTimeOutException import com.angcyo.bluetooth.fsc.WaitReceivePacket import com.angcyo.bluetooth.fsc.laserpacker.HawkEngraveKeys import com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerHelper import com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerHelper.packetHeadSize import com.angcyo.bluetooth.fsc.laserpacker.LaserPeckerHelper.sumCheck import com.angcyo.library.component.ByteArrayWriter import com.angcyo.library.component.byteWriter import com.angcyo.library.ex.toHexByteArray import com.angcyo.library.toastQQ /** * 功能码(第四个字节): AABB 长度 功能码 * 0x00 查询指令 无提示声 * 0x01 开始打印指令 * 0x02 打印预览指令 * 0x04 调焦指令 * 0x05 文件传输指令 * 0x06 设置指令 * 0x0f 出厂设置指令 * 0xdd 固件更新指令 * 0xff 退出指令 * * 进入文件传输指令: * -> AA BB 09 05 01 00 0E B3 42 00 01 09 * <- AA BB 08 05 01 01 00 00 00 00 07 //rev=1 时表示接收成功,rev=0 时表示接收失败 * <- AA BB 08 05 02 01 00 00 00 00 08 //0x02 表示数据传输结束回应 * * * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022/03/26 */ interface ICommand { /**指令唯一标识符*/ val uuid: String /**优先调用此方法, 如果为空, 则使用[toHexCommandString]*/ fun toByteArray(): ByteArray = toHexCommandString().toHexByteArray() /**功能码*/ fun commandFunc(): Byte = toByteArray()[packetHeadSize + 1] /**转换成十六进制指令, 可以包含空格. * 最后转换ByteArray时, 会剔除空格 * * * 长度:指由功能码开始到较验和一共包含的字节数,这里为不定长Len,一般情况下最小长度为0x08。 * * 功能码:用来指定该数据包功能 * * Data :数据包携带的(Len - 2)字节数据 * * 较验和:包含“功能码”“数据内容”在内,由“功能码”开始至数据结束内容的较验和运算结果,高字节先发送。 * * */ fun toHexCommandString(): String = "" /**获取指令超时时长, 毫秒*/ fun getReceiveTimeout(): Long = HawkEngraveKeys.receiveTimeout /**转换成日志*/ fun toCommandLogString(): String } /**发送一条指令, 未连接设备时, 返回空*/ fun ICommand.sendCommand( address: String? = null, progress: ISendProgressAction? = null, action: IReceiveBeanAction? = { bean: ReceivePacket?, error: Exception? -> error?.let { if (it is ReceiveTimeOutException) { } else { toastQQ(it.message) } } } ): WaitReceivePacket? { return LaserPeckerHelper.sendCommand(this, address, progress, action) } /**指令字节写入, 自动计算字节长度. 动态指令长度 * * 只需要写入功能码开始到较验和之前的数据即可 * * 返回的数据, 可以直接发送的指令*/ fun commandByteWriter(action: ByteArrayWriter.() -> Unit): ByteArray { val headBytes = LaserPeckerHelper.PACKET_HEAD.toHexByteArray() val dataBytes = byteWriter { action() } //长度 val length = dataBytes.size + LaserPeckerHelper.CHECK_SIZE /*if (length > 255) { throw CommandException(_string(R.string.command_too_long_tip)) }*/ val result = byteWriter { //头 write(headBytes) //长度 write(length) //数据 write(dataBytes) //较验和 write(sumCheck(dataBytes)) } return result }
0
Kotlin
4
4
9e5646677153f5fba31c31a1bc8ce5753b84660a
3,041
UICoreEx
MIT License
compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/GeneratorContext.kt
nskvortsov
367,097,840
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.psi2ir.generators import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.NotFoundClasses import org.jetbrains.kotlin.ir.builders.IrGeneratorContext import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.expressions.IrDeclarationReference import org.jetbrains.kotlin.ir.util.ConstantValueGenerator import org.jetbrains.kotlin.ir.util.SymbolTable import org.jetbrains.kotlin.ir.util.TypeTranslator import org.jetbrains.kotlin.psi2ir.Psi2IrConfiguration import org.jetbrains.kotlin.psi2ir.PsiSourceManager import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.storage.LockBasedStorageManager class GeneratorContext( val configuration: Psi2IrConfiguration, val moduleDescriptor: ModuleDescriptor, val bindingContext: BindingContext, val languageVersionSettings: LanguageVersionSettings, val symbolTable: SymbolTable, val extensions: GeneratorExtensions, val typeTranslator: TypeTranslator, val constantValueGenerator: ConstantValueGenerator, override val irBuiltIns: IrBuiltIns ) : IrGeneratorContext { internal val callToSubstitutedDescriptorMap = mutableMapOf<IrDeclarationReference, CallableDescriptor>() val sourceManager = PsiSourceManager() // TODO: inject a correct StorageManager instance, or store NotFoundClasses inside ModuleDescriptor val reflectionTypes = ReflectionTypes(moduleDescriptor, NotFoundClasses(LockBasedStorageManager.NO_LOCKS, moduleDescriptor)) fun IrDeclarationReference.commitSubstituted(descriptor: CallableDescriptor) { callToSubstitutedDescriptorMap[this] = descriptor } }
5
null
1
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
2,081
kotlin
Apache License 2.0
src/main/kotlin/eu/automateeverything/nspanelplugin/blocks/NsPanelOptionAutomationNode.kt
tomaszbabiuk
669,691,372
false
null
/* * Copyright (c) 2019-2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.automateeverything.nspanelplugin.blocks import eu.automateeverything.domain.automation.StatementNode import eu.automateeverything.domain.automation.StatementNodeBase import eu.automateeverything.nspanelplugin.NsPanelAutomationUnit import java.util.* class NsPanelOptionAutomationNode( override val next: StatementNode?, private val insideNode: StatementNode?, private val optionId: Int?, private val nsPanelDevice: NsPanelAutomationUnit, ) : StatementNodeBase() { override fun process(now: Calendar, firstLoop: Boolean) { if (nsPanelDevice.selectedOptionId == optionId) { insideNode?.process(now, firstLoop) } next?.process(now, firstLoop) } }
0
Kotlin
0
0
d22c52d3d85f97cf7195e09d6d7f71f2b1a5867c
1,322
aeplugin-nspanel
Apache License 2.0
compose/runtime/runtime/integration-tests/src/androidAndroidTest/kotlin/androidx/compose/runtime/AndroidSnapshotTests.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime import androidx.compose.runtime.snapshots.Snapshot import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class AndroidSnapshotTests : BaseComposeTest() { @get:Rule override val activityRule = makeTestActivityRule() @Test // regression test for b/163903673 fun testCommittingInABackgroundThread() { val states = Array(10000) { mutableStateOf(0) } var stop = false object : Thread() { override fun run() { while (!stop) { for (state in states) { state.value = state.value + 1 } sleep(1) } } }.start() try { val unregister = Snapshot.registerApplyObserver { changed, _ -> // Try to catch a concurrent modification exception val iterator = changed.iterator() while (iterator.hasNext()) { iterator.next() } } try { repeat(100) { activityRule.activity.uiThread { Snapshot.sendApplyNotifications() } } } finally { unregister.dispose() } } finally { stop = true } } }
29
null
937
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,152
androidx
Apache License 2.0
src/test/kotlin/org/wfanet/panelmatch/common/certificates/openssl/OpenSslCertificateAuthorityTest.kt
world-federation-of-advertisers
357,662,978
false
null
// Copyright 2021 The Cross-Media Measurement Authors // // 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.wfanet.panelmatch.common.certificates.openssl import com.google.common.truth.Truth.assertThat import com.google.protobuf.kotlin.toByteStringUtf8 import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneId import java.util.Date import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.crypto.authorityKeyIdentifier import org.wfanet.measurement.common.crypto.readCertificate import org.wfanet.measurement.common.crypto.sign import org.wfanet.measurement.common.crypto.subjectKeyIdentifier import org.wfanet.measurement.common.crypto.testing.FIXED_CA_CERT_PEM_FILE import org.wfanet.measurement.common.crypto.verifySignature import org.wfanet.panelmatch.common.certificates.CertificateAuthority private val CONTEXT = CertificateAuthority.Context( commonName = "some-common-name", organization = "some-org-name", dnsName = "example.com", validDays = 5, ) private val ROOT_X509 by lazy { readCertificate(FIXED_CA_CERT_PEM_FILE) } private val ROOT_PUBLIC_KEY by lazy { ROOT_X509.publicKey } private val ROOT_PRIVATE_KEY_FILE by lazy { FIXED_CA_CERT_PEM_FILE.resolveSibling("ca.key") } @RunWith(JUnit4::class) class OpenSslCertificateAuthorityTest { @get:Rule val temporaryFolder = TemporaryFolder() @get:Rule val temporaryFolderForRootPrivateKey = TemporaryFolder() // This is necessary or OpenSSL will complain about a filename being too long. private val rootPrivateKeyFile by lazy { temporaryFolderForRootPrivateKey.root.resolve("root.key").apply { ROOT_PRIVATE_KEY_FILE.copyTo(this) } } @Test fun generatesCertificateAndCleansUpAfterwards() { val certificateAuthority = OpenSslCertificateAuthority( CONTEXT, rootPrivateKeyFile, FIXED_CA_CERT_PEM_FILE, temporaryFolder.root, ) val (x509, privateKey) = runBlocking { certificateAuthority.generateX509CertificateAndPrivateKey() } assertThat(x509.notBefore.toLocalDate()).isEqualTo(LocalDate.now()) assertThat(x509.notAfter.toLocalDate()) .isEqualTo(LocalDate.now().plusDays(CONTEXT.validDays.toLong())) x509.verify(ROOT_PUBLIC_KEY) // Does not throw assertThat(x509.authorityKeyIdentifier).isEqualTo(ROOT_X509.subjectKeyIdentifier) val data = "some-data-to-be-signed".toByteStringUtf8() val signature = privateKey.sign(x509, data) assertThat(x509.verifySignature(data, signature)).isTrue() // Ensure OpenSSL input and output files are cleaned up: assertThat(temporaryFolder.root.list()).isEmpty() } } private fun Date.toLocalDate(): LocalDate { return LocalDateTime.ofInstant(toInstant(), ZoneId.systemDefault()).toLocalDate() }
145
Kotlin
11
4
9826ef29ac445b7aee8f28dd0ddd9ee8cf116102
3,453
panel-exchange-client
Apache License 2.0
demo/kotlin-demo/src/test/kotlin/com/alibaba/demo/one2multi/ASvcMock.kt
alibaba
311,530,297
false
null
package com.alibaba.demo.one2multi import com.alibaba.testable.core.annotation.MockInvoke class ASvcMock { @MockInvoke(targetClass = String::class, targetMethod = "format") fun a_format(format: String, vararg args: Any?): String { return "a_mock" } }
57
Java
299
1,715
30570ae69dcbfd1851d81ee2c934614762e45e95
275
testable-mock
MIT License