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
app/src/main/java/com/example/androiddevchallenge/theme/Color.kt
odaridavid
342,733,605
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.theme import androidx.compose.ui.graphics.Color val grey300 = Color(0xFFE0E0E0) val grey300Light = Color(0xFFFFFFFF) val grey300Dark = Color(0xFFAEAEAE) val grey700 = Color(0xFF616161) val grey700Light = Color(0xFF8E8E8E) val grey700Dark = Color(0xFF373737) val white = Color(0xFFFFFFFF) val black = Color(0xFF000000) val green300 = Color(0xFF81C784) val red300 = Color(0xFFE57373)
0
Kotlin
0
1
188ddf8513edfefc65f6c299c479b07491d29312
1,043
pick-a-pup
Apache License 2.0
src/jvmTest/kotlin/org/angproj/aux/num/BigIntTest.kt
angelos-project
677,039,667
false
{"Kotlin": 516041}
package org.angproj.aux.num import org.angproj.aux.util.NullObject import kotlin.test.* import java.math.BigInteger as JavaBigInteger class BigIntTest { @Test fun testNull() { assertTrue(NullObject.bigInt.isNull()) assertFalse(BigInt.zero.isNull()) } /** * This test recognizes that BigInt and Java BigInteger interprets a ByteArray of some random values * the same when importing from the said ByteArray and exporting to a new ByteArray. * */ @Test fun testByteArray() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertContentEquals( x, xJbi, xBi2, xJbi, xBi2 ) } } /** * This test recognizes that BigInt can predict its export size properly. * */ @Test fun testToSize() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xBi2.getByteSize(), xBi2.toByteArray().size, ) } } /** * This test recognizes that BigInt and Java BigInteger interprets a Long random value * the same way when importing and then exporting to a new ByteArray. * */ @Test fun testLong() { Combinator.longGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger.valueOf(x) Debugger.assertContentEquals( x, xJbi, xBi2, xJbi, xBi2 ) } } /** * This test recognizes that BigInt and Java BigInteger interprets a ByteArray of some random values * the same when exporting toInt. * */ @Test fun testToInt() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xJbi.toInt(), xBi2.toInt() ) } } /** * This test recognizes that BigInt and Java BigInteger interprets a ByteArray of some random values * the same when exporting toLong. * */ @Test fun testToLong() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xJbi.toLong(), xBi2.toLong() ) } } /** * This test recognizes that BigInt and Java BigInteger calculates * the sigNum of the same underlying value similarly. * */ @Test fun testSigNum() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xJbi.signum(), xBi2.sigNum.state ) } } /** * This test recognizes that BigInt and Java BigInteger calculates * the bitLength of the same underlying value similarly. * */ @Test fun testBitLength() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xJbi.bitLength(), xBi2.bitLength ) } } /** * This test recognizes that BigInt and Java BigInteger calculates * the bitCount of the same underlying value similarly. * */ @Test fun testBitCount() { Combinator.numberGenerator(-64..64) { x -> val xBi2 = bigIntOf(x) val xJbi = JavaBigInteger(x) Debugger.assertEquals( x, xJbi, xBi2, xJbi.bitCount(), xBi2.bitCount ) } } /** * This test recognizes whether large zero unsigned big integer * translates into zero magnitude and sigNum properly. * */ @Test fun testUnsignedBigIntOf() { val xBi2 = unsignedBigIntOf(ByteArray(100) { 0 }) val yBi2 = unsignedBigIntOf((ByteArray(100) { 0 }).also { it[5] = 1 }) assertTrue(xBi2.sigNum.isZero()) assertTrue(xBi2.mag.isEmpty()) assertTrue(yBi2.sigNum.isNonZero()) assertTrue(yBi2.mag.isNotEmpty()) } }
0
Kotlin
0
0
c9433fa9f8b2e96fe26636a1043a7e87e78d7b7c
4,864
angelos-project-aux
MIT License
sphinx/application/common/wrappers/wrapper-subscription/src/main/java/chat/sphinx/wrapper_subscription/SubscriptionInterval.kt
stakwork
340,103,148
false
{"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.wrapper_subscription @Suppress("NOTHING_TO_INLINE") inline fun SubscriptionInterval.isDaily(): Boolean = this is SubscriptionInterval.Daily @Suppress("NOTHING_TO_INLINE") inline fun SubscriptionInterval.isWeekly(): Boolean = this is SubscriptionInterval.Weekly @Suppress("NOTHING_TO_INLINE") inline fun SubscriptionInterval.isMonthly(): Boolean = this is SubscriptionInterval.Monthly @Suppress("NOTHING_TO_INLINE") inline fun SubscriptionInterval.isUnknown(): Boolean = this is SubscriptionInterval.Unknown /** * Converts the integer value returned over the wire to an object. * * @throws [IllegalArgumentException] if the integer is not supported * */ @Suppress("NOTHING_TO_INLINE") @Throws(IllegalArgumentException::class) inline fun String.toSubscriptionInterval(): SubscriptionInterval = when (this) { SubscriptionInterval.DAILY -> { SubscriptionInterval.Daily } SubscriptionInterval.WEEKLY -> { SubscriptionInterval.Weekly } SubscriptionInterval.MONTHLY -> { SubscriptionInterval.Monthly } else -> { SubscriptionInterval.Unknown(this) } } /** * Comes off the wire as: * - "daily" (Daily) * - "weekly" (Weekly) * - "monthly" (Monthly) * */ sealed class SubscriptionInterval { companion object { const val DAILY = "daily" const val WEEKLY = "weekly" const val MONTHLY = "monthly" } abstract val value: String object Daily: SubscriptionInterval() { override val value: String get() = DAILY } object Weekly: SubscriptionInterval() { override val value: String get() = WEEKLY } object Monthly: SubscriptionInterval() { override val value: String get() = MONTHLY } data class Unknown(override val value: String): SubscriptionInterval() }
96
Kotlin
8
18
4fd9556a4a34f14126681535558fe1e39747b323
1,941
sphinx-kotlin
MIT License
tklogger/src/main/kotlin/cn/shper/tklogger/TKLogLevel.kt
shper
216,601,435
false
null
package cn.shper.tklogger import androidx.annotation.Keep /** * Author : Shper * EMail : <EMAIL> * Date : 2020/6/10 */ @Keep enum class TKLogLevel { VERBOSE, DEBUG, INFO, WARN, ERROR, } @Keep class LevelString { var verbose = "V" var debug = "D" var info = "I" var warning = "W" var error = "E" } @Keep class LevelColor { var verbose = "💜" // silver var debug = "💚" // green var info = "💙" // blue var warning = "💛" // yellow var error = "💔" // red }
0
Kotlin
0
2
f43f998d34555dd1e5776a4a69ed69337667a963
510
TKLogger-Android
Apache License 2.0
ChatroomService/src/main/java/io/agora/chatroom/UIChatroomUser.kt
apex-wang
728,010,838
false
{"Kotlin": 497622}
package io.agora.chatroom import io.agora.chatroom.service.UserEntity class UIChatroomUser { fun getUserInfo(userId:String): UserEntity { return ChatroomUIKitClient.getInstance().getCacheManager().getUserInfo(userId) } fun setUserInfo(userId:String,userInfo: UserEntity){ ChatroomUIKitClient.getInstance().getCacheManager().saveUserInfo(userId,userInfo) } }
0
Kotlin
0
0
20b1ff03d06d87d44565e322ccf9abced24264c5
393
test
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ssmincidents/ActionPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.ssmincidents import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.ssmincidents.CfnResponsePlan @Generated public fun buildActionProperty(initializer: @AwsCdkDsl CfnResponsePlan.ActionProperty.Builder.() -> Unit): CfnResponsePlan.ActionProperty = CfnResponsePlan.ActionProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
451
aws-cdk-kt
Apache License 2.0
glados-client/glados-client-discord/src/main/kotlin/jp/nephy/glados/clients/discord/command/Annotation.kt
StarryBlueSky
125,806,741
false
null
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED") package jp.nephy.glados.clients.discord.command import jp.nephy.glados.api.GLaDOS import jp.nephy.glados.api.config import jp.nephy.glados.clients.discord.config.discord import jp.nephy.glados.clients.name val DiscordCommandSubscription.primaryCommandName: String get() = annotation.command.ifBlank { name } val DiscordCommandSubscription.commandNames: List<String> get() = listOf(primaryCommandName) + annotation.aliases val DiscordCommandSubscription.description: String? get() = annotation.description.ifBlank { null } val DiscordCommandSubscription.arguments: List<String> get() = annotation.arguments.toList() val DiscordCommandSubscription.category: String? get() = annotation.category.ifBlank { null } val DiscordCommandSubscription.prefix: String get() = annotation.prefix.ifBlank { GLaDOS.config.discord.prefix } val DiscordCommandSubscription.commandSyntaxes: List<String> get() = commandNames.map { "$prefix$it" } val DiscordCommandSubscription.primaryCommandSyntax: String get() = commandSyntaxes.first()
0
Kotlin
1
12
89c2ca214e728f454c386ebee4ee78c5a99d5130
2,245
GLaDOS-bot
MIT License
Content/Kotlin/utils/FastReader.kt
wesley-a-leung
88,320,237
false
null
import java.io.* import java.math.* import java.util.* class FastReader { private val BUFFER_SIZE: Int = 1 shl 12 private var LENGTH: Int = -1 private val din: DataInputStream private val buffer: ByteArray = ByteArray(BUFFER_SIZE) private var bufferPointer: Int = 0 private var bytesRead: Int = 0 private var buf: CharArray = CharArray(0) constructor(inputStream: InputStream) { din = DataInputStream(inputStream) } constructor(fileName: String) { din = DataInputStream(FileInputStream(fileName)) } fun nextInt(): Int { var ret: Int = 0 var c: Byte do { c = read() } while (c <= 32) var neg: Boolean = c == 45.toByte() if (neg) c = read() do { ret = ret * 10 + c - 48 c = read() } while (c >= 48) if (neg) return -ret return ret } fun nextLong(): Long { var ret: Long = 0L var c: Byte do { c = read() } while (c <= 32) var neg: Boolean = c == 45.toByte() if (neg) c = read() do { ret = ret * 10 + c - 48 c = read() } while (c >= 48) if (neg) return -ret return ret } fun nextDouble(): Double { var ret: Double = 0.0 var div: Double = 1.0 var c: Byte do { c = read() } while (c <= 32) var neg: Boolean = c == 45.toByte() if (neg) c = read() do { ret = ret * 10 + c - 48 c = read() } while (c >= 48) if (c == 46.toByte()) { c = read() while (c >= 48) { div *= 10 ret += (c - 48) / div c = read() } } if (neg) return -ret return ret } fun nextChar(): Char { var c: Byte do { c = read() } while (c <= 32) return c.toChar() } fun next(): String { var c: Byte var cnt: Int = 0 do { c = read() } while (c <= 32) do { buf[cnt++] = c.toChar() c = read() } while (c > 32) return String(buf, 0, cnt) } fun nextLine(): String { while (bufferPointer > 0 && buffer[bufferPointer - 1] == 13.toByte()) read() var c: Byte var cnt: Int = 0 c = read() while (c != 10.toByte() && c != 0.toByte()) { if (c != 13.toByte()) buf[cnt++] = c.toChar() c = read() } return String(buf, 0, cnt) } fun setLength(len: Int) { LENGTH = len buf = CharArray(len) } fun hasNext(): Boolean { while (peek() > -1 && peek() <= 32) read() return peek() > -1 } fun hasNextLine(): Boolean { while (peek() == 13.toByte()) read() return peek() > -1 } private fun fillBuffer() { bufferPointer = 0 bytesRead = din.read(buffer, bufferPointer, BUFFER_SIZE) if (bytesRead == -1) buffer[0] = -1 } private fun read(): Byte { if (bufferPointer == bytesRead) fillBuffer() return buffer[bufferPointer++] } private fun peek(): Byte { if (bufferPointer == bytesRead) fillBuffer() return buffer[bufferPointer] } fun close() { din.close() } }
0
C++
9
34
dfb32ddc81f08a7ab4053b5daba9ec1b11c84307
2,965
Resources
Creative Commons Zero v1.0 Universal
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/filled/BagX.kt
wiryadev
380,639,096
false
null
package com.wiryadev.bootstrapiconscompose.bootstrapicons.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.wiryadev.bootstrapiconscompose.bootstrapicons.FilledGroup public val FilledGroup.BagX: ImageVector get() { if (_bagX != null) { return _bagX!! } _bagX = Builder(name = "BagX", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(10.5f, 3.5f) arcToRelative(2.5f, 2.5f, 0.0f, false, false, -5.0f, 0.0f) lineTo(5.5f, 4.0f) horizontalLineToRelative(5.0f) verticalLineToRelative(-0.5f) close() moveTo(11.5f, 3.5f) lineTo(11.5f, 4.0f) lineTo(15.0f, 4.0f) verticalLineToRelative(10.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f) lineTo(3.0f, 16.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) lineTo(1.0f, 4.0f) horizontalLineToRelative(3.5f) verticalLineToRelative(-0.5f) arcToRelative(3.5f, 3.5f, 0.0f, true, true, 7.0f, 0.0f) close() moveTo(6.854f, 8.146f) arcToRelative(0.5f, 0.5f, 0.0f, true, false, -0.708f, 0.708f) lineTo(7.293f, 10.0f) lineToRelative(-1.147f, 1.146f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.708f, 0.708f) lineTo(8.0f, 10.707f) lineToRelative(1.146f, 1.147f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.708f, -0.708f) lineTo(8.707f, 10.0f) lineToRelative(1.147f, -1.146f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.708f, -0.708f) lineTo(8.0f, 9.293f) lineTo(6.854f, 8.146f) close() } } .build() return _bagX!! } private var _bagX: ImageVector? = null
0
Kotlin
0
2
1c199d953dc96b261aab16ac230dc7f01fb14a53
2,772
bootstrap-icons-compose
MIT License
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/SimpleTextSpec.kt
stripe
6,926,049
false
null
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import androidx.annotation.StringRes import androidx.compose.ui.text.input.KeyboardCapitalization import com.stripe.android.uicore.elements.IdentifierSpec import com.stripe.android.uicore.elements.SimpleTextElement import com.stripe.android.uicore.elements.SimpleTextFieldConfig import com.stripe.android.uicore.elements.SimpleTextFieldController import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class Capitalization { @SerialName("none") None, @SerialName("characters") Characters, @SerialName("words") Words, @SerialName("sentences") Sentences; } @Serializable enum class KeyboardType { @SerialName("text") Text, @SerialName("ascii") Ascii, @SerialName("number") Number, @SerialName("phone") Phone, @SerialName("uri") Uri, @SerialName("email") Email, @SerialName("password") Password, @SerialName("number_password") NumberPassword; } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Serializable data class SimpleTextSpec( @SerialName("api_path") override val apiPath: IdentifierSpec, @SerialName("label") @StringRes val label: Int, @SerialName("capitalization") val capitalization: Capitalization = Capitalization.None, @SerialName("keyboard_type") val keyboardType: KeyboardType = KeyboardType.Ascii, @SerialName("show_optional_label") val showOptionalLabel: Boolean = false ) : FormItemSpec() { fun transform( initialValues: Map<IdentifierSpec, String?> = mapOf() ) = createSectionElement( SimpleTextElement( this.apiPath, SimpleTextFieldController( SimpleTextFieldConfig( label = this.label, capitalization = when (this.capitalization) { Capitalization.None -> KeyboardCapitalization.None Capitalization.Characters -> KeyboardCapitalization.Characters Capitalization.Words -> KeyboardCapitalization.Words Capitalization.Sentences -> KeyboardCapitalization.Sentences }, keyboard = when (this.keyboardType) { KeyboardType.Text -> androidx.compose.ui.text.input.KeyboardType.Text KeyboardType.Ascii -> androidx.compose.ui.text.input.KeyboardType.Ascii KeyboardType.Number -> androidx.compose.ui.text.input.KeyboardType.Number KeyboardType.Phone -> androidx.compose.ui.text.input.KeyboardType.Phone KeyboardType.Uri -> androidx.compose.ui.text.input.KeyboardType.Uri KeyboardType.Email -> androidx.compose.ui.text.input.KeyboardType.Email KeyboardType.Password -> androidx.compose.ui.text.input.KeyboardType.Password KeyboardType.NumberPassword -> androidx.compose.ui.text.input.KeyboardType.NumberPassword } ), initialValue = initialValues[this.apiPath], showOptionalLabel = this.showOptionalLabel ) ) ) }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
3,321
stripe-android
MIT License
xs2awizard/src/main/java/com/fintecsystems/xs2awizard/components/theme/XS2AColors.kt
FinTecSystems
379,873,214
false
{"Kotlin": 166986}
package com.fintecsystems.xs2awizard.components.theme import androidx.compose.ui.graphics.Color import com.fintecsystems.xs2awizard.components.theme.interop.XS2AColor /** * Default color-palette of the wizard. */ object XS2AColors { val primary = XS2AColor("#427783") val textColor = XS2AColor("#262626") val textColorLight = XS2AColor(Color.White) val darkGrey = XS2AColor("#BFBFBF") val backgroundLight = XS2AColor(Color.White) val backgroundDark = XS2AColor("#121212") val backgroundTranslucent = XS2AColor("#AAFFFFFF") val backgroundTranslucentDark = XS2AColor("#AA121212") val backgroundWarning = XS2AColor("#FEAE22") val backgroundInfo = XS2AColor("#0E9EC2") val backgroundError = XS2AColor("#EA544A") val backgroundInput = XS2AColor("#14000000") val backgroundInputDark = XS2AColor("#14FFFFFF") val surfaceColor = XS2AColor(Color.White) val flickerBackground = XS2AColor(Color.Black) val flickerForeground = XS2AColor(Color.White) val flickerMarker = XS2AColor("#BFBFBF") val unselected = XS2AColor(Color.Gray) val disabled = XS2AColor(Color.LightGray) val unselectedDark = XS2AColor(Color.LightGray) val disabledDark = XS2AColor(Color.Gray) }
2
Kotlin
4
6
ef3ea8e9b2a4834b1be8cc4aa576bbdf29a5527e
1,243
xs2a-android
Apache License 2.0
core-v2/core-v2-train/src/test/java/com/github/teracy/odpt/core/v2/train/response/OdptTrainTest.kt
teracy
193,032,147
false
null
package com.github.teracy.odpt.core.v2.train.response import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith /** * v2版列車ロケーション情報APIレスポンス */ @RunWith(Enclosed::class) class OdptTrainTest { /** * デシリアライズのテスト */ class DeserializeTest { private val parameterizedType = Types.newParameterizedType(List::class.java, OdptTrain::class.java) lateinit var jsonAdapter: JsonAdapter<List<OdptTrain>> @Before fun setUp() { jsonAdapter = Moshi.Builder().build().adapter(parameterizedType) } /** * 東京メトロオープンデータAPIサンプルデータより */ @Test fun tokyoMetroSampleData() { // テストデータ val json = "[\n" + " {\n" + " \"@context\": \"http://vocab.tokyometroapp.jp/context_odpt_Train.jsonld\",\n" + " \"@type\": \"odpt:Train\",\n" + " \"@id\": \"urn:ucode:_00001C000000000000010000030C4D61\",\n" + " \"dc:date\": \"2014-09-08T20:53:51+09:00\",\n" + " \"dct:valid\": \"2014-09-08T20:54:51+09:00\",\n" + " \"odpt:frequency\": 60,\n" + " \"odpt:railway\": \"odpt.Railway:TokyoMetro.Chiyoda\",\n" + " \"owl:sameAs\": \"odpt.Train:TokyoMetro.Chiyoda.A2098S4\",\n" + " \"odpt:trainNumber\": \"A2098S4\",\n" + " \"odpt:trainType\": \"odpt.TrainType:TokyoMetro.Local\",\n" + " \"odpt:delay\": 0,\n" + " \"odpt:startingStation\": \"odpt.Station:TokyoMetro.Chiyoda.KitaAyase\",\n" + " \"odpt:terminalStation\": \"odpt.Station:TokyoMetro.Chiyoda.Ayase\",\n" + " \"odpt:fromStation\": \"odpt.Station:TokyoMetro.Chiyoda.KitaAyase\",\n" + " \"odpt:toStation\": null,\n" + " \"odpt:railDirection\": \"odpt.RailDirection:TokyoMetro.Ayase\",\n" + " \"odpt:trainOwner\": \"odpt.TrainOwner:TokyoMetro\"\n" + " },\n" + " {\n" + " \"@context\": \"http://vocab.tokyometroapp.jp/context_odpt_train.jsonld\",\n" + " \"@type\": \"odpt:Train\",\n" + " \"@id\": \"urn:ucode:_00001C000000000000010000030C4D65\",\n" + " \"dc:date\": \"2014-09-08T20:53:51+09:00\",\n" + " \"dct:valid\": \"2014-09-08T20:54:51+09:00\",\n" + " \"odpt:frequency\": 60,\n" + " \"odpt:railway\": \"odpt.Railway:TokyoMetro.Chiyoda\",\n" + " \"owl:sameAs\": \"odpt.Train:TokyoMetro.Chiyoda.A2029K\",\n" + " \"odpt:trainNumber\": \"A2029K\",\n" + " \"odpt:trainType\": \"odpt.TrainType:TokyoMetro.Local\",\n" + " \"odpt:delay\": 0,\n" + " \"odpt:startingStation\": \"odpt.Station:JR-East.Joban.Abiko\",\n" + " \"odpt:terminalStation\": \"odpt.Station:TokyoMetro.Chiyoda.YoyogiUehara\",\n" + " \"odpt:fromStation\": \"odpt.Station:TokyoMetro.Chiyoda.Yushima\",\n" + " \"odpt:toStation\": null,\n" + " \"odpt:railDirection\": \"odpt.RailDirection:TokyoMetro.YoyogiUehara\",\n" + " \"odpt:trainOwner\": \"odpt.TrainOwner:JR-East\"\n" + " }\n" + "]" val trainList = jsonAdapter.fromJson(json) assertThat(trainList).isNotNull assertThat(trainList!!.size).isEqualTo(2) val train0 = trainList[0] assertThat(train0.id).isEqualTo("urn:ucode:_00001C000000000000010000030C4D61") assertThat(train0.sameAs).isEqualTo("odpt.Train:TokyoMetro.Chiyoda.A2098S4") assertThat(train0.trainNumber).isEqualTo("A2098S4") assertThat(train0.trainType).isEqualTo("odpt.TrainType:TokyoMetro.Local") assertThat(train0.date).isEqualTo("2014-09-08T20:53:51+09:00") assertThat(train0.valid).isEqualTo("2014-09-08T20:54:51+09:00") assertThat(train0.frequency).isEqualTo(60) assertThat(train0.railway).isEqualTo("odpt.Railway:TokyoMetro.Chiyoda") assertThat(train0.trainOwner).isEqualTo("odpt.TrainOwner:TokyoMetro") assertThat(train0.railDirection).isEqualTo("odpt.RailDirection:TokyoMetro.Ayase") assertThat(train0.delay).isEqualTo(0) assertThat(train0.startingStation).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.KitaAyase") assertThat(train0.terminalStation).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.Ayase") assertThat(train0.fromStation).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.KitaAyase") assertThat(train0.toStation).isNull() assertThat(train0.trainId.id).isEqualTo("odpt.Train:TokyoMetro.Chiyoda.A2098S4") assertThat(train0.trainTypeId.id).isEqualTo("odpt.TrainType:TokyoMetro.Local") assertThat(train0.railwayId.id).isEqualTo("odpt.Railway:TokyoMetro.Chiyoda") assertThat(train0.trainOwnerId.id).isEqualTo("odpt.TrainOwner:TokyoMetro") assertThat(train0.railDirectionId.id).isEqualTo("odpt.RailDirection:TokyoMetro.Ayase") assertThat(train0.startingStationId.id).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.KitaAyase") assertThat(train0.terminalStationId.id).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.Ayase") assertThat(train0.fromStationId.id).isEqualTo("odpt.Station:TokyoMetro.Chiyoda.KitaAyase") assertThat(train0.toStationId).isNull() } } }
0
Kotlin
0
1
002554e4ca6e2f460207cfd1cb8265c2267f149d
6,210
odpt
Apache License 2.0
js/js.engines/src/org/jetbrains/kotlin/js/engine/ScriptEngineV8.kt
JetBrains
3,432,266
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.js.engine class ScriptEngineV8 : ProcessBasedScriptEngine(System.getProperty("javascript.engine.path.V8")) fun main() { // System.setProperty("javascript.engine.path.V8", "<path-to-d8>") val vm = ScriptEngineV8() println("Welcome!") while (true) { print("> ") val t = readLine() try { println(vm.eval(t!!)) } catch (e: Throwable) { System.err.println(e) } } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
684
kotlin
Apache License 2.0
app/src/main/java/org/covidwatch/android/util/ButtonUtils.kt
generalmotors
279,946,799
false
{"Gradle": 6, "XML": 79, "Markdown": 3, "Java Properties": 3, "Shell": 2, "Text": 2, "Ignore List": 4, "Batchfile": 2, "PlantUML": 2, "YAML": 3, "JSON": 3, "Proguard": 2, "Kotlin": 88, "INI": 1, "Java": 2}
package org.covidwatch.android.util import android.content.Intent import android.content.res.ColorStateList import android.net.Uri import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import android.widget.Toast import org.covidwatch.android.GlobalConstants import org.covidwatch.android.R import org.covidwatch.android.presentation.settings.SettingsFragment class ButtonUtils { // TODO: josh - accessibility adjustments for performClickOverride // class CustomButtonView : AppCompatButton { // constructor(context: Context?) : super(context) {} // constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {} // // override fun onTouchEvent(event : MotionEvent) : Boolean { // super.onTouchEvent(event) // when (event.action) { // MotionEvent.ACTION_DOWN -> { // Toast.makeText(context,"USING NEW OVERRIDE",Toast.LENGTH_LONG).show() // invalidate() // } // MotionEvent.ACTION_UP -> { // performClick() // invalidate() // return true // } // } // return false // } // // override fun performClick(): Boolean { // super.performClick() // return true // } // // } class ButtonTouchListener: OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { if (v.isClickable) { when (event.action) { MotionEvent.ACTION_DOWN -> { v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.accentYellowPressed)) v.invalidate() } MotionEvent.ACTION_CANCEL -> { v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.accentYellow)) v.invalidate() } MotionEvent.ACTION_UP -> { when (v.id) { 2131361878 -> { // Turn On Bluetooth SettingsFragment() .ensureBluetoothIsOn() v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.maroon_shadow)) v.invalidate() } 2131361983 -> { // Grant Location Access SettingsFragment() .ensureLocationPermissionIsGranted() v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.maroon_shadow)) v.invalidate() } 2131362067 -> { // Save Contact Button Toast.makeText(v.context,"Saving Number...",Toast.LENGTH_LONG).show() // SettingsFragment().savePhoneNumber() Toast.makeText(v.context,"Number Saved!",Toast.LENGTH_LONG).show() v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.maroon_shadow)) v.invalidate() } 2131361921 -> { // Dial GM Medical v.backgroundTintList = ColorStateList.valueOf(v.context.getColor(R.color.accentYellow)) v.invalidate() val phone = GlobalConstants.MEDICAL_NUMBER val intent = Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone.toString(), null)) v.context.startActivity(intent) } } } } } return false } } }
1
null
2
1
41c9eefcc48f584a5544f7c92b6fc95e89e11f9c
4,134
covidwatch-android-tcn
Apache License 2.0
src/main/kotlin/mainRoomCollector/mainRoomCollectorInfo.kt
Solovova
199,853,060
false
{"JavaScript": 388035, "Kotlin": 318290}
package mainRoomCollector import MainRoomInfoSetup import TypeOfMainRoomInfo import mainRoom.getInfo import screeps.api.* fun MainRoomCollector.infoShow() { fun colorToHTMLColor(color: ColorConstant): String { return when (color) { COLOR_YELLOW -> "yellow" COLOR_RED -> "red" COLOR_GREEN -> "green" COLOR_BLUE -> "blue" COLOR_ORANGE -> "orange" COLOR_CYAN -> "cyan" COLOR_GREY -> "grey" else -> "white" } } val mainRoomInfoSetup: List<MainRoomInfoSetup> = listOf( MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomName, "", COLOR_WHITE, COLOR_RED, 7, prefix = "", suffix = ""), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomDescribe, "", COLOR_WHITE, COLOR_WHITE, 3, prefix = "(", suffix = ")"), MainRoomInfoSetup(TypeOfMainRoomInfo.infoController, "Controller", COLOR_WHITE, COLOR_RED, 38, prefix = "(", suffix = ") "), MainRoomInfoSetup(TypeOfMainRoomInfo.infoQueue, "Queue", COLOR_YELLOW, COLOR_ORANGE, 80), MainRoomInfoSetup(TypeOfMainRoomInfo.infoConstructionSites, "Construction sites", COLOR_YELLOW, COLOR_ORANGE, 9), MainRoomInfoSetup(TypeOfMainRoomInfo.infoNeedBuild, "Need build", COLOR_YELLOW, COLOR_RED, 40), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomName, "", COLOR_WHITE, COLOR_RED, 7, prefix = "", suffix = ""), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomLevel, "", COLOR_WHITE, COLOR_RED, 3, prefix = " ", suffix = ""), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomEnergy, "Room energy", COLOR_WHITE, COLOR_RED, 14), MainRoomInfoSetup(TypeOfMainRoomInfo.infoNeedUpgrade, "Need upgrade", COLOR_WHITE, COLOR_ORANGE, 10), MainRoomInfoSetup(TypeOfMainRoomInfo.infoPlaceInStorage, "Storage place", COLOR_WHITE, COLOR_RED, 12), MainRoomInfoSetup(TypeOfMainRoomInfo.infoPlaceInTerminal, "Terminal place", COLOR_WHITE, COLOR_RED, 12), MainRoomInfoSetup(TypeOfMainRoomInfo.infoReaction, "Labs", COLOR_WHITE, COLOR_ORANGE, 12), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomDescribe, "", COLOR_WHITE, COLOR_WHITE, 3, prefix = "(", suffix = ")"), MainRoomInfoSetup(TypeOfMainRoomInfo.infoRoomName, "", COLOR_WHITE, COLOR_RED, 7, prefix = "", suffix = "") ) for (mainRoom in this.rooms.values) { val roomInfo = mainRoom.getInfo() var allText = "" for (mainRoomInfoSetupRecord in mainRoomInfoSetup) { var text: String = roomInfo[mainRoomInfoSetupRecord.type]?.text ?: "" val alarm: Boolean = roomInfo[mainRoomInfoSetupRecord.type]?.alarm ?: false text = if (text.length > mainRoomInfoSetupRecord.width) text.substring(0, mainRoomInfoSetupRecord.width) else text.padEnd(mainRoomInfoSetupRecord.width) val color = if (!alarm) mainRoomInfoSetupRecord.color else mainRoomInfoSetupRecord.colorAlarm text = mainRoomInfoSetupRecord.prefix + text + mainRoomInfoSetupRecord.suffix text = "<font color=${colorToHTMLColor(color)} >$text</font>" allText += text } console.log(allText) } }
0
JavaScript
0
0
58050cf11074e315bd3845db9aa78ef6af58abef
4,735
ScreepsKT
MIT License
cottontaildb-cli/src/main/kotlin/org/vitrivr/cottontail/cli/entity/CreateEntityCommand.kt
vitrivr
160,775,368
false
{"Kotlin": 2317843, "Dockerfile": 548}
package org.vitrivr.cottontail.cli.entity import com.github.ajalt.clikt.output.TermUi import com.github.ajalt.clikt.parameters.options.convert import com.github.ajalt.clikt.parameters.options.option import com.google.gson.Gson import com.google.gson.JsonParser import com.google.gson.reflect.TypeToken import com.jakewharton.picnic.table import io.grpc.Status import io.grpc.StatusRuntimeException import org.vitrivr.cottontail.cli.AbstractCottontailCommand import org.vitrivr.cottontail.client.SimpleClient import org.vitrivr.cottontail.client.language.ddl.ListEntities import org.vitrivr.cottontail.grpc.CottontailGrpc import org.vitrivr.cottontail.utilities.TabulationUtilities import org.vitrivr.cottontail.utilities.extensions.proto import kotlin.time.ExperimentalTime import kotlin.time.measureTimedValue /** * Command to create a new a [org.vitrivr.cottontail.dbms.entity.DefaultEntity]. * * @author Ralph Gasser * @version 2.0.0 */ @ExperimentalTime class CreateEntityCommand(client: SimpleClient) : AbstractCottontailCommand.Entity(client, name = "create", help = "Creates a new entity in the database. Usage: entity create <schema>.<entity>") { companion object { data class ColumnInfo(val name: String, val type: CottontailGrpc.Type, val nullable: Boolean = false, val size: Int = -1) { fun toDefinition() : CottontailGrpc.ColumnDefinition { val def = CottontailGrpc.ColumnDefinition.newBuilder() def.nameBuilder.name = name def.type = type def.nullable = nullable def.length = size return def.build() } } } private inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object : TypeToken<T>() {}.type) private val columnDefinition by option( "-d", "--definition", help = "List of column definitions in the form of {\"name\": ..., \"type\": ..., \"nullable\": ..., \"size\": ...}" ).convert { string -> val canonicalFormat = JsonParser.parseString(string).toString() val list: List<ColumnInfo> = Gson().fromJson(canonicalFormat) list.map { it.toDefinition() } } override fun exec() { /* Perform sanity check. */ checkValid() /* Prepare entity definition and prompt user use to add columns to definition. */ val colDef = CottontailGrpc.EntityDefinition.newBuilder().setEntity(this.entityName.proto()) if (columnDefinition != null && columnDefinition!!.isNotEmpty()) { columnDefinition!!.forEach { colDef.addColumns(it) } val time = measureTimedValue { TabulationUtilities.tabulate(this.client.create(CottontailGrpc.CreateEntityMessage.newBuilder().setDefinition(colDef).build())) } println("Entity ${this.entityName} created successfully (took ${time.duration}).") print(time.value) } else { do { /* Prompt user for column definition. */ println("Please specify column to add at position ${colDef.columnsCount + 1}.") val ret = this.promptForColumn() if (ret != null) { colDef.addColumns(ret) } /* Ask if anther column should be added. */ if (colDef.columnsCount > 0 && TermUi.confirm("Do you want to add another column (size = ${colDef.columnsCount})?") == false) { break } } while (true) /* Prepare table for printing. */ val tbl = table { cellStyle { border = true paddingLeft = 1 paddingRight = 1 } header { row { cell([email protected]) { columnSpan = 4 } } row { cells("Name", "Type", "Size", "Nullable") } } body { colDef.columnsList.forEach { def -> row { cells(def.name, def.type, def.length, def.nullable) } } } } /* As for final confirmation and create entity. */ if (TermUi.confirm(text = "Please confirm that you want to create the entity:\n$tbl", default = true) == true) { val time = measureTimedValue { TabulationUtilities.tabulate(this.client.create(CottontailGrpc.CreateEntityMessage.newBuilder().setDefinition(colDef).build())) } println("Entity ${this.entityName} created successfully (took ${time.duration}).") print(time.value) } else { println("Create entity ${this.entityName} aborted!") } } } /** * Checks if this [Name.EntityName] is actually valid to create an [Entity] for. * * @return true if name is valid, false otherwise. */ private fun checkValid(): Boolean { try { val ret = this.client.list(ListEntities(this.entityName.schema().toString())) while (ret.hasNext()) { if (ret.next().asString(0) == this.entityName.simple) { println("Error: Entity ${this.entityName} already exists!") return false } } return true } catch (e: StatusRuntimeException) { if (e.status == Status.NOT_FOUND) { println("Error: Schema ${this.entityName.schema()} not found.") } return false } } /** * Prompts user to specify column information and returns a [CottontailGrpc.ColumnDefinition] if user completes this step. * * @return Optional [CottontailGrpc.ColumnDefinition] */ private fun promptForColumn(): CottontailGrpc.ColumnDefinition? { val def = CottontailGrpc.ColumnDefinition.newBuilder() def.nameBuilder.name = TermUi.prompt("Column name (must consist of letters and numbers)") def.type = TermUi.prompt("Column type (${CottontailGrpc.Type.values().joinToString(", ")})") { CottontailGrpc.Type.valueOf(it.uppercase()) } def.length = when (def.type) { CottontailGrpc.Type.DOUBLE_VEC, CottontailGrpc.Type.FLOAT_VEC, CottontailGrpc.Type.LONG_VEC, CottontailGrpc.Type.INT_VEC, CottontailGrpc.Type.BOOL_VEC, CottontailGrpc.Type.COMPLEX32_VEC, CottontailGrpc.Type.COMPLEX64_VEC -> TermUi.prompt("\rColumn lengths (i.e. number of entries for vectors)") { it.toInt() } ?: 1 else -> -1 } def.nullable = TermUi.confirm(text = "Should column be nullable?", default = false) ?: false val tbl = table { cellStyle { border = true paddingLeft = 1 paddingRight = 1 } header { row { cells("Name", "Type", "Size", "Nullable") } } body { row { cells(def.name, def.type, def.length, def.nullable) } } } return if (TermUi.confirm("Please confirm column:\n$tbl") == true) { def.build() } else { null } } }
7
Kotlin
18
26
50cc8526952f637d685da9d18f4b1630b782f1ff
7,689
cottontaildb
MIT License
buildSrc/buildSrc/src/main/kotlin/Deps.kt
LouisCAD
380,833,587
true
{"Kotlin": 184981, "Ruby": 2062, "Swift": 344, "Shell": 306}
object Lib { const val kermit = "co.touchlab:kermit:0.1.9" const val stately = "co.touchlab:stately-common:1.1.7" const val uuid = "com.benasher44:uuid:0.3.0" object Koin { private const val version = "3.1.0" const val core = "io.insert-koin:koin-core:$version" const val test = "io.insert-koin:koin-test:$version" const val android = "io.insert-koin:koin-android:$version" const val compose = "io.insert-koin:koin-androidx-compose:$version" } object Firebase { const val bom = "com.google.firebase:firebase-bom:28.0.1" const val analytics = "com.google.firebase:firebase-analytics-ktx" const val messagingDirectBoot = "com.google.firebase:firebase-messaging-directboot" const val cloudMessaging = "com.google.firebase:firebase-messaging-ktx" } object OKHTTP { private const val version = "4.9.0" const val core = "com.squareup.okhttp3:okhttp:$version" const val logging = "com.squareup.okhttp3:logging-interceptor:$version" } object Apollo { private const val version = Version.apollo const val runtimeKotlin = "com.apollographql.apollo:apollo-runtime-kotlin:$version" const val runtime = "com.apollographql.apollo:apollo-runtime:$version" const val coroutinesSupport = "com.apollographql.apollo:apollo-coroutines-support:$version" const val cacheSqlite = "com.apollographql.apollo:apollo-normalized-cache-sqlite:$version" } object MultiplatformSettings { private const val version = "0.7.7" const val settings = "com.russhwolf:multiplatform-settings:$version" const val coroutines = "com.russhwolf:multiplatform-settings-coroutines:$version" const val datastore = "com.russhwolf:multiplatform-settings-datastore:$version" const val test = "com.russhwolf:multiplatform-settings-test:$version" } object Jetpack { const val startup = "androidx.startup:startup-runtime:1.0.0" const val browser = "androidx.browser:browser:1.3.0" const val dataStore = "androidx.datastore:datastore-preferences:1.0.0-beta02" } object KotlinX { object Serialization { private const val version = "1.2.1" const val core = "org.jetbrains.kotlinx:kotlinx-serialization-core:$version" const val json = "org.jetbrains.kotlinx:kotlinx-serialization-json:$version" } const val dateTime = "org.jetbrains.kotlinx:kotlinx-datetime:0.2.1" object Coroutines { private const val version = Version.coroutines const val bom = "org.jetbrains.kotlinx:kotlinx-coroutines-bom:$version" val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core" val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android" val test = "org.jetbrains.kotlinx:kotlinx-coroutines-test" } } object Ktor { const val bom = "io.ktor:ktor-bom:1.6.0" const val clientCore = "io.ktor:ktor-client-core" const val clientJson = "io.ktor:ktor-client-json" const val clientLogging = "io.ktor:ktor-client-logging" const val clientSerialization = "io.ktor:ktor-client-serialization" const val clientAndroid = "io.ktor:ktor-client-android" const val clientEncoding = "io.ktor:ktor-client-encoding" // val clientApache = "io.ktor:ktor-client-apache:${Versions.ktor}" // val slf4j = "org.slf4j:slf4j-simple:${Versions.slf4j}" // val clientIos = "io.ktor:ktor-client-ios:${Versions.ktor}" // val clientCio = "io.ktor:ktor-client-cio:${Versions.ktor}" // val clientJs = "io.ktor:ktor-client-js:${Versions.ktor}" } object SqlDelight { private const val version = Version.sqlDelight const val runtime = "com.squareup.sqldelight:runtime:$version" const val coroutineExtensions = "com.squareup.sqldelight:coroutines-extensions:$version" const val androidDriver = "com.squareup.sqldelight:android-driver:$version" const val iosDriver = "com.squareup.sqldelight:native-driver:$version" } object Arrow { private const val version = Version.arrow const val STACK = "io.arrow-kt:arrow-stack:$version" const val CORE = "io.arrow-kt:arrow-core" const val FX = "io.arrow-kt:arrow-fx" const val MTL = "io.arrow-kt:arrow-mtl" const val SYNTAX = "io.arrow-kt:arrow-syntax" const val FX_MTL = "io.arrow-kt:arrow-fx-mtl" const val COROUTINES = "io.arrow-kt:arrow-fx-coroutines" const val OPTICS = "io.arrow-kt:arrow-optics" const val META = "io.arrow-kt:arrow-meta" } object Accompanist { private const val version = "0.10.0" const val coil = "com.google.accompanist:accompanist-coil:$version" const val insets = "com.google.accompanist:accompanist-insets:$version" } object Activity { const val activityCompose = "androidx.activity:activity-compose:1.3.0-alpha08" } object Compose { private const val snapshot = "" private const val version = Version.compose const val animation = "androidx.compose.animation:animation:$version" const val foundation = "androidx.compose.foundation:foundation:$version" const val layout = "androidx.compose.foundation:foundation-layout:$version" const val iconsExtended = "androidx.compose.material:material-icons-extended:$version" const val material = "androidx.compose.material:material:$version" const val runtime = "androidx.compose.runtime:runtime:$version" const val tooling = "androidx.compose.ui:ui-tooling:$version" const val ui = "androidx.compose.ui:ui:$version" const val uiUtil = "androidx.compose.ui:ui-util:$version" const val uiTest = "androidx.compose.ui:ui-test-junit4:$version" } object ConstraintLayout { const val constraintLayoutCompose = "androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha07" } } object Version { const val kotlin = "1.5.10" const val sqlDelight = "1.5.0" const val apollo = "2.5.9" const val arrow = "0.13.2" const val compose = "1.0.0-beta09" const val androidTools = "7.1.0-alpha02" const val coroutines = "1.5.0-native-mt" }
0
null
0
0
f46020f59be5f1603ee00d7540d83bf7d6840a1c
6,390
yaba-kmm
Apache License 2.0
mvvmbase/src/main/java/by/iba/mvvmbase/custom/bottomnavigation/Utils.kt
lev4ik911
309,679,864
false
null
package by.iba.mvvmbase.custom.bottomnavigation import android.content.Context import android.graphics.PorterDuff import android.graphics.drawable.Drawable import android.view.View import androidx.core.content.ContextCompat import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat private fun getDP(context: Context) = context.resources.displayMetrics.density internal fun dipf(context: Context,f: Float) = f * getDP(context) internal fun dipf(context: Context,i: Int) = i * getDP(context) internal fun dip(context: Context,i: Int) = (i * getDP(context)).toInt() internal object DrawableHelper{ @Suppress("DEPRECATION") fun changeColorDrawableVector(c: Context?, resDrawable: Int, color: Int): Drawable? { if (c == null) return null val d = VectorDrawableCompat.create(c.resources, resDrawable, null) ?: return null d.mutate() if (color != -2) d.setColorFilter(color, PorterDuff.Mode.SRC_IN) return d } fun changeColorDrawableRes(c: Context?, resDrawable: Int, color: Int): Drawable? { if (c == null) return null val d = ContextCompat.getDrawable(c, resDrawable) ?: return null d.mutate() if (color != -2) d.setColorFilter(color, PorterDuff.Mode.SRC_IN) return d } } internal object ColorHelper{ fun mixTwoColors(color1: Int, color2: Int, amount: Float): Int { val alphaChannel = 24 val redChannel = 16 val greenChannel = 8 val inverseAmount = 1.0f - amount val a = ((color1 shr alphaChannel and 0xff).toFloat() * amount + (color2 shr alphaChannel and 0xff).toFloat() * inverseAmount).toInt() and 0xff val r = ((color1 shr redChannel and 0xff).toFloat() * amount + (color2 shr redChannel and 0xff).toFloat() * inverseAmount).toInt() and 0xff val g = ((color1 shr greenChannel and 0xff).toFloat() * amount + (color2 shr greenChannel and 0xff).toFloat() * inverseAmount).toInt() and 0xff val b = ((color1 and 0xff).toFloat() * amount + (color2 and 0xff).toFloat() * inverseAmount).toInt() and 0xff return a shl alphaChannel or (r shl redChannel) or (g shl greenChannel) or b } } internal fun Context.getDrawableCompat(res: Int) = ContextCompat.getDrawable(this, res) internal inline fun <T : View?> T.runAfterDelay(delay: Long, crossinline f: T.() -> Unit) { this?.postDelayed({ try { f() }catch (e:Exception){} }, delay) }
0
Kotlin
0
0
86e909810e147cf138c0eae4af874c28b52b0c6c
2,497
SBS_JB
Apache License 2.0
app/src/main/java/com/gentalhacode/github/features/search/adapter/RepositoryViewHolder.kt
thgMatajs
239,887,486
false
null
package com.gentalhacode.github.features.search.adapter import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import coil.api.load import coil.request.CachePolicy import coil.size.Precision import com.gentalhacode.github.R import com.gentalhacode.github.model.Repository /** * .:.:.:. Created by @thgMatajs on 18/03/20 .:.:.:. */ class RepositoryViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val itemName: TextView = itemView.findViewById(R.id.repositoryItemName) private val itemOwnerName: TextView = itemView.findViewById(R.id.repositoryItemOwner) private val itemTotalStars: TextView = itemView.findViewById(R.id.repositoryItemStars) private val itemTotalForks: TextView = itemView.findViewById(R.id.repositoryItemForks) private val itemIv: ImageView = itemView.findViewById(R.id.repositoryItemIv) fun bindView(item: Repository?) { item?.apply { itemName.text = name itemOwnerName.text = owner.name itemTotalStars.text = totalStars.toString() itemTotalForks.text = totalForks.toString() itemIv.load(owner.urlPhoto) { crossfade(true) size(130, 130) precision(Precision.AUTOMATIC) diskCachePolicy(CachePolicy.ENABLED) memoryCachePolicy(CachePolicy.ENABLED) } } } }
0
Kotlin
0
5
f3e8465cdbc92c9375f32c20085afdeac69dd04d
1,469
GitHubSearch
The Unlicense
app/src/main/java/com/beomsu317/cocktailrecipeapp/presentation/util/screens/cocktails_info/CocktailsInfoViewModel.kt
beomsu317
477,009,961
false
null
package com.beomsu317.cocktailrecipeapp.presentation.util.screens.cocktails_info import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.palette.graphics.Palette import com.beomsu317.cocktailrecipeapp.common.Resource import com.beomsu317.cocktailrecipeapp.domain.model.Cocktail import com.beomsu317.cocktailrecipeapp.domain.use_case.CocktailUseCases import com.beomsu317.cocktailrecipeapp.presentation.util.OneTimeEvent import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import java.net.URLDecoder import javax.inject.Inject @HiltViewModel class CocktailsInfoViewModel @Inject constructor( private val cocktailUseCases: CocktailUseCases, savedStateHandle: SavedStateHandle ) : ViewModel() { var state by mutableStateOf(CocktailsInfoState()) private set private val _oneTimeEventChannel = Channel<OneTimeEvent>() val oneTimeEventFlow = _oneTimeEventChannel.receiveAsFlow() private var getIdsJob: Job? = null init { savedStateHandle.get<String>("cocktail")?.let { encodedCocktail -> val decodedCocktail = Json.decodeFromString<Cocktail>(URLDecoder.decode(encodedCocktail, "UTF-8")) getCocktailInfos(decodedCocktail.strDrink) } savedStateHandle.get<Boolean>("single")?.let { single -> state = state.copy(single = single) } refreshIds() } fun onEvent(event: CocktailsInfoEvent) { when (event) { is CocktailsInfoEvent.ToggleCocktailInfo -> { viewModelScope.launch { if (state.ids.contains(event.cocktailInfo.idDrink)) { cocktailUseCases.deleteCocktailInfoByIdUseCase(event.cocktailInfo.idDrink) } else { cocktailUseCases.insertCocktailInfoUseCase(event.cocktailInfo) } refreshIds() } } is CocktailsInfoEvent.CalcDominantColor -> { viewModelScope.launch { calcDominantColor(event.drawable) } } } } private fun calcDominantColor(drawable: Drawable) { val bmp = (drawable as BitmapDrawable).bitmap.copy(Bitmap.Config.ARGB_8888, true) Palette.from(bmp).generate { palette -> palette?.dominantSwatch?.rgb?.let { colorValue -> state = state.copy(dominantColor = colorValue) } } } private fun refreshIds() { getIdsJob?.cancel() getIdsJob = cocktailUseCases.getCocktailInfoIdsUseCase().onEach { ids -> state = state.copy(ids = ids) }.launchIn(viewModelScope) } private fun getCocktailInfos(name: String) { cocktailUseCases.getCocktailInfosByNameUseCase(name).onEach { result -> when (result) { is Resource.Success -> { state = state.copy( isLoading = false, cocktailInfos = result?.data ?: emptyList() ) } is Resource.Error -> { _oneTimeEventChannel.send( OneTimeEvent.ShowSnackbar( result?.message ?: "An unexpected error occured" ) ) state = state.copy(isLoading = false) } is Resource.Loading -> { state = state.copy(isLoading = true) } } }.launchIn(viewModelScope) } }
0
Kotlin
0
0
92566be22082f10be8d990f9b00906e128fa40bd
4,234
cocktail-recipe-app
Apache License 2.0
app/src/main/java/io/github/fuadreza/storelog/di/AppModule.kt
fuadreza
298,769,785
false
null
package io.github.fuadreza.storelog.di import android.app.Activity import android.content.Context import androidx.activity.ComponentActivity import androidx.lifecycle.LifecycleCoroutineScope import androidx.lifecycle.ViewModel import androidx.lifecycle.lifecycleScope import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import androidx.lifecycle.viewModelScope import dagger.hilt.android.components.ApplicationComponent import dagger.hilt.android.qualifiers.ActivityContext import dagger.hilt.android.qualifiers.ApplicationContext import io.github.fuadreza.storelog.database.LocalDatabase import io.github.fuadreza.storelog.database.dao.SupplyDao import io.github.fuadreza.storelog.database.dao.UserDao import io.github.fuadreza.storelog.repository.SupplyRepository import io.github.fuadreza.storelog.repository.UserRepository import io.github.fuadreza.storelog.view.login.LoginActivity import kotlinx.coroutines.CoroutineScope /** * Dibuat dengan kerjakerasbagaiquda oleh Shifu pada tanggal 26/09/2020. * */ @Module @InstallIn(ApplicationComponent::class) object AppModule { @Provides fun provideSupplyDao(@ApplicationContext appContext: Context): SupplyDao { return LocalDatabase.getDatabase(appContext).supplyDao() } @Provides fun provideSupplyRepo(supplyDao: SupplyDao) = SupplyRepository(supplyDao) @Provides fun provideUserDao(@ApplicationContext appContext: Context): UserDao { return LocalDatabase.getDatabase(appContext).userDao() } @Provides fun provideUserRepo(userDao: UserDao) = UserRepository(userDao) }
0
Kotlin
0
0
860603d78a27c655b908f9a2d67b935df12d68c5
1,605
StoreLog
Apache License 2.0
lwjgl3/src/main/kotlin/gdx/liftoff/lwjgl3/StartupHelper.kt
tommyettinger
575,705,154
false
null
/* * Copyright 2020 damios * * 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. */ //Note, the above license and copyright applies to this file only. package gdx.liftoff.lwjgl3; import org.lwjgl.system.macosx.LibC; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.util.ArrayList; /** * Adds some utilities to ensure that the JVM was started with the * {@code -XstartOnFirstThread} argument, which is required on macOS for LWJGL 3 * to function. Also helps on Windows when users have names with characters from * outside the Latin alphabet, a common cause of startup crashes. * <br> * <a href="https://jvm-gaming.org/t/starting-jvm-on-mac-with-xstartonfirstthread-programmatically/57547">Based on this java-gaming.org post by kappa</a> * @author damios */ public class StartupHelper { private static final String JVM_RESTARTED_ARG = "jvmIsRestarted"; private StartupHelper() { throw new UnsupportedOperationException(); } /** * Starts a new JVM if the application was started on macOS without the * {@code -XstartOnFirstThread} argument. This also includes some code for * Windows, for the case where the user's home directory includes certain * non-Latin-alphabet characters (without this code, most LWJGL3 apps fail * immediately for those users). Returns whether a new JVM was started and * thus no code should be executed. * <p> * <u>Usage:</u> * * <pre><code> * public static void main(String... args) { * if (StartupHelper.startNewJvmIfRequired(true)) return; // This handles macOS support and helps on Windows. * // after this is the actual main method code * } * </code></pre> * * @param redirectOutput * whether the output of the new JVM should be rerouted to the * old JVM, so it can be accessed in the same place; keeps the * old JVM running if enabled * @return whether a new JVM was started and thus no code should be executed * in this one */ public static boolean startNewJvmIfRequired(boolean redirectOutput) { String osName = System.getProperty("os.name").toLowerCase(); if (!osName.contains("mac")) { if (osName.contains("windows")) { // Here, we are trying to work around an issue with how LWJGL3 loads its extracted .dll files. // By default, LWJGL3 extracts to the directory specified by "java.io.tmpdir", which is usually the user's home. // If the user's name has non-ASCII (or some non-alphanumeric) characters in it, that would fail. // By extracting to the relevant "ProgramData" folder, which is usually "C:\ProgramData", we avoid this. System.setProperty("java.io.tmpdir", System.getenv("ProgramData") + "/libGDX-temp"); } return false; } long pid = LibC.getpid(); // check whether -XstartOnFirstThread is enabled if ("1".equals(System.getenv("JAVA_STARTED_ON_FIRST_THREAD_" + pid))) { return false; } // check whether the JVM was previously restarted // avoids looping, but most certainly leads to a crash if ("true".equals(System.getProperty(JVM_RESTARTED_ARG))) { System.err.println( "There was a problem evaluating whether the JVM was started with the -XstartOnFirstThread argument."); return false; } // Restart the JVM with -XstartOnFirstThread ArrayList<String> jvmArgs = new ArrayList<>(); String separator = System.getProperty("file.separator"); // The following line is used assuming you target Java 8, the minimum for LWJGL3. String javaExecPath = System.getProperty("java.home") + separator + "bin" + separator + "java"; // If targeting Java 9 or higher, you could use the following instead of the above line: //String javaExecPath = ProcessHandle.current().info().command().orElseThrow(); if (!(new File(javaExecPath)).exists()) { System.err.println( "A Java installation could not be found. If you are distributing this app with a bundled JRE, be sure to set the -XstartOnFirstThread argument manually!"); return false; } jvmArgs.add(javaExecPath); jvmArgs.add("-XstartOnFirstThread"); jvmArgs.add("-D" + JVM_RESTARTED_ARG + "=true"); jvmArgs.addAll(ManagementFactory.getRuntimeMXBean().getInputArguments()); jvmArgs.add("-cp"); jvmArgs.add(System.getProperty("java.class.path")); String mainClass = System.getenv("JAVA_MAIN_CLASS_" + pid); if (mainClass == null) { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); if (trace.length > 0) { mainClass = trace[trace.length - 1].getClassName(); } else { System.err.println("The main class could not be determined."); return false; } } jvmArgs.add(mainClass); try { if (!redirectOutput) { ProcessBuilder processBuilder = new ProcessBuilder(jvmArgs); processBuilder.start(); } else { Process process = (new ProcessBuilder(jvmArgs)) .redirectErrorStream(true).start(); BufferedReader processOutput = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = processOutput.readLine()) != null) { System.out.println(line); } process.waitFor(); } } catch (Exception e) { System.err.println("There was a problem restarting the JVM"); e.printStackTrace(); } return true; } /** * Starts a new JVM if the application was started on macOS without the * {@code -XstartOnFirstThread} argument. Returns whether a new JVM was * started and thus no code should be executed. Redirects the output of the * new JVM to the old one. * <p> * <u>Usage:</u> * * <pre> * public static void main(String... args) { * if (StartupHelper.startNewJvmIfRequired()) return; // This handles macOS support and helps on Windows. * // the actual main method code * } * </pre> * * @return whether a new JVM was started and thus no code should be executed * in this one */ public static boolean startNewJvmIfRequired() { return startNewJvmIfRequired(true); } }
0
Kotlin
0
0
3a99a94f07e21fea8da175e81b6ea69c010830fc
7,271
gdx-liftoff-demo-kotlin
The Unlicense
src/main/kotlin/it/nicolasfarabegoli/gradle/central/Configurations.kt
nicolasfara
440,837,601
false
null
package it.nicolasfarabegoli.gradle.central import org.gradle.api.Project import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.publish.maven.tasks.PublishToMavenRepository import org.gradle.api.publish.plugins.PublishingPlugin import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.create import org.gradle.kotlin.dsl.the import org.gradle.kotlin.dsl.withType /** * Extension useful to configure the POM file in the plugin. */ fun MavenPublication.configurePom(extension: PublishToMavenCentralExtension) { pom { pom -> with(pom) { name.set(extension.projectName) description.set(extension.projectDescription) packaging = "jar" url.set(extension.projectUrl) scm { scm -> scm.url.set(extension.projectUrl) scm.connection.set(extension.scmConnection) scm.developerConnection.set(extension.scmConnection) } licenses { it.license { license -> license.name.set(extension.licenseName) license.url.set(extension.licenseUrl) } } } } } /** * Extension useful to configure a new repository [repoToConfigure] in the project. */ fun Project.configureRepository(repoToConfigure: Repository) { extensions.configure(PublishingExtension::class) { publishing -> publishing.repositories { repository -> repository.maven { mar -> mar.name = repoToConfigure.name mar.url = uri(repoToConfigure.url) mar.credentials { credentials -> credentials.username = repoToConfigure.username.orNull credentials.password = repoToConfigure.password.orNull } tasks.withType<PublishToMavenRepository> { if (this.repository == mar) { this.doFirst { warnIfCredentialsAreMissing(repoToConfigure) } } } } } } repoToConfigure.nexusUrl?.let { configureNexusRepository(repoToConfigure, it) } } /** * Extension useful to configure a new Nexus [repo] with [nexusUrl]. */ fun Project.configureNexusRepository(repo: Repository, nexusUrl: String) { the<PublishingExtension>().publications.withType<MavenPublication>().forEach { pub -> val nexus = NexusOperation( project = project, nexusUrl = nexusUrl, group = project.group.toString(), username = repo.username, password = <PASSWORD>, timeOut = repo.timeout, connectionTimeOut = repo.connectionTimeout ) val publicationName = pub.name.replaceFirstChar(Char::titlecase) val uploadArtifacts = project.tasks.create<PublishToMavenRepository>( "upload${publicationName}To${repo.name}Nexus" ) { this.repository = project.repositories.maven { artifactRepo -> artifactRepo.name = repo.name artifactRepo.url = project.uri(repo.url) artifactRepo.credentials { it.username = repo.username.orNull it.password = <PASSWORD> } } this.doFirst { warnIfCredentialsAreMissing(repo) this.repository.url = nexus.repoUrl } this.publication = pub this.group = PublishingPlugin.PUBLISH_TASK_GROUP this.description = "Initialize a new Nexus repository on ${repo.name}" + "and uploads the $publicationName publication." } val closeRepository = tasks.create("close${publicationName}On${repo.name}Nexus") { it.doLast { nexus.close() } it.dependsOn(uploadArtifacts) it.group = PublishingPlugin.PUBLISH_TASK_GROUP it.description = "Closes the Nexus repository on ${repo.name} with the $publicationName publication" } tasks.create("release${publicationName}On${repo.name}Nexus") { it.doLast { nexus.release() } it.dependsOn(closeRepository) it.group = PublishingPlugin.PUBLISH_TASK_GROUP it.description = "Releases the Nexus repo on ${repo.name} with the $publicationName publication." } } } /** * Extension used to verify if credentials for repository are correctly setup, otherwise a warning is raised. */ fun Project.warnIfCredentialsAreMissing(repository: Repository) { repository.username.orNull ?: logger.warn( "No username configured for repository {} at {}.", repository.name, repository.url, ) repository.password.orNull ?: logger.warn( "No password configured for user {} on repository {} at {}.", repository.username.orNull, repository.name, repository.url, ) }
12
Kotlin
0
0
650a2acb5b03c135e3dfd053eec9e741f320e2be
5,075
publish-to-maven-central
Apache License 2.0
bukkit/src/main/kotlin/com/r4g3baby/simplemotd/bukkit/listener/MOTDListener.kt
r4g3baby
444,226,350
false
{"Kotlin": 49549}
package com.r4g3baby.simplemotd.bukkit.listener import com.r4g3baby.simplemotd.BukkitPlugin import net.kyori.adventure.text.minimessage.MiniMessage import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerLoginEvent import org.bukkit.event.server.ServerListPingEvent class MOTDListener(private val plugin: BukkitPlugin): Listener { @EventHandler(priority = EventPriority.HIGHEST) fun onServerListPing(e: ServerListPingEvent) { val username = plugin.getManager().storage.getPlayerUsername(e.address) val text = if (username != null) { MiniMessage.miniMessage().deserialize("<red>Hello <username>!", Placeholder.unparsed("username", username)) } else MiniMessage.miniMessage().deserialize("<red>Hello World!") e.motd = LegacyComponentSerializer.legacySection().serialize(text) } @EventHandler(priority = EventPriority.MONITOR) fun onAsyncPlayerPreLogin(e: PlayerLoginEvent) { if (e.player.name != null) { plugin.server.scheduler.runTaskAsynchronously(plugin) { plugin.getManager().storage.setPlayerUsername(e.address, e.player.name) } } } }
0
Kotlin
0
0
fcd5198d9865177367aea2b7674f7ab84a90fb51
1,400
SimpleMOTD
MIT License
app/src/main/java/co/ello/android/ello/controllers/profile/cells/ProfileHeaderTotalAndBadgesPresenter.kt
ello
129,277,321
false
null
package co.ello.android.ello object ProfileHeaderTotalAndBadgesPresenter { fun configure(cell: ProfileHeaderTotalAndBadgesCell, item: StreamCellItem) { val user = item.model as? User ?: return cell.config(ProfileHeaderTotalAndBadgesCell.Config( totalCount = user.totalViewsCount, badges = user.badges )) } }
0
Kotlin
0
2
489a1b9f0acf5c2b92bd65ada7e73b91fc8e2ff4
371
android
MIT License
app/src/main/java/com/example/fooddeliveryapp/data/datasource/DataSource.kt
ismailfatihbirak
738,936,261
false
{"Kotlin": 43400}
package com.example.fooddeliveryapp.data.datasource import com.example.fooddeliveryapp.data.model.Yemek import com.example.fooddeliveryapp.data.model.Yemekler import com.example.fooddeliveryapp.data.model.YemeklerSepet import com.example.fooddeliveryapp.retrofit.FoodDao import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class DataSource(var fdao:FoodDao) { suspend fun anasayfaYemekYukle() : List<Yemekler> = withContext(Dispatchers.IO){ return@withContext fdao.anasayfaYemekYukle().yemekler } suspend fun sepetEkle(yemek_adi:String,yemek_resim_adi:String,yemek_fiyat:String,yemek_siparis_adet:String,kullanici_adi:String) = fdao.sepetEkle(yemek_adi,yemek_resim_adi,yemek_fiyat,yemek_siparis_adet,kullanici_adi) suspend fun sepetGetir(kullanici_adi:String) : List<YemeklerSepet> = withContext(Dispatchers.IO){ return@withContext fdao.sepetGetir(kullanici_adi).sepet_yemekler } suspend fun sepetSil(sepet_yemek_id:Int,kullanici_adi:String) = fdao.sepetSil(sepet_yemek_id,kullanici_adi) }
0
Kotlin
0
0
a016b5e124ddbd6c7a742aac3438349a7d8ec183
1,098
FoodDeliveryApp
The Unlicense
src/main/kotlin/at/ahammer/bluetooth/checker/Foo.kt
andi-git
102,292,061
false
null
package at.ahammer.bluetooth.checker class Foo() { fun bar() : String { return "bar"; } }
0
Kotlin
0
0
d3d5de2da70191b8e83031d20a457c1313906f09
108
kotlin-test
MIT License
src/main/kotlin/org/jetbrains/packagesearch/api/v2/ApiPackagesResponse.kt
JetBrains
498,634,410
false
null
package org.jetbrains.packagesearch.api.v2 import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ApiPackagesResponse<T : ApiPackage<V>, V : ApiVersion>( @SerialName("packages") val packages: List<T>, @SerialName("repositories") val repositories: List<ApiRepository> )
1
Kotlin
1
7
6be63a916e034f08e6647e1da03200418e313752
331
package-search-api-models
Apache License 2.0
sdk/src/main/java/io/stipop/models/enums/ComponentEnum.kt
stipop-development
372,351,610
false
{"Kotlin": 309491}
package io.stipop.models.enums enum class ComponentEnum { PICKER_VIEW, // SEARCH_VIEW, // Not added yet. // STORE_VIEW // Not added yet. }
2
Kotlin
5
19
6b78b4354e3b3cfbc51db685196d56197d57a653
151
stipop-android-sdk
MIT License
workflow-rx2/src/test/java/com/squareup/workflow/rx2/ComposedReactorIntegrationTest.kt
charbgr
160,076,805
true
{"Kotlin": 258018, "Java": 2825}
/* * Copyright 2017 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.squareup.workflow.rx2 import com.squareup.workflow.Delegating import com.squareup.workflow.EnterState import com.squareup.workflow.FinishWith import com.squareup.workflow.Reaction import com.squareup.workflow.Workflow import com.squareup.workflow.WorkflowPool import com.squareup.workflow.WorkflowPool.Id import com.squareup.workflow.makeId import com.squareup.workflow.register import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.Background import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.Cancel import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.Pause import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.Resume import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.RunEchoJob import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterEvent.RunImmediateJob import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterReactor import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterState.Idle import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterState.Paused import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterState.RunningEchoJob import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.OuterState.RunningImmediateJob import com.squareup.workflow.rx2.ComposedReactorIntegrationTest.StringEchoer import io.reactivex.Single import org.assertj.core.api.Java6Assertions.assertThat import org.junit.Rule import org.junit.Test /** * Tests [Reactor], [Delegating] and [WorkflowPool], with an [OuterReactor] * that can run, pause, background, resume named instances of an [StringEchoer]. * * This IS NOT meant to be an example of how to write workflows in production. * The background workflow thing is very fragile, it's just an amusing way * to exercise running concurrent workflows of the same time. */ @Suppress("MemberVisibilityCanBePrivate") class ComposedReactorIntegrationTest { @Rule @JvmField val assemblyTracking = RxAssemblyTrackingRule() @Test fun runAndSeeResultAfterStateUpdate() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job")) sendEchoEvent("job", "fnord") sendEchoEvent("job", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf("fnord")) assertThat(pool.peekWorkflowsCount).isZero() } @Test fun runAndSeeResultAfterNoStateUpdates() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job")) sendEchoEvent("job", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf(NEW_ECHO_JOB)) assertThat(pool.peekWorkflowsCount).isZero() } @Test fun pause_doesAbandonAndRestartFromSavedState() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job")) sendEchoEvent("job", "able") workflow.sendEvent(Pause) assertThat(pool.peekWorkflowsCount).isZero() workflow.sendEvent(Resume) sendEchoEvent("job", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf("able")) } @Test fun pauseImmediatelyAndResumeAndCompleteImmediately() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job")) workflow.sendEvent(Pause) workflow.sendEvent(Resume) sendEchoEvent("job", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf(NEW_ECHO_JOB)) assertThat(pool.peekWorkflowsCount).isZero() } @Test fun cancel_abandons() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job")) sendEchoEvent("job", "able") sendEchoEvent("job", "baker") workflow.sendEvent(Cancel) assertThat(pool.peekWorkflowsCount).isZero() workflow.sendEvent(RunEchoJob("job")) sendEchoEvent("job", STOP_ECHO_JOB) // We used the same job id, but the state changes from the previous session were dropped. assertThat(results).isEqualTo(listOf(NEW_ECHO_JOB)) assertThat(pool.peekWorkflowsCount).isZero() } @Test fun background_demonstratesConcurrentWorkflowsOfTheSameType() { val workflow = outerReactor.launch() workflow.sendEvent(RunEchoJob("job1")) workflow.sendEvent(Background) workflow.sendEvent(RunEchoJob("job2")) workflow.sendEvent(Background) workflow.sendEvent(RunEchoJob("job3")) workflow.sendEvent(Background) sendEchoEvent("job1", "biz") sendEchoEvent("job2", "baz") sendEchoEvent("job3", "bang") workflow.sendEvent(RunEchoJob("job1")) sendEchoEvent("job1", STOP_ECHO_JOB) workflow.sendEvent(RunEchoJob("job2")) sendEchoEvent("job2", STOP_ECHO_JOB) workflow.sendEvent(RunEchoJob("job3")) sendEchoEvent("job3", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf("biz", "baz", "bang")) } @Test fun syncSingleOnSuccessInNestedWorkflow() { val workflow = outerReactor.launch() workflow.sendEvent(RunImmediateJob) workflow.sendEvent(RunEchoJob("fnord")) sendEchoEvent("fnord", STOP_ECHO_JOB) assertThat(results).isEqualTo(listOf("Finished ${ImmediateOnSuccess::class}", NEW_ECHO_JOB)) assertThat(pool.peekWorkflowsCount).isZero() } companion object { const val NEW_ECHO_JOB = "*NEW ECHO JOB*" const val STOP_ECHO_JOB = "*STOP ECHO JOB*" } /** * Basically a job that can emit strings at arbitrary times, and whose * result code is the last string it emitted. */ class StringEchoer : Reactor<String, String, String> { override fun onReact( state: String, events: EventChannel<String>, workflows: WorkflowPool ): Single<out Reaction<String, String>> = events.select { onEvent<String> { event -> when (event) { STOP_ECHO_JOB -> FinishWith(state) else -> EnterState(event) } } } override fun launch( initialState: String, workflows: WorkflowPool ): Workflow<String, String, String> = doLaunch(initialState, workflows) } val echoReactor = StringEchoer() class ImmediateOnSuccess : Reactor<Unit, String, Unit> { override fun onReact( state: Unit, events: EventChannel<String>, workflows: WorkflowPool ): Single<out Reaction<Unit, Unit>> = events.select { onSuccess(Single.just("fnord")) { FinishWith(Unit) } } override fun launch( initialState: Unit, workflows: WorkflowPool ): Workflow<Unit, String, Unit> = doLaunch(initialState, workflows) } val immediateReactor = ImmediateOnSuccess() sealed class OuterState { object Idle : OuterState() data class RunningEchoJob constructor( override val id: Id<String, String, String>, override val delegateState: String ) : OuterState(), Delegating<String, String, String> { constructor( id: String, state: String ) : this(StringEchoer::class.makeId(id), state) } data class Paused( val id: String, val lastState: String ) : OuterState() object RunningImmediateJob : OuterState(), Delegating<Unit, String, Unit> { override val id = makeId() override val delegateState = Unit } } sealed class OuterEvent { data class RunEchoJob( val id: String, val state: String = NEW_ECHO_JOB ) : OuterEvent() object RunImmediateJob : OuterEvent() /** Ctrl-C */ object Cancel : OuterEvent() /** Ctrl-S */ object Pause : OuterEvent() /** Ctrl-Q */ object Resume : OuterEvent() /** Ctrl-Z */ object Background : OuterEvent() } val results = mutableListOf<String>() val pool = WorkflowPool() /** * One running job, which might be paused or backgrounded. Any number of background jobs. */ inner class OuterReactor : Reactor<OuterState, OuterEvent, Unit> { override fun onReact( state: OuterState, events: EventChannel<OuterEvent>, workflows: WorkflowPool ): Single<out Reaction<OuterState, Unit>> = when (state) { Idle -> events.select { onEvent<RunEchoJob> { EnterState(RunningEchoJob(it.id, it.state)) } onEvent<RunImmediateJob> { EnterState(RunningImmediateJob) } onEvent<Cancel> { FinishWith(Unit) } } is RunningEchoJob -> events.select { onSuccess(workflows.nextDelegateReaction(state)) { when (it) { is EnterState -> EnterState(state.copy(delegateState = it.state)) is FinishWith -> { results += it.result EnterState(Idle) } } } onEvent<Pause> { workflows.abandonDelegate(state.id) EnterState(Paused(state.id.name, state.delegateState)) } onEvent<Background> { EnterState(Idle) } onEvent<Cancel> { workflows.abandonDelegate(state.id) EnterState(Idle) } } is Paused -> events.select { onEvent<Resume> { EnterState(RunningEchoJob(state.id, state.lastState)) } onEvent<Cancel> { EnterState(Idle) } } is RunningImmediateJob -> workflows.nextDelegateReaction(state).map { when (it) { is EnterState -> throw AssertionError("Should never re-enter $RunningImmediateJob.") is FinishWith -> { results += "Finished ${ImmediateOnSuccess::class}" EnterState(Idle) } } } } fun launch() = launch(Idle, pool) override fun launch( initialState: OuterState, workflows: WorkflowPool ): Workflow<OuterState, OuterEvent, Unit> { workflows.register(echoReactor) workflows.register(immediateReactor) val workflow = doLaunch(initialState, workflows) workflow.toCompletable() .subscribe { workflows.abandonAll() } return workflow } } val outerReactor = OuterReactor() fun sendEchoEvent( echoJobId: String, event: String ) { pool.input(StringEchoer::class.makeId(echoJobId)) .sendEvent(event) } }
0
Kotlin
0
0
e3456eb75d4183f1539a83e557fbb8b89ebdbd16
10,526
workflow
Apache License 2.0
app/src/main/java/io/github/wellingtoncosta/feed/infrastructure/network/api/fuel/PostFuelApi.kt
wellingtoncosta
196,209,803
false
{"Kotlin": 72101}
package io.github.wellingtoncosta.feed.infrastructure.network.api.fuel import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.coroutines.awaitString import com.github.kittinunf.fuel.coroutines.awaitStringResponse import io.github.wellingtoncosta.feed.infrastructure.network.api.PostApi import io.github.wellingtoncosta.feed.infrastructure.network.entity.PostResponse import kotlinx.serialization.json.Json import kotlinx.serialization.list class PostFuelApi( private val json: Json ) : PostApi { override suspend fun getAllPosts() = Fuel.get("/posts").awaitString().let { json.parse(PostResponse.serializer().list, it) } override suspend fun getPostById(postId: Long) = Fuel.get("/posts/$postId").awaitStringResponse().run { when(second.statusCode) { HTTP_200, HTTP_304 -> json.parse(PostResponse.serializer(), third) else -> null } } }
0
Kotlin
0
6
3644d65e7b3e3338b72b25ce7a578a1eae8512e7
954
feed
MIT License
domain/src/main/java/pl/handsome/club/domain/product/FavouriteProduct.kt
krzysztofwycislo
298,275,532
false
null
package pl.handsome.club.domain.product import java.util.* data class FavouriteProduct( val productBarcode: String, val productName: String, val productBrand: String, val updateTime: Date, val imageUrl: String? )
0
Kotlin
0
0
61c47aae3e0e7d9a385ffbc07d8d4e2b6d4bad1f
235
KetoScanner
Open Market License
0899.Orderly Queue.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun orderlyQueue(s: String, k: Int): String { if (k == 1) { var ans = s val sb = StringBuilder(s) for (i in 0 until s.length - 1) { sb.append(sb[0]).deleteCharAt(0) if (sb.toString().compareTo(ans) < 0) { ans = sb.toString() } } return ans } val cs: CharArray = s.toCharArray() Arrays.sort(cs) return String(cs) } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
430
kotlin-leetcode
MIT License
speechManagerFeature/src/main/java/com/yes/speechmanagerfeature/data/Speech.kt
Yeroshin
561,680,210
false
{"Kotlin": 655371}
package com.yes.speechmanagerfeature.data import android.annotation.SuppressLint import android.content.Context import android.media.AudioDeviceInfo import android.media.AudioManager import android.media.MicrophoneInfo import android.os.Build import android.os.CountDownTimer import androidx.annotation.OptIn import androidx.annotation.RequiresApi import androidx.media3.common.util.UnstableApi import org.json.JSONObject import org.vosk.Model import org.vosk.Recognizer import org.vosk.android.RecognitionListener import org.vosk.android.StorageService import java.io.IOException import java.io.InputStream @OptIn(UnstableApi::class) @SuppressLint("SuspiciousIndentation") @RequiresApi(Build.VERSION_CODES.P) class Speech( private val context: Context, private val onVoiceCommand:()->Unit, private val onGetVolume:(volume:Double?)->Unit ) { private var model: Model? = null private val speechListener = object : RecognitionListener { override fun onPartialResult(hypothesis: String?) { println(hypothesis) } override fun onResult(hypothesis: String?) { println(hypothesis) val prefix = "sound:" hypothesis?.let { if(hypothesis.startsWith(prefix)) { onGetVolume( hypothesis.removePrefix(prefix).toDoubleOrNull() ) }else if (checkGreetings(hypothesis)){ onVoiceCommand() } } } override fun onFinalResult(hypothesis: String?) { println(hypothesis) } override fun onError(exception: Exception?) { println(exception.toString()) } override fun onTimeout() { println("onTimeout") } } fun checkGreetings(jsonString: String): Boolean { val jsonObject = JSONObject(jsonString) val alternativesArray = jsonObject.getJSONArray("alternatives") for (i in 0 until alternativesArray.length()) { val item = alternativesArray.getJSONObject(i) if (item.getString("text") == "привет") { return true } } return false } init { StorageService.unpack( context, "model", "model", { model: Model -> this.model = model recognizeMicrophone() tmp() }, { exception: IOException -> println("Failed to unpack the model" + exception.message) } ) /* processor.setListener {byteBuffer-> // speechService?.setNoiseBuffer(byteBuffer) }*/ } private fun recognizeMicrophone() { val rec = Recognizer( model, 16000.0f, "[\"привет\",\"риве\",\"иве\",\"и\",\"ив\",\"ве\",\"в\",\"е\",\"э\",\"эт\",\"вет\",\"ет\",\"риве\",\"рив\",\"т\",\"спать\",\"спи\", \"[unk]\"]" ) rec.setMaxAlternatives(10) rec.setPartialWords(true) rec.setWords(true) /////////////// val speechService = VoskSpeechService( context, rec, 16000.0f, {volume->onGetVolume(volume)} ) speechService.startListening(speechListener) val timer = object: CountDownTimer(60000, 1000) { override fun onTick(millisUntilFinished: Long) { } override fun onFinish() { // speechService.setPause(true) speechService.stopRecord() // speechService.shutdown() } } timer.start() //////////// /* val ais: InputStream = context.assets.open( "Recording_6.wav" ) val speechService = VoskSpeechStreamService( rec, ais, 16000.0f, context ) speechService.start(speechListener)*/ /////////////// } fun tmp() { //////////////////////////// val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val volume_level: Int = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) val maxVolume: Int = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) val volumeDb = audioManager.getStreamVolumeDb( AudioManager.STREAM_MUSIC, volume_level, AudioDeviceInfo.TYPE_BUILTIN_SPEAKER ) val mics: List<MicrophoneInfo> = audioManager.microphones ///////////////////////////// } }
0
Kotlin
2
2
b4389943c051917d3f3ab6c2fcdb534d9747d2da
4,682
YES_MusicPlayer
MIT License
src/test/kotlin/no/nav/dagpenger/iverksett/utbetaling/tilstand/IverksettingRepositoryTest.kt
navikt
611,752,955
false
{"Kotlin": 322143, "Gherkin": 57891, "Shell": 626, "Dockerfile": 121}
package no.nav.dagpenger.iverksett.utbetaling.tilstand import no.nav.dagpenger.iverksett.Integrasjonstest import no.nav.dagpenger.iverksett.utbetaling.domene.Iverksetting import no.nav.dagpenger.iverksett.utbetaling.domene.behandlingId import no.nav.dagpenger.iverksett.utbetaling.domene.sakId import no.nav.dagpenger.iverksett.utbetaling.lagIverksettingEntitet import no.nav.dagpenger.iverksett.utbetaling.lagIverksettingsdata import no.nav.dagpenger.kontrakter.felles.somString import no.nav.dagpenger.kontrakter.felles.somUUID import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import java.time.LocalDate import java.util.UUID class IverksettingRepositoryTest : Integrasjonstest() { @Autowired private lateinit var iverksettingRepository: IverksettingRepository @Test fun `lagre og hent iverksett på fagsakId, forvent likhet`() { val iverksettingData: Iverksetting = lagIverksettingsdata( sakId = UUID.randomUUID(), behandlingId = UUID.randomUUID(), andelsdatoer = listOf(LocalDate.now(), LocalDate.now().minusDays(15)), ) iverksettingRepository.findByFagsakId(iverksettingData.fagsak.fagsakId.somString).also { assertEquals(0, it.size) } val iverksett = iverksettingRepository.insert(lagIverksettingEntitet(iverksettingData)) iverksettingRepository.findByFagsakId(iverksettingData.fagsak.fagsakId.somString).also { assertEquals(1, it.size) assertEquals(it[0], iverksett) } } @Test fun `lagre og hent iverksett på behandlingId og iverksettingId, forvent likhet`() { val tmp: Iverksetting = lagIverksettingsdata( sakId = UUID.randomUUID(), behandlingId = UUID.randomUUID(), andelsdatoer = listOf(LocalDate.now(), LocalDate.now().minusDays(15)), ) val iverksettingData = tmp.copy(behandling = tmp.behandling.copy(iverksettingId = "TEST123")) val iverksetting = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData.sakId.somString, behandlingId = iverksettingData.behandlingId.somUUID, iverksettingId = iverksettingData.behandling.iverksettingId, ) assertTrue(iverksetting.isEmpty()) val iverksett = iverksettingRepository.insert(lagIverksettingEntitet(iverksettingData)) val iverksetting2 = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData.sakId.somString, behandlingId = iverksettingData.behandlingId.somUUID, iverksettingId = iverksettingData.behandling.iverksettingId, ) assertTrue(iverksetting2.isNotEmpty()) assertEquals(iverksett, iverksetting2.first()) } @Test fun `lagre og hent iverksett på behandlingId og tom iverksettingId, forvent likhet`() { val iverksettingData: Iverksetting = lagIverksettingsdata( sakId = UUID.randomUUID(), behandlingId = UUID.randomUUID(), andelsdatoer = listOf(LocalDate.now(), LocalDate.now().minusDays(15)), ) val iverksetting = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData.sakId.somString, behandlingId = iverksettingData.behandlingId.somUUID, iverksettingId = iverksettingData.behandling.iverksettingId, ) assertTrue(iverksetting.isEmpty()) val iverksett = iverksettingRepository.insert(lagIverksettingEntitet(iverksettingData)) val iverksetting2 = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData.sakId.somString, behandlingId = iverksettingData.behandlingId.somUUID, iverksettingId = iverksettingData.behandling.iverksettingId, ) assertTrue(iverksetting2.isNotEmpty()) assertEquals(iverksett, iverksetting2.first()) } @Test fun `lagre og hent iverksett på fagsakId, behandlingId og tom iverksettingId, forvent 1 iverksetting per fagsak`() { val sakId1 = UUID.randomUUID() val sakId2 = UUID.randomUUID() val behandlingId = UUID.randomUUID() val iverksettingData1 = lagIverksettingsdata( sakId = sakId1, behandlingId = behandlingId, andelsdatoer = listOf(LocalDate.now(), LocalDate.now().minusDays(15)), ) val iverksettingData2 = lagIverksettingsdata( sakId = sakId2, behandlingId = behandlingId, andelsdatoer = listOf(LocalDate.now(), LocalDate.now().minusDays(15)), ) val iverksett1 = iverksettingRepository.insert(lagIverksettingEntitet(iverksettingData1)) val iverksett2 = iverksettingRepository.insert(lagIverksettingEntitet(iverksettingData2)) val iverksetting1 = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData1.sakId.somString, behandlingId = iverksettingData1.behandlingId.somUUID, iverksettingId = iverksettingData1.behandling.iverksettingId, ) val iverksetting2 = iverksettingRepository.findByFagsakAndBehandlingAndIverksetting( fagsakId = iverksettingData2.sakId.somString, behandlingId = iverksettingData2.behandlingId.somUUID, iverksettingId = iverksettingData2.behandling.iverksettingId, ) assertEquals(1, iverksetting1.size) assertEquals(iverksett1, iverksetting1.first()) assertEquals(1, iverksetting2.size) assertEquals(iverksett2, iverksetting2.first()) } }
1
Kotlin
1
0
bf943e6b800daa357f6584486b1e5e0d4f87e439
6,164
dp-iverksett
MIT License
generator/src/commonTest/kotlin/maryk/generator/kotlin/GenerateKotlinForEmbeddedDataModelTest.kt
marykdb
290,454,412
false
{"Kotlin": 3292487, "JavaScript": 1004}
package maryk.generator.kotlin import maryk.test.models.EmbeddedModel import kotlin.test.Test import kotlin.test.assertEquals val generatedKotlinForEmbeddedDataModel = """ package maryk.test.models import maryk.core.properties.DataModel import maryk.core.properties.definitions.string object EmbeddedModel : DataModel<EmbeddedModel>() { val value by string( index = 1u, default = "haha", regEx = "ha.*" ) } """.trimIndent() class GenerateKotlinForEmbeddedDataModelTest { @Test fun generateKotlinForSimpleModel() { val output = buildString { EmbeddedModel.generateKotlin("maryk.test.models") { append(it) } } assertEquals(generatedKotlinForEmbeddedDataModel, output) } }
5
Kotlin
1
8
1da24fb090889aaf712592bcdb34876cb502f13a
784
maryk
Apache License 2.0
pretty-dialog/src/main/java/com/fphoenixcorneae/animation/zoom/ZoomInBottomEnter.kt
FPhoenixCorneaE
288,119,870
false
null
package com.fphoenixcorneae.animation.zoom import android.animation.ObjectAnimator import android.view.View import com.fphoenixcorneae.animation.BaseAnimatorSet /** * @desc 底部放大进入动效 */ class ZoomInBottomEnter : BaseAnimatorSet() { override fun setAnimation(view: View) { view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) val height = view.measuredHeight.toFloat() animatorSet.playTogether( ObjectAnimator.ofFloat(view, "scaleX", 0.1f, 0.475f, 1f), ObjectAnimator.ofFloat(view, "scaleY", 0.1f, 0.475f, 1f), ObjectAnimator.ofFloat(view, "translationY", height, -60f, 0f), ObjectAnimator.ofFloat(view, "alpha", 0f, 1f, 1f) ) } init { duration = 600 } }
0
Kotlin
0
1
9851ad86c5042a4fa5473febada00d6bf356326a
782
PrettyDialog
Apache License 2.0
library/src/main/java/com/rosberry/android/debuggerman2/ui/adapter/DelegatedDebugAdapter.kt
rosberry
460,289,416
false
{"Kotlin": 35099}
package com.rosberry.android.debuggerman2.ui.adapter import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.rosberry.android.debuggerman2.entity.DebuggermanItem import com.rosberry.android.debuggerman2.entity.DebuggermanItem.Title class DelegatedDebugAdapter( private var items: List<DebuggermanItem> = listOf() ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val delegateManager by lazy { DelegateManager(items) } private val diffCallback = DiffCallback() init { if (items.isNotEmpty()) items = items.insertGroupHeaders() } override fun getItemCount(): Int = items.size override fun getItemViewType(position: Int): Int = delegateManager.getItemViewType(items[position]) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return delegateManager.onCreateViewHolder(parent, viewType) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { delegateManager.onBindViewHolder(holder, items[position]) } fun setItems(items: List<DebuggermanItem>) { val newItems = items.insertGroupHeaders() val diffResult = diffCallback.calculateDiff(this.items, newItems) delegateManager.onAdapterItemsChanged(newItems) [email protected] = newItems diffResult.dispatchUpdatesTo(this@DelegatedDebugAdapter) } fun updateItem(item: DebuggermanItem) { val index = this.items.indexOf(item) if (index >= 0) notifyItemChanged(index) } private fun List<DebuggermanItem>.insertGroupHeaders(): List<DebuggermanItem> { val groups = groupBy(DebuggermanItem::group) return mutableListOf<DebuggermanItem>().apply { groups.keys .sortedWith(nullsLast { _, _ -> 0 }) .forEach { group -> if (group != null) this.add(Title(group)) groups[group]?.let(this::addAll) } } } private class DiffCallback : DiffUtil.Callback() { private lateinit var old: List<DebuggermanItem> private lateinit var new: List<DebuggermanItem> fun calculateDiff(old: List<DebuggermanItem>, new: List<DebuggermanItem>): DiffUtil.DiffResult { this.old = old this.new = new return DiffUtil.calculateDiff(this) } override fun getOldListSize(): Int = old.size override fun getNewListSize(): Int = new.size override fun areItemsTheSame(oldPosition: Int, newPosition: Int): Boolean { return old[oldPosition] == new[newPosition] } override fun areContentsTheSame(oldPosition: Int, newPosition: Int): Boolean { return old[oldPosition] == new[newPosition] } } }
0
Kotlin
0
0
e94b9875dd2e7e9d618ef4c3fc38d1eb3b400825
2,901
Debuggerman2
MIT License
libtulip/src/jsMain/kotlin/com/tajmoti/multiplatform/JsTulipNetworkModule.kt
Tajmoti
391,138,914
false
null
package com.tajmoti.multiplatform import com.tajmoti.libtulip.di.ProxyType import com.tajmoti.libtulip.misc.webdriver.UrlRewriter import com.tajmoti.libtulip.setupTulipKtor import io.ktor.client.* import io.ktor.client.engine.js.* import org.koin.core.qualifier.qualifier import org.koin.dsl.module val jsNetworkModule = module { single { getAppHttpClient(proxy = true) } single(qualifier(ProxyType.PROXY)) { getAppHttpClient(proxy = true) } single(qualifier(ProxyType.DIRECT)) { getAppHttpClient(proxy = false) } } fun getAppHttpClient(proxy: Boolean): HttpClient { return HttpClient(Js) { setupTulipKtor(this) if (proxy) install(UrlRewriter) { wrapper = ::wrapUrlInCorsProxy } } }
6
Kotlin
0
1
7dd02fe23b3205967e02d0efff2b7efd191fe138
722
Tulip
MIT License
app/src/main/java/com/hal/kaiyan/App.kt
leihaogit
734,572,648
false
{"Kotlin": 236323}
package com.hal.kaiyan import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import androidx.appcompat.app.AppCompatDelegate import com.hal.kaiyan.base.BaseApp import com.hal.kaiyan.ui.base.Constant import com.hal.kaiyan.utils.AppUtils import com.tencent.mmkv.MMKV /** * ... * @author LeiHao * @date 2023/11/28 * @description 自定义的 Application 类,用于进行应用程序的全局配置和初始化工作。 */ class App : BaseApp() { companion object { //震动 fun vibrate() { val vibrator: Vibrator = appContext.getSystemService(Vibrator::class.java) if (vibrator.hasVibrator()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val vibrationEffect = VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK) vibrator.vibrate(vibrationEffect) } else { val amplitude = VibrationEffect.DEFAULT_AMPLITUDE val vibrationEffect = VibrationEffect.createOneShot(5, amplitude) vibrator.vibrate(vibrationEffect) } } } } override fun onCreate() { super.onCreate() MMKV.initialize(this) setNightMode() } //初始设置日间还是夜间模式还是跟随系统 private fun setNightMode() { when (AppUtils.decodeMMKV( Constant.KEY_NIGHT_MODE, Constant.FOLLOW_MODE )) { Constant.NIGHT_MODE -> { // 设置夜间模式的主题和样式 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } Constant.DAY_MODE -> { // 设置日间模式的主题和样式 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } Constant.FOLLOW_MODE -> { // 设置跟随系统的主题和样式 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) } else -> { //为空,设置为跟随系统,保存跟随系统标志 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) AppUtils.encodeMMKV( Constant.KEY_NIGHT_MODE, Constant.FOLLOW_MODE ) } } } }
0
Kotlin
0
1
b10b4643c8d04f18b930a538f7922adf51f0d674
2,272
kaiyan
Apache License 2.0
android/src/main/java/deckyfx/reactnative/printer/escposprinter/connection/serial/SerialConnection.kt
deckyfx
663,502,538
false
{"Kotlin": 283454, "TypeScript": 61671, "Java": 7149, "C": 5445, "Ruby": 3954, "JavaScript": 3698, "Objective-C": 2368, "Objective-C++": 1066, "Makefile": 817, "CMake": 317, "Swift": 282, "Shell": 89}
package deckyfx.reactnative.printer.escposprinter.connection.serial import android_serialport_api.SerialPort import deckyfx.reactnative.printer.escposprinter.connection.DeviceConnection import deckyfx.reactnative.printer.escposprinter.exceptions.EscPosConnectionException import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream class SerialConnection constructor( val path: String, var baudRate: Int? = DEFAULT_BAUD_RATE ) : DeviceConnection() { private var serial: SerialPort? = null override var outputStream: OutputStream? = null get() = serial?.outputStream override var inputStream: InputStream? = null get() = serial?.inputStream constructor( path: String, ) : this(path, DEFAULT_BAUD_RATE) init { if (baudRate == null) { baudRate = DEFAULT_BAUD_RATE } serial = SerialPort( File(path), baudRate!!, 0, ) } override fun connect(): DeviceConnection { if (isConnected) { return this } try { serial?.open() data = ByteArray(0) } catch (e: IOException) { e.printStackTrace() serial?.close() throw EscPosConnectionException("Unable to connect to Serial device.") } return this } override fun disconnect(): DeviceConnection { serial?.close() return this } companion object { const val DEFAULT_BAUD_RATE = 9600 } }
0
Kotlin
0
0
4edce0748f1a2e647eca5648c533b8b6a588ba77
1,422
react-native-printer
MIT License
data/src/main/java/com/foundy/data/repository/KeywordRepositoryImpl.kt
Hansung-Notification
504,857,617
false
null
package com.foundy.data.repository import android.util.Log import com.foundy.data.reference.DatabaseReferenceGetter import com.foundy.domain.model.Keyword import com.foundy.domain.repository.KeywordRepository import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.database.* import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import javax.inject.Inject import javax.inject.Named import com.foundy.domain.exception.NotSignedInException class KeywordRepositoryImpl @Inject constructor( @Named("keywords") private val keywordsReferenceGetter: DatabaseReferenceGetter, @Named("userKeywords") private val userKeywordsReferenceGetter: DatabaseReferenceGetter ) : KeywordRepository { /** * 유저의 키워드 목록 흐름을 반환한다. * * 반드시 이 함수를 호출하기 전에 로그인이 되어있어야 한다. 그렇지 않으면 [NotSignedInException]을 던진다. */ override fun getAll(): Flow<Result<List<Keyword>>> = callbackFlow { val reference = userKeywordsReferenceGetter() val postListener = object : ValueEventListener { override fun onCancelled(error: DatabaseError) { [email protected](Result.failure(error.toException())) } override fun onDataChange(dataSnapshot: DataSnapshot) { val items = dataSnapshot.children.map { ds -> ds.key?.let { Keyword(it) } } [email protected](Result.success(items.filterNotNull())) } } reference.addValueEventListener(postListener) awaitClose { reference.removeEventListener(postListener) } } /** * 키워드를 추가한다. * * 반드시 이 함수를 호출하기 전에 로그인이 되어있어야 한다. 그렇지 않으면 [NotSignedInException]을 던진다. */ override fun add(keyword: Keyword) { val userRef = userKeywordsReferenceGetter() userRef.child(keyword.title) .setValue(1) .addOnCompleteListener(onCompleteListener) keywordsReferenceGetter().child(keyword.title) .setValue(ServerValue.increment(1)) .addOnCompleteListener(onCompleteListener) } /** * 키워드를 삭제한다. * * 반드시 이 함수를 호출하기 전에 로그인이 되어있어야 한다. 그렇지 않으면 [NotSignedInException]을 던진다. */ override fun remove(keyword: Keyword) { val userRef = userKeywordsReferenceGetter() userRef.child(keyword.title) .removeValue() .addOnCompleteListener(onCompleteListener) keywordsReferenceGetter().child(keyword.title) .setValue(ServerValue.increment(-1)) .addOnCompleteListener(onCompleteListener) } private val onCompleteListener = OnCompleteListener<Void> { if (!it.isSuccessful) { Log.e(TAG, it.exception!!.stackTraceToString()) } } companion object { private const val TAG = "KeywordRepositoryImpl" } }
1
Kotlin
0
2
95b18d17bd2e4b94d69e00d1e72a6b77c83baf9f
3,003
Hansung_Android
MIT License
core/ui-state/src/main/kotlin/com/qt/app/core/utils/Utils.kt
alyx-d
845,106,252
false
{"Kotlin": 127869}
package com.qt.app.core.utils import android.content.Context import android.os.Build.VERSION.SDK_INT import android.widget.Toast import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import coil.ImageLoader import coil.decode.GifDecoder import coil.decode.ImageDecoderDecoder import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter fun main() { val s = "[img=图片]134[/img]123[emot=acfun,1111/]" val rex = Regex(pattern = "\\[img=图片].+\\[/img]|\\[emot=acfun,\\d+/]") rex.findAll(s).forEach { println(it.value) } // println(rex.replace(s, "-=-=-")) } object Util { private val dateFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") fun showToast(msg: String, context: Context) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show() } private var _imageLoader: ImageLoader? = null fun imageLoader(context: Context): ImageLoader = _imageLoader ?: run { _imageLoader = ImageLoader.Builder(context) .components { if (SDK_INT >= 28) { add(ImageDecoderDecoder.Factory()) } else { add(GifDecoder.Factory()) } } .crossfade(true) .build() _imageLoader!! } fun dateFormat(value: Long): String { return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneId.of("UTC+8")) .format(dateFormater) } } @Composable fun ComposableLifeCycle( lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit ) { DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { source, event -> onEvent(source, event) } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } }
0
Kotlin
0
0
b48dae0c188937526f2ffe11c15772d59a73f6fb
2,243
acfun-article
Apache License 2.0
app/src/main/java/com/debanshu777/compose_github/network/model/userStats/LanguagesX.kt
Debanshu777
467,621,052
false
{"Kotlin": 390827}
package com.debanshu777.compose_github.network.model.userStats import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class LanguagesX( @SerialName("colors") val colors: Colors = Colors(), @SerialName("favorites") val favorites: List<Favorite> = listOf(), @SerialName("indepth") val indepth: Boolean = false, // false @SerialName("sections") val sections: List<String> = listOf(), @SerialName("stats") val stats: Stats = Stats(), @SerialName("stats.recent") val statsRecent: StatsRecent = StatsRecent(), @SerialName("total") val total: Int = 0, // 6115273 @SerialName("unique") val unique: Int = 0 // 22 )
1
Kotlin
2
57
422904eb5e71737e7f527932bfe84253740ed35c
718
Github-Compose
MIT License
apps/etterlatte-brev-api/src/main/kotlin/no/nav/etterlatte/brev/dokument/DokumentRoute.kt
navikt
417,041,535
false
{"Kotlin": 4746046, "TypeScript": 1019807, "Handlebars": 21474, "Shell": 9939, "HTML": 1776, "CSS": 598, "Dockerfile": 520}
package no.nav.etterlatte.brev.dokument import io.ktor.http.HttpStatusCode import io.ktor.server.application.call import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.get import io.ktor.server.routing.post import io.ktor.server.routing.put import io.ktor.server.routing.route import no.nav.etterlatte.brev.dokarkiv.DokarkivService import no.nav.etterlatte.brev.hentinformasjon.Tilgangssjekker import no.nav.etterlatte.brev.journalpost.BrukerIdType import no.nav.etterlatte.libs.common.sak.Sak import no.nav.etterlatte.libs.common.withFoedselsnummer import no.nav.etterlatte.libs.ktor.brukerTokenInfo fun Route.dokumentRoute( safService: SafService, dokarkivService: DokarkivService, tilgangssjekker: Tilgangssjekker, ) { route("dokumenter") { post { withFoedselsnummer(tilgangssjekker) { foedselsnummer -> val result = safService.hentDokumenter(foedselsnummer.value, BrukerIdType.FNR, brukerTokenInfo) if (result.error == null) { call.respond(result.journalposter) } else { call.respond(result.error.statusCode, result.error.message) } } } post("{journalpostId}/ferdigstill") { val sak = call.receive<Sak>() val journalpostId = requireNotNull(call.parameters["journalpostId"]) { "JournalpostID er påkrevd for å kunne ferdigstille journalposten" } dokarkivService.ferdigstill(journalpostId, sak) call.respond(HttpStatusCode.OK) } put("{journalpostId}/tema/{nyttTema}") { val journalpostId = call.parameters["journalpostId"]!! val nyttTema = call.parameters["nyttTema"]!! dokarkivService.endreTema(journalpostId, nyttTema) call.respond(HttpStatusCode.OK) } get("{journalpostId}") { val journalpostId = call.parameters["journalpostId"]!! val result = safService.hentJournalpost(journalpostId, brukerTokenInfo) call.respond(result.journalpost ?: HttpStatusCode.NotFound) } get("{journalpostId}/{dokumentInfoId}") { val journalpostId = call.parameters["journalpostId"]!! val dokumentInfoId = call.parameters["dokumentInfoId"]!! val innhold = safService.hentDokumentPDF(journalpostId, dokumentInfoId, brukerTokenInfo.accessToken()) call.respond(innhold) } } }
12
Kotlin
0
5
b5e8a7438c498c3bbd6170cfc4eb9818729ff6f7
2,615
pensjon-etterlatte-saksbehandling
MIT License
kotlin-project/rekindle-book-store-aqa/domain/core/src/main/kotlin/com/rekindle/book/store/domain/valueobjects/Order.kt
amfibolos
845,646,691
false
{"Kotlin": 69165, "C#": 51552, "TypeScript": 5221, "JavaScript": 581}
package com.rekindle.book.store.domain.valueobjects data class Order( var customerId: String, var bookstoreId: String, var items: List<Item>, var address: Address ) : ValueObject
0
Kotlin
0
0
30bae3e9408d89ffb5c1b028b2729411426313ad
196
rekindle-aqa
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/request/im/ImHistoryRequest.kt
uakihir0
794,979,552
false
{"Kotlin": 945304, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package work.socialhub.kslack.api.methods.request.im import work.socialhub.kslack.api.methods.SlackApiRequest class ImHistoryRequest( /** Authentication token. Requires scope: `im:history` */ override var token: String?, /** Direct message channel to fetch history for. */ var channel: String?, /** Start of time range of messages to include in results. */ var oldest: String?, /** End of time range of messages to include in results. */ var latest: String?, /** Include messages with latest or oldest timestamp in results. */ var isInclusive: Boolean, /** Number of messages to return, between 1 and 1000. */ var count: Int?, /** Include `unread_count_display` in the output? */ var isUnreads: Boolean ) : SlackApiRequest
5
Kotlin
0
0
4d7fe4d7658ebe5e7daac29f727db96a09deaead
780
kslack
MIT License
_5Arrays/src/main/kotlin/3.0initializers.kt
Meus-Livros-Lidos
690,208,771
false
{"Kotlin": 146138}
fun main() { var letters = charArrayOf('C', 'S', '1', '9', '9') println(letters[0]) println(letters[4]) }
0
Kotlin
0
1
09ada25ca613cb3bd46806e45b78390eca8470c7
117
LearnCsOnline-Kotlin
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/unit/service/FeatureFlagServiceTest.kt
ministryofjustice
515,276,548
false
{"Kotlin": 6885855, "Shell": 8075, "Dockerfile": 1780}
package uk.gov.justice.digital.hmpps.approvedpremisesapi.unit.service import io.flipt.api.FliptClient import io.flipt.api.evaluation.Evaluation import io.flipt.api.evaluation.models.BooleanEvaluationResponse import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import uk.gov.justice.digital.hmpps.approvedpremisesapi.service.FeatureFlagService import uk.gov.justice.digital.hmpps.approvedpremisesapi.service.SentryService class FeatureFlagServiceTest { val client = mockk<FliptClient>() val sentryService = mockk<SentryService>() @ParameterizedTest @CsvSource("true", "false") fun `getBooleanFlag if flipt is disabled then return default value`(default: Boolean) { val service = FeatureFlagService( client = null, sentryService, ) val result = service.getBooleanFlag("theKey", default) assertThat(result).isEqualTo(default) } @ParameterizedTest @CsvSource("true", "false") fun `getBooleanFlag return flipt client value`(enabled: Boolean) { val evaluation = mockk<Evaluation>() val booleanEvaluationResponse = mockk<BooleanEvaluationResponse>() every { client.evaluation() } returns evaluation every { evaluation.evaluateBoolean(any()) } returns booleanEvaluationResponse every { booleanEvaluationResponse.isEnabled } returns enabled val service = FeatureFlagService(client, sentryService) val result = service.getBooleanFlag("theKey", false) assertThat(result).isEqualTo(enabled) } @ParameterizedTest @CsvSource("true", "false") fun `getBooleanFlag if exception occurs log it then return default value`(default: Boolean) { val exception = RuntimeException("oh dear") every { client.evaluation() } throws exception every { sentryService.captureException(any()) } returns Unit val service = FeatureFlagService(client, sentryService) val result = service.getBooleanFlag("theKey", default) verify { sentryService.captureException(exception) } assertThat(result).isEqualTo(default) } }
32
Kotlin
1
4
bc7d57577d3f4c2521132c4a3da340e23729b0e5
2,178
hmpps-approved-premises-api
MIT License
MarvelApp/app/src/main/java/com/example/marvelapp/di/RepositoryModule.kt
salvaMsanchez
753,067,204
false
{"Kotlin": 84359}
package com.example.marvelapp.di import com.example.marvelapp.data.Repository import com.example.marvelapp.domain.RepositoryInterface import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds abstract fun bindsRepositoryInterface(repository: Repository): RepositoryInterface }
0
Kotlin
0
0
93162cec0bda0228216c5f1191486734df2b2978
434
MarvelApp-Android
MIT License
presentation/src/main/java/me/androidbox/busbyfood/screen/ListHomeScreen.kt
steve1rm
508,604,702
false
null
package me.androidbox.busbyfood.screen import androidx.compose.material.Scaffold import androidx.compose.material.Text 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.ui.graphics.Color import androidx.compose.ui.unit.sp import androidx.navigation.NavController import me.androidbox.busbyfood.viewmodel.FoodListViewModel @Composable fun ListHomeScreen( foodListViewModel: FoodListViewModel, navController: NavController ) { foodListViewModel.fetchComplexSearch() val listOfComplexSearch by foodListViewModel.complexSearchStateFlow.collectAsState() val rememberScaffoldState = rememberScaffoldState() Scaffold( scaffoldState = rememberScaffoldState, topBar = { TopAppBar { Text(text = "Busby Food", color = Color.White, fontSize = 24.sp) } }, content = { ListComplexSearchContent(responseState = listOfComplexSearch, navController = navController) } ) }
0
Kotlin
0
0
97044f8d2c57ef608e19e5f6eb59a0de449334bd
1,180
BusbyFood
MIT License
serve-app/student/src/main/java/org/evidyaloka/student/ui/doubt/DoubtViewModel.kt
Sunbird-Serve
607,662,046
false
null
package org.evidyaloka.student.ui.rtc import androidx.lifecycle.* import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import dagger.hilt.android.lifecycle.HiltViewModel import org.evidyaloka.core.Constants.StudentConst import org.evidyaloka.core.student.datasource.doubt.DoubtDataSource import org.evidyaloka.core.student.datasource.doubt.DoubtDataSourceFactory import org.evidyaloka.core.student.model.Doubt import org.evidyaloka.core.student.repository.StudentRepository import org.evidyaloka.student.ui.BaseViewModel import javax.inject.Inject @HiltViewModel class DoubtViewModel @Inject constructor( private val repo: StudentRepository ) : BaseViewModel() { private var listDoubt : LiveData<PagedList<Doubt>> = MutableLiveData<PagedList<Doubt>>() private var doubtSourceLiveData = MutableLiveData<DoubtDataSource>() var doubtDetailsObserver = MutableLiveData<Int>() lateinit var config: PagedList.Config init { config = PagedList.Config.Builder() .setPageSize(StudentConst.DOUBT_PAGINATION_COUNT) .setEnablePlaceholders(false) .build() } fun getDoubts(doubtId:Int? = null, offeringId:Int? = null, topicId : Int? = null, subtopicId: Int?= null): LiveData<PagedList<Doubt>> { val factory = DoubtDataSourceFactory(doubtId, offeringId, topicId, subtopicId, repo,viewModelScope) doubtDetailsObserver = factory.doubtDetailObserver() doubtSourceLiveData = factory.doubtDataSource() listDoubt = LivePagedListBuilder(factory,config).build() return listDoubt } fun getStudentCourses() = requestWithRetry { repo.getStudentOfferings() } fun getSelectedStudent() = repo.getSelectedStudent() }
0
Kotlin
1
0
6d8d170333e2d32c808e608863e02e076dc06a73
1,756
serve-beta-android-app
MIT License
packages/SystemUI/src/com/android/systemui/common/shared/model/Text.kt
liu-wanshun
595,904,109
true
null
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.systemui.common.shared.model import android.annotation.StringRes import android.content.Context /** * Models a text, that can either be already [loaded][Text.Loaded] or be a [reference] * [Text.Resource] to a resource. */ sealed class Text { data class Loaded( val text: String?, ) : Text() data class Resource( @StringRes val res: Int, ) : Text() companion object { /** * Returns the loaded test string, or null if we don't have one. * * Prefer [com.android.systemui.common.ui.binder.TextViewBinder.bind] over this method. This * should only be used for testing or concatenation purposes. */ fun Text?.loadText(context: Context): String? { return when (this) { null -> null is Loaded -> this.text is Resource -> context.getString(this.res) } } } }
0
Java
1
2
e99201cd9b6a123b16c30cce427a2dc31bb2f501
1,581
platform_frameworks_base
Apache License 2.0
src/code/gfx/Sprite0x1.kt
Jki10
111,472,876
true
{"Markdown": 2, "Java": 75, "Kotlin": 10}
package code.gfx /** * Created on 17-11-05. * @author brian * @since 2017/11/05 * @param row this is the row of the sprite * @param column The column of the sprite */ data class Sprite0x1(val column: Int, val row: Int) { init { check(column in 1..128 && row in 1..128) } fun update(bit: Int) = Sprite0x2(this.row, this.column, bit) }
0
Java
0
0
da04a6d7edacce8f22f7337973ca23f423a9e1fb
347
Camasia
Apache License 2.0
src/main/kotlin/komet/editor/ImGuiLayout.kt
cometflaretech
450,687,142
false
{"Kotlin": 80738, "GLSL": 1138}
package komet.editor import komet.Window import komet.scene.Scene import imgui.*; import imgui.callback.* import imgui.flag.* import imgui.gl3.* import imgui.internal.ImGuiWindow import imgui.type.ImBoolean import komet.KeyListener import komet.MouseListener import org.lwjgl.glfw.GLFW.* class ImGuiLayer(private val glfwWindow: Long) { // Mouse cursors provided by GLFW private val mouseCursors = LongArray(ImGuiMouseCursor.COUNT) // LWJGL3 renderer (SHOULD be initialized) private val imGuiGl3 = ImGuiImplGl3() // Initialize Dear ImGui. fun initImGui() { // IMPORTANT!! // This line is critical for Dear ImGui to work. ImGui.createContext() // ------------------------------------------------------------ // Initialize ImGuiIO config val io: ImGuiIO = ImGui.getIO() io.iniFilename = "imgui.ini" io.addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard) // Navigation with keyboard io.addConfigFlags(ImGuiConfigFlags.DockingEnable) io.backendFlags = ImGuiBackendFlags.HasMouseCursors // Mouse cursors to display while resizing windows etc. io.backendPlatformName = "imgui_java_impl_glfw" // ------------------------------------------------------------ // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array. val keyMap = IntArray(ImGuiKey.COUNT) keyMap[ImGuiKey.Tab] = GLFW_KEY_TAB keyMap[ImGuiKey.LeftArrow] = GLFW_KEY_LEFT keyMap[ImGuiKey.RightArrow] = GLFW_KEY_RIGHT keyMap[ImGuiKey.UpArrow] = GLFW_KEY_UP keyMap[ImGuiKey.DownArrow] = GLFW_KEY_DOWN keyMap[ImGuiKey.PageUp] = GLFW_KEY_PAGE_UP keyMap[ImGuiKey.PageDown] = GLFW_KEY_PAGE_DOWN keyMap[ImGuiKey.Home] = GLFW_KEY_HOME keyMap[ImGuiKey.End] = GLFW_KEY_END keyMap[ImGuiKey.Insert] = GLFW_KEY_INSERT keyMap[ImGuiKey.Delete] = GLFW_KEY_DELETE keyMap[ImGuiKey.Backspace] = GLFW_KEY_BACKSPACE keyMap[ImGuiKey.Space] = GLFW_KEY_SPACE keyMap[ImGuiKey.Enter] = GLFW_KEY_ENTER keyMap[ImGuiKey.Escape] = GLFW_KEY_ESCAPE keyMap[ImGuiKey.KeyPadEnter] = GLFW_KEY_KP_ENTER keyMap[ImGuiKey.A] = GLFW_KEY_A keyMap[ImGuiKey.C] = GLFW_KEY_C keyMap[ImGuiKey.V] = GLFW_KEY_V keyMap[ImGuiKey.X] = GLFW_KEY_X keyMap[ImGuiKey.Y] = GLFW_KEY_Y keyMap[ImGuiKey.Z] = GLFW_KEY_Z io.setKeyMap(keyMap) // ------------------------------------------------------------ // Mouse cursors mapping mouseCursors[ImGuiMouseCursor.Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) mouseCursors[ImGuiMouseCursor.TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR) mouseCursors[ImGuiMouseCursor.ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) mouseCursors[ImGuiMouseCursor.ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR) mouseCursors[ImGuiMouseCursor.ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR) mouseCursors[ImGuiMouseCursor.ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) mouseCursors[ImGuiMouseCursor.ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) mouseCursors[ImGuiMouseCursor.Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR) mouseCursors[ImGuiMouseCursor.NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // ------------------------------------------------------------ // GLFW callbacks to handle user input glfwSetKeyCallback(glfwWindow) { w, key, scancode, action, mods -> if (action == GLFW_PRESS) { io.setKeysDown(key, true) } else if (action == GLFW_RELEASE) { io.setKeysDown(key, false) } io.keyCtrl = io.getKeysDown(GLFW_KEY_LEFT_CONTROL) || io.getKeysDown(GLFW_KEY_RIGHT_CONTROL) io.keyShift = io.getKeysDown(GLFW_KEY_LEFT_SHIFT) || io.getKeysDown(GLFW_KEY_RIGHT_SHIFT) io.keyAlt = io.getKeysDown(GLFW_KEY_LEFT_ALT) || io.getKeysDown(GLFW_KEY_RIGHT_ALT) io.keySuper = io.getKeysDown(GLFW_KEY_LEFT_SUPER) || io.getKeysDown(GLFW_KEY_RIGHT_SUPER) if (!io.wantCaptureKeyboard) { KeyListener.keyCallback(w, key, scancode, action, mods) } } glfwSetCharCallback(glfwWindow) { _, c -> if (c != GLFW_KEY_DELETE) { io.addInputCharacter(c) } } glfwSetMouseButtonCallback(glfwWindow) { w, button, action, mods -> val mouseDown = BooleanArray(5) mouseDown[0] = button == GLFW_MOUSE_BUTTON_1 && action != GLFW_RELEASE mouseDown[1] = button == GLFW_MOUSE_BUTTON_2 && action != GLFW_RELEASE mouseDown[2] = button == GLFW_MOUSE_BUTTON_3 && action != GLFW_RELEASE mouseDown[3] = button == GLFW_MOUSE_BUTTON_4 && action != GLFW_RELEASE mouseDown[4] = button == GLFW_MOUSE_BUTTON_5 && action != GLFW_RELEASE io.setMouseDown(mouseDown) if (!io.wantCaptureMouse && mouseDown[1]) { ImGui.setWindowFocus(null) } if (!io.wantCaptureMouse || GameViewWindow.wantCaptureMouse) { MouseListener.mouseButtonCallback(w, button, action, mods) } } glfwSetScrollCallback(glfwWindow) { _, xOffset, yOffset -> io.mouseWheelH = io.mouseWheelH + xOffset.toFloat() io.mouseWheel = io.mouseWheel + yOffset.toFloat() //if (!io.wantCaptureMouse) { // todo. enable? // MouseListener.mouseScrollCallback(w, xOffset, yOffset) //} } io.setSetClipboardTextFn(object : ImStrConsumer() { override fun accept(s: String?) { glfwSetClipboardString(glfwWindow, s) } }) io.setGetClipboardTextFn(object : ImStrSupplier() { override fun get(): String { val clipboardString = glfwGetClipboardString(glfwWindow) return clipboardString ?: "" } }) // Fonts configuration val fontAtlas = io.fonts val fontConfig = ImFontConfig() fontConfig.glyphRanges = fontAtlas.glyphRangesDefault fontConfig.pixelSnapH = true fontAtlas.addFontFromFileTTF("assets/fonts/segoeui.ttf", 32f, fontConfig) fontConfig.destroy() // Method initializes LWJGL3 renderer. // This method SHOULD be called after you've initialized your ImGui configuration (fonts and so on). // ImGui context should be created as well. imGuiGl3.init("#version 460 core") } fun update(dt: Float, scene: Scene) { startFrame(dt) ImGui.newFrame() setupDockSpace() scene.sceneImgui() GameViewWindow.imgui() ImGui.end() ImGui.render() endFrame() } private fun startFrame(deltaTime: Float) { // Get window properties and mouse position val winWidth = floatArrayOf(Window.width.toFloat()) val winHeight = floatArrayOf(Window.height.toFloat()) val mousePosX = doubleArrayOf(0.0) val mousePosY = doubleArrayOf(0.0) glfwGetCursorPos(glfwWindow, mousePosX, mousePosY) // We SHOULD call those methods to update Dear ImGui state for the current frame val io: ImGuiIO = ImGui.getIO() io.setDisplaySize(winWidth[0], winHeight[0]) io.setDisplayFramebufferScale(1f, 1f) io.setMousePos(mousePosX[0].toFloat(), mousePosY[0].toFloat()) io.deltaTime = deltaTime // Update the mouse cursor val imguiCursor: Int = ImGui.getMouseCursor() glfwSetCursor(glfwWindow, mouseCursors[imguiCursor]) glfwSetInputMode(glfwWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL) } private fun endFrame() { // After Dear ImGui prepared a draw data, we use it in the LWJGL3 renderer. // At that moment ImGui will be rendered to the current OpenGL context. imGuiGl3.renderDrawData(ImGui.getDrawData()) } // If you want to clean a room after yourself - do it by yourself private fun destroyImGui() { imGuiGl3.dispose() ImGui.destroyContext() } private fun setupDockSpace() { var windowFlags = ImGuiWindowFlags.MenuBar or ImGuiWindowFlags.NoDocking ImGui.setNextWindowPos(0f, 0f, ImGuiCond.Always) ImGui.setNextWindowSize(Window.width.toFloat(), Window.height.toFloat()) ImGui.pushStyleVar(ImGuiStyleVar.WindowRounding, 0f) ImGui.pushStyleVar(ImGuiStyleVar.WindowBorderSize, 0f) windowFlags = windowFlags or ImGuiWindowFlags.NoTitleBar or ImGuiWindowFlags.NoCollapse or ImGuiWindowFlags.NoResize or ImGuiWindowFlags.NoMove or ImGuiWindowFlags.NoBringToFrontOnFocus or ImGuiWindowFlags.NoNavFocus ImGui.begin("DockSpace Demo", ImBoolean(true), windowFlags) ImGui.popStyleVar(2) ImGui.dockSpace(ImGui.getID("DockSpace")) } }
0
Kotlin
0
3
17687363cb9573c299dc6501c7515ceac6a82bd0
9,188
komet_engine
Apache License 2.0
android/src/main/kotlin/lam/flutter/plugin/flutter_plugin_tk/ContactUtils.kt
lamdev99
473,455,848
false
null
package lam.flutter.plugin.flutter_plugin_tk import android.app.Activity import android.provider.ContactsContract import android.util.Log import com.google.gson.Gson import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext object ContactUtils { fun getAllContact(act: Activity?, onReturnAllContact: (ArrayList<Any>) -> Unit) { val listContact = arrayListOf<Any>() act?.contentResolver?.let { CoroutineScope(Dispatchers.IO).launch { val cursorContact = it.query( ContactsContract.Contacts.CONTENT_URI, null, null, null, null ) try { cursorContact?.let { ct -> while (ct.moveToNext()) { val id = ct.getString(ct.getColumnIndexOrThrow(ContactsContract.Contacts._ID)) val name = ct.getString(ct.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)) if (ct.getInt(ct.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { val cursor = it.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf(id), null ) cursor?.let { cr -> while (cr.moveToNext()) { val phoneNo = cr.getString(cr.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)) val gson = Gson() val contact = Contact(name = name, number = phoneNo) withContext(Dispatchers.Default) { listContact.add(gson.toJson(contact)) } } cr.close() } } } } withContext(Dispatchers.Main) { onReturnAllContact(listContact) } } catch (ex: Exception) { Log.d("FlutterPlugin105", ex.toString()) } cursorContact?.close() } } } }
0
Kotlin
1
0
7022d124277fc4b7bc725694ac050a69dbdbcea2
2,929
flutter_plugin
Apache License 2.0
rabbit-base/src/main/java/com/susion/rabbit/base/config/RabbitDaoProviderConfig.kt
SusionSuc
210,506,798
false
null
package com.susion.rabbit.base.config import org.greenrobot.greendao.AbstractDao /** * susionwang at 2019-10-28 * greendao 数据存储提供类 */ class RabbitDaoProviderConfig(val clazz: Class<Any>, val dao: AbstractDao<Any, Long>)
9
Kotlin
146
998
f1d1faf9f69b4ec162ae2215e9338dd1d7bdc893
224
rabbit-client
MIT License
src/examples/kotlin/net/dinkla/raytracer/examples/World57.kt
jdinkla
38,753,756
false
{"Kotlin": 490829, "Shell": 239}
package net.dinkla.raytracer.examples import net.dinkla.raytracer.colors.Color import net.dinkla.raytracer.math.Normal import net.dinkla.raytracer.math.Point3D import net.dinkla.raytracer.samplers.MultiJittered import net.dinkla.raytracer.samplers.Sampler import net.dinkla.raytracer.utilities.Ply import net.dinkla.raytracer.world.Builder import net.dinkla.raytracer.world.World import net.dinkla.raytracer.world.WorldDefinition object World57 : WorldDefinition { val sampler = Sampler(MultiJittered, 2500, 1000) private const val NUM_AMBIENT_SAMPLES = 4 init { sampler.mapSamplesToHemiSphere(1.0) } override val id: String = "World57.kt" override fun world(): World = Builder.build { metadata { id(id) } // TODO camera(d: 1000, eye: p(8, 1, 7), lookAt: p(11.2, 1, 0), numThreads: 64, ray: SampledRenderer, raySampler: sampler, rayNumSamples: 2 ) camera(d = 1000.0, eye = p(0, 1, -10), lookAt = p(0.0, 1.0, 0.0)) ambientOccluder(minAmount = Color.WHITE, sampler = sampler, numSamples = NUM_AMBIENT_SAMPLES) lights { pointLight(location = p(0, 5, 5), ls = 1.0) } materials { reflective(id = "gray", cd = c(1.0), ka = 0.5, kd = 0.5) phong(id = "yellow", cd = c(1, 1, 0), ka = 0.5, kd = 0.5, ks = 0.25, exp = 4.0) phong(id = "orange", cd = c(1.0, 0.5, 0.0), ka = 0.5, kd = 0.25, ks = 0.55, exp = 2.0) phong(id = "chocolate", cd = c(0.5647, 0.1294, 0.0), ka = 0.5, kd = 0.25, ks = 0.55, exp = 2.0) } val bunny = Ply.fromFile( fileName = "resources/bunny4K.ply", isSmooth = true, material = this.world.materials["chocolate"]!! ) objects { plane(material = "orange", point = Point3D.ORIGIN, normal = Normal.UP) // plane(material = "yellow", point = p(0, 1000, 0), normal = Normal.DOWN) for (i in listOf(-10, -5, 0, 5, 10)) { instance(material = "chocolate", of = bunny.compound) { scale(v(15.0, 15.0, 15.0)) translate(v(i.toDouble(), 0.0, 0.0)) } } } } }
0
Kotlin
2
5
fdf196ff5370a5e64f27c6e7ea66141a25d17413
2,234
from-the-ground-up-ray-tracer
Apache License 2.0
src/main/kotlin/io/realworld/conduit/user/infrastructure/api/ContextExtensions.kt
Davidonium
217,222,926
false
null
package io.realworld.conduit.user.infrastructure.api import io.javalin.http.Context import io.realworld.conduit.shared.domain.ConduitException import io.realworld.conduit.user.domain.UserId fun Context.requireCurrentUserId(): UserId { return currentUserId() ?: throw ConduitException("User not logged in") } fun Context.currentUserId(): UserId? { return attribute("userId") } private const val AUTHORIZATION_HEADER = "Authorization" fun Context.token(): String? { return header(AUTHORIZATION_HEADER)?.replace("Token ", "") } fun Context.requireToken(): String { return token() ?: throw ConduitException("Token is missing from the request") }
0
Kotlin
1
3
3204f521806dfde901f415cdd4fcdfd5446a6524
664
realworld-kotlin-javalin-jooq
MIT License
common/src/main/java/dev/arunkumar/common/os/HandlerExecutor.kt
arunkumar9t2
156,014,529
false
null
/* * Copyright 2021 Arunkumar * * 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 dev.arunkumar.common.os import android.os.Handler import android.os.Looper import java.util.concurrent.Executor class HandlerExecutor(private val handler: Handler) : Executor { override fun execute(command: Runnable) { if (Looper.myLooper() == handler.looper) { command.run() } else { handler.post(command) } } }
2
Kotlin
9
48
f6cdee22071167630d902a3713c6ee6dc7583f6e
944
base-android
Apache License 2.0
src/com/puzzletimer/puzzles/Other.kt
unquenchedservant
370,853,858
true
{"Kotlin": 1024655}
package com.puzzletimer.puzzles import com.puzzletimer.solvers.RubiksClockSolver.State.rotateWheel import com.puzzletimer.puzzles.Puzzle import com.puzzletimer.models.PuzzleInfo import com.puzzletimer.graphics.Plane import com.puzzletimer.models.ColorScheme import com.puzzletimer.graphics.Mesh import java.awt.Color import com.puzzletimer.graphics.Matrix44 import com.puzzletimer.graphics.Vector3 import java.util.HashMap import com.puzzletimer.graphics.Face import com.puzzletimer.puzzles.RubiksPocketCube import com.puzzletimer.puzzles.RubiksCube import com.puzzletimer.puzzles.RubiksRevenge import com.puzzletimer.puzzles.ProfessorsCube import com.puzzletimer.puzzles.VCube6 import com.puzzletimer.puzzles.VCube7 import com.puzzletimer.puzzles.SS8 import com.puzzletimer.puzzles.SS9 import com.puzzletimer.puzzles.RubiksClock import com.puzzletimer.puzzles.Megaminx import com.puzzletimer.puzzles.Pyraminx import com.puzzletimer.puzzles.Square1 import com.puzzletimer.puzzles.Skewb import com.puzzletimer.puzzles.FloppyCube import com.puzzletimer.puzzles.TowerCube import com.puzzletimer.puzzles.RubiksTower import com.puzzletimer.puzzles.RubiksDomino import com.puzzletimer.solvers.RubiksClockSolver class Other : Puzzle { override val puzzleInfo: PuzzleInfo get() = PuzzleInfo("OTHER") override fun toString(): String { return puzzleInfo.description } override fun getScrambledPuzzleMesh(colorScheme: ColorScheme, sequence: Array<String>): Mesh? { return Mesh(arrayOfNulls(0)) } }
0
Kotlin
0
0
7e9c509c24ece82b1c02e349e61deb9316736f86
1,534
prisma
MIT License
app/src/main/java/com/chenguang/simpleclock/dagger/component/ApplicationComponent.kt
lcgforever
229,995,622
false
null
package com.chenguang.simpleclock.dagger.component import android.content.Context import com.chenguang.simpleclock.SimpleClockApplication import com.chenguang.simpleclock.dagger.annotation.ForApplication import com.chenguang.simpleclock.dagger.module.ApplicationModule import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton /** * Application component wrapping application scope dependencies */ @Singleton @Component( modules = [ AndroidInjectionModule::class, AndroidSupportInjectionModule::class, ApplicationModule::class ] ) interface ApplicationComponent : AndroidInjector<SimpleClockApplication> { @ForApplication fun provideApplicationContext(): Context @Component.Factory interface Factory { fun create(@BindsInstance @ForApplication context: Context): ApplicationComponent } }
0
Kotlin
0
0
0421c994cac14e762f1fb4c01e128d8b4ad5015b
1,022
SimpleClock
MIT License
app/src/main/java/com/sritadip/memorygame/models/BoardSize.kt
Srihitha18798
455,051,314
false
null
package com.sritadip.memorygame.models enum class BoardSize(val numCards: Int) { EASY(numCards = 8), MEDIUM(numCards = 18), HARD(numCards = 24); companion object { fun getByValue(value: Int) = values().first { it.numCards == value } } fun getWidth(): Int { return when (this) { EASY -> 2 MEDIUM -> 3 HARD -> 4 } } fun getHeight(): Int { return numCards / getWidth() } fun getNumPairs(): Int { return numCards / 2 } }
0
Kotlin
1
1
193c453c7c003fa714a85eaa9714de56a8082492
542
MemoryGame
Apache License 2.0
app/src/main/java/com/example/expensetrackerapp/WalletScreen.kt
Lerampen
758,345,582
false
{"Kotlin": 130231}
package com.example.expensetrackerapp import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background 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.fillMaxHeight 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.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.Send import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.QrCodeScanner import androidx.compose.material.icons.outlined.ShoppingCart import androidx.compose.material3.Card import androidx.compose.material3.CardColors import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.res.colorResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.expensetrackerapp.ui.theme.ExpenseTrackerAppTheme import com.example.expensetrackerapp.ui.theme.poppinsFontFamily @Composable fun WalletScreen() { Box(modifier = Modifier .fillMaxSize() .background( color = colorResource(id = R.color.green_hue) )) { Column( modifier = Modifier .fillMaxSize() , horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box( modifier = Modifier .fillMaxWidth() .fillMaxHeight(0.10f), ) Column(modifier = Modifier .fillMaxSize() .clip( RoundedCornerShape( topStart = 32.dp, topEnd = 32.dp ) ) .background(color = Color.White), horizontalAlignment = Alignment.CenterHorizontally) { Spacer(modifier = Modifier.height(16.dp)) BalanceComp() Spacer(modifier = Modifier.height(16.dp)) TransactionsComp() Row( modifier = Modifier.padding(4.dp) ) { } Spacer(modifier = Modifier.width(16.dp)) TabSwitcher() } } } } @Preview(showBackground = true, apiLevel = 34) @Composable fun WalletPreview() { ExpenseTrackerAppTheme { WalletScreen() } } @Composable fun BalanceComp() { Column(modifier = Modifier.padding(top = 8.dp)) { Text( text = "Total Balance", fontFamily = poppinsFontFamily, fontWeight = FontWeight.Normal, textAlign = TextAlign.Center ) Text( text = "$12,385.00", fontFamily = poppinsFontFamily, fontWeight = FontWeight.Normal, fontSize = 40.sp ) } } @Preview(showBackground = true, apiLevel = 34) @Composable fun BalanceCompPreview() { ExpenseTrackerAppTheme { BalanceComp() } } @Composable fun TransactionsComp() { Row(modifier = Modifier.padding(horizontal = 8.dp)) { Column { OutlinedButton( onClick = { /*TODO*/ }, modifier = Modifier.size(80.dp), shape = MaterialTheme.shapes.medium, border = BorderStroke( width = 1.dp, color = colorResource( id = R.color.green_hue ) ) ) { Icon( imageVector = Icons.Outlined.Add, contentDescription = "Add", tint = colorResource( id = R.color.green_hue ) ) } Spacer(modifier = Modifier.height(4.dp)) Text( text = "Add", modifier = Modifier.padding(horizontal = 12.dp), fontFamily = poppinsFontFamily, textAlign = TextAlign.Center ) } Spacer(modifier = Modifier.width(12.dp)) Column { OutlinedButton( onClick = { /*TODO*/ }, modifier = Modifier.size(80.dp), shape = MaterialTheme.shapes.medium, border = BorderStroke( width = 1.dp, color = colorResource( id = R.color.green_hue ) ) ) { Icon( imageVector = Icons.Outlined.QrCodeScanner, contentDescription = "Scan", tint = colorResource( id = R.color.green_hue ) ) } Spacer(modifier = Modifier.height(4.dp)) Text( text = "Scan", fontFamily = poppinsFontFamily, modifier = Modifier.padding(horizontal = 12.dp) ) } Spacer(modifier = Modifier.width(12.dp)) Column { OutlinedButton( onClick = { /*TODO*/ }, modifier = Modifier.size(80.dp), shape = MaterialTheme.shapes.medium, border = BorderStroke( width = 1.dp, color = colorResource( id = R.color.green_hue ) ) ) { Icon( imageVector = Icons.AutoMirrored.Outlined.Send, contentDescription = "Send", tint = colorResource( id = R.color.green_hue ) ) } Spacer(modifier = Modifier.height(4.dp)) Text( text = "Send", fontFamily = poppinsFontFamily, modifier = Modifier.padding(horizontal = 12.dp) ) } } } @Preview(showBackground = true, apiLevel = 34) @Composable fun TransactPreview() { ExpenseTrackerAppTheme { TransactionsComp() } } @Composable fun CardComp() { Card( elevation = CardDefaults.cardElevation(8.dp), onClick = { /*TODO*/ }, shape = RoundedCornerShape(16.dp), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.mojito_breeze) ), modifier = Modifier.padding(12.dp) ) { Row (modifier = Modifier.padding(20.dp)){ IconButton( onClick = { /*TODO*/ }, modifier = Modifier.background( color = colorResource(id = R.color.candy_floss ), shape = RoundedCornerShape(12.dp) ) ) { Icon(imageVector = Icons.Outlined.ShoppingCart, contentDescription = "Shopping" ) } Spacer(modifier = Modifier.width(8.dp)) Column(modifier = Modifier.weight(1f)) { Row { Text( text = "Shopping", fontFamily = poppinsFontFamily, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.weight(1f)) Text( text = "-$700", fontFamily = poppinsFontFamily, fontWeight = FontWeight.SemiBold, color = Color.Red ) } Row { Text(text = "Puma Store", fontFamily = poppinsFontFamily, fontSize = 12.sp) Spacer(modifier = Modifier.weight(1f)) Text(text = "Cash", fontFamily = poppinsFontFamily, fontSize = 12.sp, color = Color.LightGray) } } } } } @Composable fun TabSwitcher() { var selectedTabIndex by remember { mutableIntStateOf(0) } val tabs = listOf("Transactions","Upcoming Bills") Column { Card( onClick = { /*TODO*/ }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp, vertical = 16.dp), shape = RoundedCornerShape(16.dp), colors = CardColors(containerColor = colorResource(id = R.color.mojito_breeze), contentColor = Color.White, disabledContentColor = Color.Black, disabledContainerColor = Color.Gray) ) { TabRow( selectedTabIndex = selectedTabIndex, modifier = Modifier // .background(color = colorResource(id = R.color.lord_icon_green)) .padding(vertical = 8.dp) , contentColor = Color.Black, containerColor = Color.White, indicator = { tabPositions -> // Box( modifier = Modifier .tabIndicatorOffset(tabPositions[selectedTabIndex]) .fillMaxWidth() .height(0.dp) ) } ) { tabs.forEachIndexed { index: Int, title: String -> val isSelected = selectedTabIndex == index val backgroundColor = if (isSelected) colorResource(id = R.color.lord_icon_green) else Color.White val contentColor = if (isSelected) Color.Black else Color.Gray Tab( selected = isSelected, onClick = { selectedTabIndex = index }, modifier = Modifier .padding(horizontal = 4.dp, vertical = 4.dp) .background( color = backgroundColor, shape = RoundedCornerShape(50) ) ) { Text(text = title, color = contentColor) } } } } when(selectedTabIndex){ 0 -> TransactionList() 1 -> UpcomingBillsList() } } } @Composable fun TransactionList() { Text( text = "Here's a list of Transactions", fontFamily = poppinsFontFamily, style = MaterialTheme.typography.bodyMedium ) } @Composable fun UpcomingBillsList() { Text( text = "Here's a list of Upcoming Bills", fontFamily = poppinsFontFamily, style = MaterialTheme.typography.bodyMedium ) } @Preview(showBackground = true, apiLevel = 34) @Composable fun CardCompPreview() { ExpenseTrackerAppTheme { CardComp() } }
0
Kotlin
0
0
926e103392b327088eca6d29fa4ad33aef4ae042
12,035
expense-tracker
Apache License 2.0
app/src/main/java/com/recordapp/record/MainActivity.kt
shengxinsoft
477,224,964
true
{"Kotlin": 34732, "Java": 21962}
package com.recordapp.record import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import kotlinx.android.synthetic.main.activity_main.* import java.io.File import java.util.ArrayList class MainActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener { var permissionList: ArrayList<String> = ArrayList() /**存放音频文件列表 */ private var recordFiles: ArrayList<String>? = null /**文件存在 */ private var sdcardExit: Boolean = false var myRecAudioDir: String? = Environment.getExternalStorageDirectory().path + "/super_start" var myRecyclerAdapter: MyRecyclerAdapter? = null var isMp3: Boolean = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sfl_main_root.setOnRefreshListener(this) // 判断sd Card是否插入 sdcardExit = Environment.getExternalStorageState() == android.os.Environment.MEDIA_MOUNTED btn_merge.setOnClickListener(View.OnClickListener { if (isMp3) { startActivityForResult(Intent(this, RecordAudioRecordViewActivity::class.java), 1001) } else { startActivityForResult(Intent(this, RecordViewActivity::class.java), 1001) } }) getPermission( this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.RECORD_AUDIO ) recordFiles = ArrayList<String>() getRecordFiles() if (recordFiles!!.size == 0) { rlv_main.visibility = View.GONE tv_not_data.visibility=View.VISIBLE } else { rlv_main.visibility = View.VISIBLE tv_not_data.visibility=View.GONE } myRecyclerAdapter = MyRecyclerAdapter(this, recordFiles) myRecyclerAdapter!!.setListener { path -> openFile(File(path)) } rlv_main.layoutManager = LinearLayoutManager(this) rlv_main.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL)) rlv_main.adapter = myRecyclerAdapter } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK) { if (requestCode == 1001) { var myRecAudioDir = data!!.getStringExtra("record_url") recordFiles!!.add(File(myRecAudioDir).name) myRecyclerAdapter!!.notifyDataSetChanged() } } } override fun onRefresh() { getRecordFiles() if (recordFiles!!.size == 0) { rlv_main.visibility = View.GONE tv_not_data.visibility=View.VISIBLE } else { rlv_main.visibility = View.VISIBLE tv_not_data.visibility=View.GONE } myRecyclerAdapter!!.notifyDataSetChanged() } private fun getRecordFiles() { recordFiles!!.clear() if (sdcardExit) { val files = File(myRecAudioDir).listFiles() if (files != null) { for (i in files!!.indices) { if (files!![i].getName().indexOf(".") >= 0) { // 只取.amr 文件 val fileS = files!![i].getName().substring( files!![i].getName().indexOf(".") ) if (fileS.toLowerCase() == ".mp3" || fileS.toLowerCase() == ".amr" || fileS.toLowerCase() == ".mp4" ) recordFiles!!.add(files!![i].getName()) } } sfl_main_root.isRefreshing = false } } } private fun getPermission(context: Activity, vararg permission: String) { for (i in permission.indices) { if (ContextCompat.checkSelfPermission(context, permission[i]) !== PackageManager.PERMISSION_GRANTED) { permissionList.add(permission[i]) } } if (permissionList.size > 0) { val permissions = arrayOfNulls<String>(permissionList.size) for (i in permissionList.indices) { permissions[i] = permissionList.get(i) } ActivityCompat.requestPermissions(context, permissions, 1) } } private fun getTime(): String { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss"); // Date curDate = new Date(System.currentTimeMillis());//获取当前时间 // String time = formatter.format(curDate); return "start_" + System.currentTimeMillis() } private fun openFile(f: File) { var intent = Intent(Intent.ACTION_VIEW) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) var uriForFile = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", f) intent.setDataAndType(uriForFile, getMIMEType(f)) } else { intent.setDataAndType(Uri.fromFile(f), getMIMEType(f)) } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) // intent = Intent() // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // intent.action = Intent.ACTION_VIEW // val type = getMIMEType(f) // intent.setDataAndType(Uri.fromFile(f), type) // startActivity(intent) // Uri uri=Uri.fromFile(f) // MediaPlayer mediaPlayer = MediaPlayer.create (this, uri); // try { // mediaPlayer.prepare(); // } catch (IllegalStateException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // mediaPlayer.start(); } private fun getMIMEType(f: File): String { val end = f.name.substring( f.name.lastIndexOf(".") + 1, f.name.length ).toLowerCase() var type = "" if (end == "mp3" || end == "aac" || end == "amr" || end == "mpeg" || end == "mp4" ) { type = "audio" } else if (end == "jpg" || end == "gif" || end == "png" || end == "jpeg" ) { type = "image" } else { type = "*" } type += "/" return type } }
0
null
0
0
72704389c50f4670615079d1b03cecc2bea79471
7,108
AndroidRecordApp
Apache License 2.0
app/src/main/java/com/matiasmandelbaum/alejandriaapp/domain/usecase/ChangeUserProfileUseCase.kt
ManuelCastanon
765,470,240
false
{"Kotlin": 218948}
package com.matiasmandelbaum.alejandriaapp.domain.usecase import com.matiasmandelbaum.alejandriaapp.domain.model.userinput.UserDataInput import com.matiasmandelbaum.alejandriaapp.domain.repository.UsersRepository import javax.inject.Inject class ChangeUserProfileUseCase @Inject constructor(private val usersRepository: UsersRepository) { suspend operator fun invoke( userDataInput: UserDataInput ) = usersRepository.updateUserProfile(userDataInput.name, userDataInput.lastName, userDataInput.email!!, userDataInput.birthDate) }
0
Kotlin
0
0
f1f1e808cb42b2ceac6206aad89906fe618b1f45
546
ORT-TP3_AlejandriaApp
Apache License 2.0
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/object3.kt
ingokegel
72,937,917
true
null
// IS_APPLICABLE: false class Foo { companion object { fun bar() {} } } val ref: (Foo.Companion) -> Unit = {<caret> it.bar() }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
144
intellij-community
Apache License 2.0
feature/about/src/main/java/se/gustavkarlsson/skylight/android/feature/about/AboutScreen.kt
gustavkarlsson
128,669,768
false
null
package se.gustavkarlsson.skylight.android.feature.about import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.Image 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.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.accompanist.insets.LocalWindowInsets import com.google.accompanist.insets.rememberInsetsPaddingValues import com.google.accompanist.insets.ui.Scaffold import com.google.accompanist.insets.ui.TopAppBar import kotlinx.parcelize.Parcelize import se.gustavkarlsson.skylight.android.lib.navigation.Screen import se.gustavkarlsson.skylight.android.lib.navigation.navigator import se.gustavkarlsson.skylight.android.lib.scopedservice.ServiceId import se.gustavkarlsson.skylight.android.lib.scopedservice.ServiceTag import se.gustavkarlsson.skylight.android.lib.ui.compose.Icons import se.gustavkarlsson.skylight.android.lib.ui.compose.ScreenBackground import se.gustavkarlsson.skylight.android.lib.ui.compose.Typography import se.gustavkarlsson.skylight.android.lib.ui.compose.textRef import se.gustavkarlsson.skylight.android.lib.ui.getOrRegisterService private val VIEW_MODE_ID = ServiceId("aboutViewModel") @Parcelize object AboutScreen : Screen { override val type: Screen.Type get() = Screen.Type.About @Composable override fun Content(activity: AppCompatActivity, tag: ServiceTag) { val viewModel = getOrRegisterService(VIEW_MODE_ID, tag) { AboutComponent.build().viewModel() } val text = textRef(viewModel.detailsText) Content( text = text, onBackClicked = { navigator.closeScreen() }, ) } } @Composable @Preview private fun PreviewContent() { Content( text = "Line1\nLine2", onBackClicked = {}, ) } @Composable private fun Content( text: String, onBackClicked: () -> Unit, ) { ScreenBackground { Scaffold( topBar = { TopAppBar( contentPadding = rememberInsetsPaddingValues(LocalWindowInsets.current.statusBars), navigationIcon = { IconButton(onClick = onBackClicked) { Icon(Icons.ArrowBack, contentDescription = null) } }, title = { Text(stringResource(R.string.about)) }, ) }, ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Spacer(modifier = Modifier.height(64.dp)) Image( modifier = Modifier.fillMaxWidth(0.6f), painter = painterResource(R.drawable.app_logo), contentScale = ContentScale.FillWidth, contentDescription = null, ) Spacer(modifier = Modifier.height(32.dp)) Text( text = stringResource(R.string.app_name), style = Typography.h4, ) Spacer(modifier = Modifier.height(32.dp)) Text(text = text, textAlign = TextAlign.Center) } } } }
0
Kotlin
3
6
c3b1b53a73a1de97ad0e6e9645ddae1df5815800
4,188
skylight-android
MIT License
src/main/kotlin/org/batteryparkdev/cosmicgraphdb/neo4j/Neo4jUtils.kt
fcriscuo
407,274,893
false
null
package org.batteryparkdev.cosmicgraphdb.neo4j import com.google.common.flogger.FluentLogger import java.util.* object Neo4jUtils { private val logger: FluentLogger = FluentLogger.forEnclosingClass() /* Function to determine if a node has already been loaded into Neo4j */ fun nodeLoadedPredicate(cypherCommand: String): Boolean { if (cypherCommand.contains("PREDICATE", ignoreCase = true)) { try { val predicate = Neo4jConnectionService.executeCypherCommand(cypherCommand) when (predicate.lowercase(Locale.getDefault())) { "true" -> return true "false" -> return false } } catch (e: Exception) { logger.atSevere().log(e.message.toString()) return false } } return false } /* Function to delete a Neo4j relationship */ fun deleteNodeRelationshipByName(parentNode: String, childNode: String, relName: String) { val deleteTemplate = "MATCH (:PARENT) -[r:RELATIONSHIP_NAME] ->(:CHILD) DELETE r;" val countTemplate = "MATCH (:PubMedArticle) -[:RELATIONSHIP_NAME] -> (:PubMedArticle) RETURN COUNT(*)" val delCommand = deleteTemplate .replace("PARENT", parentNode) .replace("CHILD", childNode) .replace("RELATIONSHIP_NAME", relName) val countCommand = countTemplate .replace("PARENT", parentNode) .replace("CHILD", childNode) .replace("RELATIONSHIP_NAME", relName) val beforeCount = Neo4jConnectionService.executeCypherCommand(countCommand) logger.atInfo().log("Deleting $parentNode $relName $childNode relationships, before count = $beforeCount") Neo4jConnectionService.executeCypherCommand(delCommand) val afterCount = Neo4jConnectionService.executeCypherCommand(countCommand) logger.atInfo().log("After deletion command count = $afterCount") } /* Function to delete a specified label from a specified node type */ fun removeNodeLabel(nodeName: String, label: String) { val removeLabelTemplate = "MATCH (n:NODENAME) REMOVE n:LABEL RETURN COUNT(n)" val countLabelTemplate = "MATCH(l:LABEL) RETURN COUNT(l)" val removeLabelCommand = removeLabelTemplate .replace("NODENAME", nodeName) .replace("LABEL", label) val countLabelCommand = countLabelTemplate.replace("LABEL", label) val beforeCount = Neo4jConnectionService.executeCypherCommand(countLabelCommand) logger.atInfo().log("Node type: $nodeName, removing label: $label before count = $beforeCount") Neo4jConnectionService.executeCypherCommand(removeLabelCommand) val afterCount = Neo4jConnectionService.executeCypherCommand(countLabelCommand) logger.atInfo().log("Node type: $nodeName, after label removal command count = $afterCount") } // detach and delete specified nodes in database fun detachAndDeleteNodesByName(nodeName: String) { val beforeCount = Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) RETURN COUNT (n)" ) Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) DETACH DELETE (n);") val afterCount = Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) RETURN COUNT (n)" ) logger.atInfo().log("Deleted $nodeName nodes, before count=${beforeCount.toString()}" + " after count=$afterCount") } }
1
null
1
1
c55422a21c5250e61a8437fba533caff0c1c3b83
3,613
CosmicGraphDb
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/batteryparkdev/cosmicgraphdb/neo4j/Neo4jUtils.kt
fcriscuo
407,274,893
false
null
package org.batteryparkdev.cosmicgraphdb.neo4j import com.google.common.flogger.FluentLogger import java.util.* object Neo4jUtils { private val logger: FluentLogger = FluentLogger.forEnclosingClass() /* Function to determine if a node has already been loaded into Neo4j */ fun nodeLoadedPredicate(cypherCommand: String): Boolean { if (cypherCommand.contains("PREDICATE", ignoreCase = true)) { try { val predicate = Neo4jConnectionService.executeCypherCommand(cypherCommand) when (predicate.lowercase(Locale.getDefault())) { "true" -> return true "false" -> return false } } catch (e: Exception) { logger.atSevere().log(e.message.toString()) return false } } return false } /* Function to delete a Neo4j relationship */ fun deleteNodeRelationshipByName(parentNode: String, childNode: String, relName: String) { val deleteTemplate = "MATCH (:PARENT) -[r:RELATIONSHIP_NAME] ->(:CHILD) DELETE r;" val countTemplate = "MATCH (:PubMedArticle) -[:RELATIONSHIP_NAME] -> (:PubMedArticle) RETURN COUNT(*)" val delCommand = deleteTemplate .replace("PARENT", parentNode) .replace("CHILD", childNode) .replace("RELATIONSHIP_NAME", relName) val countCommand = countTemplate .replace("PARENT", parentNode) .replace("CHILD", childNode) .replace("RELATIONSHIP_NAME", relName) val beforeCount = Neo4jConnectionService.executeCypherCommand(countCommand) logger.atInfo().log("Deleting $parentNode $relName $childNode relationships, before count = $beforeCount") Neo4jConnectionService.executeCypherCommand(delCommand) val afterCount = Neo4jConnectionService.executeCypherCommand(countCommand) logger.atInfo().log("After deletion command count = $afterCount") } /* Function to delete a specified label from a specified node type */ fun removeNodeLabel(nodeName: String, label: String) { val removeLabelTemplate = "MATCH (n:NODENAME) REMOVE n:LABEL RETURN COUNT(n)" val countLabelTemplate = "MATCH(l:LABEL) RETURN COUNT(l)" val removeLabelCommand = removeLabelTemplate .replace("NODENAME", nodeName) .replace("LABEL", label) val countLabelCommand = countLabelTemplate.replace("LABEL", label) val beforeCount = Neo4jConnectionService.executeCypherCommand(countLabelCommand) logger.atInfo().log("Node type: $nodeName, removing label: $label before count = $beforeCount") Neo4jConnectionService.executeCypherCommand(removeLabelCommand) val afterCount = Neo4jConnectionService.executeCypherCommand(countLabelCommand) logger.atInfo().log("Node type: $nodeName, after label removal command count = $afterCount") } // detach and delete specified nodes in database fun detachAndDeleteNodesByName(nodeName: String) { val beforeCount = Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) RETURN COUNT (n)" ) Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) DETACH DELETE (n);") val afterCount = Neo4jConnectionService.executeCypherCommand( "MATCH (n: $nodeName) RETURN COUNT (n)" ) logger.atInfo().log("Deleted $nodeName nodes, before count=${beforeCount.toString()}" + " after count=$afterCount") } }
1
null
1
1
c55422a21c5250e61a8437fba533caff0c1c3b83
3,613
CosmicGraphDb
Creative Commons Zero v1.0 Universal
src/rest/repository/GoogleMaps.kt
NaikSoftware
51,260,826
false
null
package rest.repository import model.GoogleResponse import model.GoogleResponseList import model.Location import model.LocationDetails import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Created by naik on 20.02.16. */ interface GoogleMaps { @GET("maps/api/place/nearbysearch/json") fun getPlaceNear(@Query("location") lonLat: String, @Query("radius") radius: Int, @Query("types") types: String, @Query("name") name: String, @Query("key") apiKey: String) : Call<GoogleResponseList<List<Location>>> @GET("maps/api/place/details/json") fun getPlaceDetails(@Query("placeid") placeId: String, @Query("key") apiKey: String) : Call<GoogleResponse<LocationDetails>> }
0
Kotlin
0
1
1cf5e9fdee66e7f01d94bf6d2dd4659d00c39995
820
EVGen
Apache License 2.0
assertk-common/src/test/kotlin/test/assertk/AssertMultipleSpec.kt
palbecki
132,195,550
true
{"Kotlin": 169817, "Java": 134}
package test.assertk import assertk.all import assertk.assert import assertk.assertAll import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import assertk.assertions.toStringFun import test.assertk.AssertMultipleSpec.BasicObject import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails class AssertMultipleSpec_On_an_assert_block_with_a_value { private val subject = BasicObject("test", 1) @Test fun it_should_pass_multiple_successful_assertions() { assert(subject).all { isInstanceOf(BasicObject::class) toStringFun().isEqualTo("BasicObject(arg1=test, arg2=1)") } } @Test fun it_should_fail_the_first_assertion() { val error = assertFails { assert(subject).all { isInstanceOf(String::class) toStringFun().isEqualTo("BasicObject(arg1=test, arg2=1)") } } assertEquals( "expected to be instance of:<${String::class}> but had class:<${BasicObject::class}>", error.message ) } @Test fun it_should_fail_the_second_assertion() { val error = assertFails { assert(subject).all { isInstanceOf(BasicObject::class) toStringFun().isEqualTo("wrong") } } assertEquals( "expected [toString]:<\"[wrong]\"> but was:<\"[BasicObject(arg1=test, arg2=1)]\"> (BasicObject(arg1=test, arg2=1))", error.message ) } @Test fun it_should_fail_both_assertions() { val error = assertFails { assert<Any>(subject).all { isInstanceOf(String::class) toStringFun().isEqualTo("wrong") } } assertEquals( """The following 2 assertions failed: - expected to be instance of:<${String::class}> but had class:<${BasicObject::class}> - expected [toString]:<"[wrong]"> but was:<"[BasicObject(arg1=test, arg2=1)]"> (BasicObject(arg1=test, arg2=1))""", error.message ) } } class AssertMultipleSpec_On_an_assert_all_block { val subject1 = BasicObject("test1", 1) val subject2 = BasicObject("test2", 2) @Test fun it_should_pass_multiple_successful_assertions() { assertAll { assert(subject1).toStringFun().isEqualTo("BasicObject(arg1=test1, arg2=1)") assert(subject2).toStringFun().isEqualTo("BasicObject(arg1=test2, arg2=2)") } } @Test fun it_should_fail_the_first_assertion() { val error = assertFails { assertAll { assert(subject1).toStringFun().isEqualTo("wrong1") assert(subject2).toStringFun().isEqualTo("BasicObject(arg1=test2, arg2=2)") } } assertEquals( "expected [toString]:<\"[wrong1]\"> but was:<\"[BasicObject(arg1=test1, arg2=1)]\"> (BasicObject(arg1=test1, arg2=1))", error.message ) } @Test fun it_should_fail_the_second_assertion() { val error = assertFails { assertAll { assert(subject1).toStringFun().isEqualTo("BasicObject(arg1=test1, arg2=1)") assert(subject2).toStringFun().isEqualTo("wrong2") } } assertEquals( "expected [toString]:<\"[wrong2]\"> but was:<\"[BasicObject(arg1=test2, arg2=2)]\"> (BasicObject(arg1=test2, arg2=2))", error.message ) } @Test fun it_should_fail_both_assertions() { val error = assertFails { assertAll { assert(subject1).toStringFun().isEqualTo("wrong1") assert(subject2).toStringFun().isEqualTo("wrong2") } } assertEquals( """The following 2 assertions failed: - expected [toString]:<"[wrong1]"> but was:<"[BasicObject(arg1=test1, arg2=1)]"> (BasicObject(arg1=test1, arg2=1)) - expected [toString]:<"[wrong2]"> but was:<"[BasicObject(arg1=test2, arg2=2)]"> (BasicObject(arg1=test2, arg2=2))""", error.message ) } } class AssertMultipleSpec { data class BasicObject(val arg1: String, val arg2: Int) }
0
Kotlin
0
0
3b362c222a1987cd763d9ffde52e5dca5bf99ee1
4,236
assertk
MIT License
app/src/main/java/ramzi/eljabali/justjog/ui/util/BottomNavigationItems.kt
RamziJabali
406,133,718
false
{"Kotlin": 76393}
package ramzi.eljabali.justjog.ui.util import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AreaChart import androidx.compose.material.icons.filled.CalendarToday import androidx.compose.material.icons.outlined.AreaChart import androidx.compose.material.icons.outlined.CalendarToday import androidx.compose.ui.graphics.vector.ImageVector enum class BottomNavigationItems( val title: String, val selectedIcon: ImageVector, val unSelectedIcon: ImageVector, ) { STATISTICS("Statistics", Icons.Filled.AreaChart, Icons.Outlined.AreaChart), CALENDAR("Calendar", Icons.Filled.CalendarToday, Icons.Outlined.CalendarToday) }
4
Kotlin
1
12
9fb53f663562b83677e3386201575ada0e352913
674
just-jog-android
MIT License
src/main/kotlin/tomasvolker/komputo/dataset/LabeledData.kt
TomasVolker
169,266,002
false
null
package tomasvolker.komputo.dataset data class LabeledData<out D, out L>( val data: D, val label: L ) inline fun <D, D2, L> LabeledData<D, L>.mapData(transform: (D)->D2) = LabeledData(transform(data), label) inline fun <D, L, L2> LabeledData<D, L>.mapLabel(transform: (L)->L2) = LabeledData(data, transform(label)) infix fun <D, L> D.labelTo(label: L) = LabeledData(this, label) typealias LabeledDataset<D, L> = List<LabeledData<D, L>> inline fun <D, D2, L> LabeledDataset<D, L>.mapData(transform: (D)->D2) = map { it.mapData(transform) } inline fun <D, L, L2> LabeledDataset<D, L>.mapLabels(transform: (L)->L2) = map { it.mapLabel(transform) }
0
Kotlin
0
3
876dc1a00caeec2b5eeea5dd5b77ff5fa2e83e6a
679
komputo
Apache License 2.0
buffer/src/main/kotlin/rpmoore/ktasync/buffer/Sink.kt
rpmoore
159,011,393
false
null
/* * * * * Copyright of Ryan Moore (c) 2019. * / * */ package rpmoore.ktasync.buffer interface Sink { suspend fun write(byteArray: ByteArray): Int }
0
Kotlin
0
0
2e10c0b949994a669e67bf9a2fa2caa26d817674
160
kt-async
Apache License 2.0
app/src/main/java/com/jppedrosa/vexillology/di/modules/AppModule.kt
joaoppedrosa
536,594,585
false
null
package com.jppedrosa.vexillology.di.modules import com.jppedrosa.vexillology.BuildConfig import com.jppedrosa.vexillology.data.remote.VexillologyApi import com.jppedrosa.vexillology.data.repository.VexillologyRepositoryImpl import com.jppedrosa.vexillology.domain.VexillologyRepository import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * @author <NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>) on 15/09/2022. */ @Module class AppModule { private val BASE_URL = "https://restcountries.com" @Provides @Singleton fun provideOkHttp(): OkHttpClient { val httpClient = OkHttpClient.Builder() val interceptor = HttpLoggingInterceptor() interceptor.setLevel(if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE) httpClient.addInterceptor(interceptor) httpClient.addInterceptor(Interceptor { chain: Interceptor.Chain -> val original: Request = chain.request() val request: Request = original.newBuilder() .header("Content-Type", "application/json") .method(original.method, original.body) .build() chain.proceed(request) }) return httpClient.build() } @Provides @Singleton fun provideVexillologyApi(okHttpClient: OkHttpClient): VexillologyApi { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(VexillologyApi::class.java) } @Provides @Singleton fun provideVexillologyRepository(api: VexillologyApi): VexillologyRepository { return VexillologyRepositoryImpl(api); } }
0
Kotlin
0
0
875e4d3324536168e5ac1eb50497a856b2e5a0ba
2,123
Vexillology
MIT License
app/src/main/java/com/jintin/quickroute/action/ActionListViewModel.kt
Jintin
375,362,756
false
null
package com.jintin.quickroute.action import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jintin.quickroute.data.Action import com.jintin.quickroute.db.ActionDao import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ActionListViewModel @Inject constructor( private val actionDao: ActionDao ) : ViewModel() { val liveData = actionDao.list() fun delete(data: Action) { viewModelScope.launch { actionDao.delete(data) } } }
0
Kotlin
2
18
d2535abb1ad9de2c9e086e094b5eccb59e977cbb
579
QuickRoute
Apache License 2.0
net/craftventure/core/feature/kart/actions/StartNbsSongAction.kt
Craftventure
770,049,457
false
{"Kotlin": 3656616, "Java": 684034}
package net.craftventure.core.feature.kart.actions import net.craftventure.bukkit.ktx.nbs.NbsPlayer import net.craftventure.core.extension.openMenu import net.craftventure.core.feature.instrument.InstrumentType import net.craftventure.core.feature.kart.Kart import net.craftventure.core.feature.kart.KartAction import net.craftventure.core.feature.nbsplayback.NbsFileManager import net.craftventure.core.inventory.impl.OwnedItemsMenu import net.craftventure.core.inventory.impl.OwnedItemsPickerMenu import net.craftventure.database.generated.cvdata.tables.pojos.OwnableItem import net.craftventure.database.type.ItemType import net.craftventure.temporary.getOwnableItemMetadata import org.bukkit.SoundCategory import org.bukkit.entity.Player class StartNbsSongAction( val instrument: InstrumentType, ) : KartAction { override fun execute(kart: Kart, type: KartAction.Type, target: Player?) { kart.metadata["nbssong"]?.onDestroy() val pickerMenu = OwnedItemsPickerMenu( kart.player, object : OwnedItemsMenu.ItemFilter { override val displayName: String = ItemType.MUSIC_SHEET.displayNamePlural override fun matches(itemType: ItemType): Boolean = itemType == ItemType.MUSIC_SHEET override fun matches(ownableItem: OwnableItem): Boolean { val supported = ownableItem.getOwnableItemMetadata()?.musicSheet?.instruments ?: return false return instrument in supported } } ) { pickedItem -> if (!kart.isValid()) return@OwnedItemsPickerMenu val songName = pickedItem.getOwnableItemMetadata()?.musicSheet?.song ?: return@OwnedItemsPickerMenu val song = NbsFileManager.getSong(songName) ?: return@OwnedItemsPickerMenu val player = NbsPlayer(song) { block, sound, volume, pitch -> kart.world.playSound( kart.location.toLocation(kart.world), sound, SoundCategory.BLOCKS, volume, pitch ) } player.start() kart.metadata["nbssong"] = object : Kart.Attachment { override fun onDestroy() { player.stop() } } } kart.player.openMenu(pickerMenu) } }
0
Kotlin
1
21
015687ff6687160835deacda57121480f542531b
2,407
open-plugin-parts
MIT License
domains/android/viewmodel/src/testFixtures/kotlin/ViewModelTest.kt
ouchadam
434,718,760
false
null
import app.dapk.st.viewmodel.MutableStateFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import test.ExpectTest @Suppress("UNCHECKED_CAST") class ViewModelTest { var instance: TestMutableState<Any>? = null fun <S> testMutableStateFactory(): MutableStateFactory<S> { return { TestMutableState(it).also { instance = it as TestMutableState<Any> } } } operator fun invoke(block: suspend ViewModelTestScope.() -> Unit) { runTest { val expectTest = ExpectTest(coroutineContext) val viewModelTest = ViewModelTestScopeImpl(expectTest, this@ViewModelTest) Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) block(viewModelTest) viewModelTest.finish() Dispatchers.resetMain() } } }
36
null
4
139
5a391676d0d482596fe5d270798c2b361dba67e7
975
small-talk
Apache License 2.0
example/src/main/java/de/charlex/compose/settings/datastore/example/MainActivity.kt
capjan
464,420,560
true
{"Kotlin": 8162}
package de.charlex.compose.settings.datastore.example import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Checkbox import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Switch import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import de.charlex.compose.settings.datastore.LocalSettingsDataStore import de.charlex.compose.settings.datastore.Setting import de.charlex.compose.settings.datastore.example.theme.SettingsTheme import de.charlex.settings.datastore.SettingsDataStore import de.charlex.settings.datastore.booleanPreference import de.charlex.settings.datastore.stringPreference class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val settingsDataStore = SettingsDataStore.create(this) setContent { Body(settingsDataStore = settingsDataStore) } } } @Composable fun Body(settingsDataStore: SettingsDataStore) { SettingsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { CompositionLocalProvider(LocalSettingsDataStore provides settingsDataStore) { Column { Setting(key = stringPreference("email", "<EMAIL>")) { value, onValueChanged -> TextField(value = value, onValueChange = onValueChanged) } Setting(key = booleanPreference("key1", false)) { value, onValueChanged -> Switch(checked = value, onCheckedChange = onValueChanged) } Setting(key = booleanPreference("key2", false)) { value, onValueChanged -> Checkbox(checked = value, onCheckedChange = onValueChanged) } Setting(key = stringPreference("email_two", "<EMAIL>"), saveDebounceMillis = 5000) { value, onValueChanged -> TextField(value = value, onValueChange = onValueChanged) } } } } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { SettingsTheme { Body(settingsDataStore = SettingsDataStore.createInMemory()) } }
0
Kotlin
0
0
54548ac856709de14b5522042ac95c6ae313c781
2,783
settings-compose
Apache License 2.0
valentine-starter/src/main/kotlin/com/unicorn/strategy/TKMUserTypeStrategy.kt
lWoHvYe
350,562,833
false
null
/* * Copyright (c) 2022-2023. lWoHvYe(<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.unicorn.strategy import com.lwohvye.sys.modules.system.annotation.UserTypeHandlerAnno import com.lwohvye.sys.modules.system.strategy.ExtraUserTypeStrategy import kotlinx.coroutines.* import org.apache.logging.log4j.LogManager.getLogger import org.jetbrains.annotations.BlockingExecutor import org.springframework.security.core.GrantedAuthority import org.springframework.stereotype.Component import java.util.concurrent.Executors import kotlin.time.ExperimentalTime import kotlin.time.measureTime @Component @UserTypeHandlerAnno(typeName = "FOUR") sealed class TKMUserTypeStrategy : ExtraUserTypeStrategy { @OptIn(DelicateCoroutinesApi::class) override fun grantedAuth(userId: Long): List<GrantedAuthority> { println("Start") // kotlinx.coroutines将在1.7版本支持JPMS,但在1.7.0-Beta。若以DeBug模式启动,依旧报错 `module kotlin.stdlib does not read module kotlinx.coroutines.core`,Normal run正常 // https://github.com/Kotlin/kotlinx.coroutines/issues/2237 // https://github.com/Kotlin/kotlinx.coroutines/pull/3297 // Coroutines can perfectly benefit from Loom: A Coroutine always relies on a thread for its execution. // This Thread can also be a VirtualThread. The advantage of having a VirtualThread executing a Coroutine is that all IO operations, // concurrency locks etc. will behave in a non-blocking fashion, wasting no resources. // { 参数列表 -> 函数体 } 是 lambda 表达式语法。它用于定义匿名函数,可以作为参数传递给其他函数或方法。 // 在这个例子中,使用了无参数的 lambda 表达式来定义一个协程,通过 GlobalScope.launch 启动了这个协程。 // lambda 表达式的主体中包含了一个使用 runBlocking 函数定义的协程,它会暂停当前协程的执行 // 具体而言就是: // 1.GlobalScope.launch { ... }: 创建了一个协程并启动,GlobalScope 是一个全局范围,表示该协程的生命周期与整个应用程序的生命周期相同。 // { .. } 中定义的是launch函数的block参数,更确叫 launch函数的调用体。 实际上也就是 `suspend CoroutineScope.() -> Unit` 中的 CoroutinesScope.() -> Unit 这个lambda表达式 // 参数拥有默认值后,变为可选参数 GlobalScope.launch { // 2.runBlocking { ... }: 用于等待协程内部的代码执行完毕后再执行后面的代码。在这个例子中,使用了 delay 函数模拟一个耗时操作,它会暂停协程的执行一段时间,这里是 1000 毫秒(1 秒)。 runBlocking { delay(1000) } // 3.println("Hello"): 该代码会在 delay 函数执行完毕后被执行,打印 "Hello" 到控制台。 println("Hello") } Thread.sleep(2000) // 等待 2 秒钟 println("Stop") //_____________ val result = GlobalScope.async { workload(16) // 调用函数 } runBlocking { println("async result is ${result.await()}") } // 抛去第一个参数的定义,下面这个与上面这个是等同的,只是因为 `Lambda argument should be moved out of parentheses` 所以把lambda移到了后面 /*runBlocking(EmptyCoroutineContext, { println("async result is ${result.await()}") })*/ // 对于存在可变参数的,可通过 参数名 = xxx 对特定参数赋值 /*runBlocking(block = { println("async result is ${result.await()}") })*/ loomCarrier() coroutinesDirect() //_____________ return emptyList() } // 这段代码是一个Kotlin协程中的挂起函数(Suspending Function),使用了suspend关键字修饰。 // 协程中的挂起函数使用suspend关键字修饰,这意味着当调用该函数时,它会暂停当前协程(所以调用代码后的部分不会执行)而不会阻塞当前线程,从而实现异步执行。 // 方法只有一行时,可以用 = 代替 { ... } suspend fun workload(n: Int): Int { // 使用suspend修饰 delay(1000) return n + 2 } // Define a Custom Dispatcher // What if instead of blocking a regular thread, we run it on one of Project Loom’s virtual threads, // effectively turning the blocking code into something non-blocking while still being Coroutine compatible? val Dispatchers.LOOM: @BlockingExecutor CoroutineDispatcher // 这里的Dispatchers.LOOM 是一个field,field可以有get/set方法 get() = Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher() // use Loom. This will need some time to warm up, overhead. 7s for 1_000_000, Debug Mode 17s for 100_000,比coroutines慢了太多了 @OptIn(ExperimentalTime::class) fun loomCarrier() = runBlocking { val log = getLogger() measureTime { supervisorScope { repeat(100_000) { launch(Dispatchers.LOOM) { Thread.sleep(1000) } } } }.also(log::info) Unit } // use Kotlinx Coroutines. While this is ballpark. 4.5s for 1_000_000, Debug Mode 5.2s for 100_000 // 这段代码的作用是使用 Kotlin 协程实现了 100,000 个并发任务,并度量了执行时间,最后将执行时间输出到日志中。其中 supervisorScope 监控了所有协程的执行情况,避免了某个协程出错后导致整个任务失败的情况。 // @OptIn(ExperimentalTime::class):这是一个注解,表示使用了实验性质的时间库。实验性质的库需要在代码中明确声明才能使用。 @OptIn(ExperimentalTime::class) // fun coroutinesDirect() = runBlocking { ... }:这是一个 Kotlin 函数,名为 coroutinesDirect。它使用了协程框架,并在 runBlocking 块中执行了一些并发任务。 fun coroutinesDirect() = runBlocking { // val log = getLogger():这行代码声明了一个变量 log,它是一个日志记录器。这里使用了某个日志库的函数 getLogger(),获取一个日志记录器实例。 val log = getLogger() // measureTime { ... }.also(log::info):这是一个计时操作,用来度量代码块的执行时间。它的返回值是执行时间,类型为 kotlin.time.Duration。.also(log::info) 表示执行计时操作的同时,将计时结果输出到日志中。 measureTime { // supervisorScope { ... }:这是一个协程作用域,用于启动一组并发任务,并监控这些任务的执行情况。其中 repeat(100_000) 表示要执行 100,000 次下面的代码块。 supervisorScope { repeat(100_000) { // launch { delay(1000) }:这是一个协程启动函数,用于启动一个新的协程,并在其中执行代码块。这里的代码块是 delay(1000),表示在协程中延迟 1 秒。 launch { delay(1000) } } } }.also(log::info) // Unit:这是一个 Kotlin 中的单例对象,表示空值。在这里,它作为 runBlocking 块的返回值,因为 runBlocking 块需要一个返回值。 Unit } }
4
Java
14
22
3e8750991f7ac4891cc8e01f13139ceb14f36af9
6,216
eladmin
Apache License 2.0
app/src/main/java/dk/itu/moapd/copenhagenbuzz/skjo/view/MainActivity.kt
JonasSkjodt
750,503,018
false
{"Kotlin": 8465}
package dk.itu.moapd.copenhagenbuzz.skjo.view import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import dk.itu.moapd.copenhagenbuzz.skjo.databinding.ActivityMainBinding import com.google.android.material.datepicker.MaterialDatePicker import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import androidx.core.util.Pair import com.google.android.material.snackbar.Snackbar import dk.itu.moapd.copenhagenbuzz.skjo.model.Event /** * The MainActivity class handles user interactions (like events) and initializes the UI in the app * * KDoc the code * @see https://kotlinlang.org/docs/kotlin-doc.html#sample-identifier * @see https://source.android.com/docs/core/architecture/hidl/code-style */ class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding // A set of private constants used in this class. companion object { private val TAG = MainActivity::class.qualifiedName } //An instance of the 'Event' class private val event: Event = Event("","","","","") /** * Sets up the current layout, the view bindings, and listeners. * When the add event button is clicked, it validates the input fields and then creates this new event (if all fields are non-empty). */ override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //the viewBindings references our UI components //kotlin changes the id from, for instance, edit_text_event_name to editTextEventName. //https://developer.android.com/topic/libraries/view-binding val eventName = binding.contentMain.editTextEventName val eventLocation = binding.contentMain.editTextEventLocation val eventType = binding.contentMain.editEventType val eventDescription = binding.contentMain.editEventDescription val addEventButton = binding.contentMain.fabAddEvent val eventDate = binding.contentMain.fieldEventDate //event listeners for the eventDate calendar with(eventDate) { editText?.setOnClickListener { showDateRangePicker() } setEndIconOnClickListener { showDateRangePicker() } } addEventButton.setOnClickListener { if (eventName.text.toString().isNotEmpty() && eventLocation.text.toString().isNotEmpty() && eventDate.editText?.text.toString().isNotEmpty() && eventType.text.toString().isNotEmpty() && eventDescription.text.toString().isNotEmpty()) { //Create a new event instances from the event data class val event = Event( eventName = eventName.text.toString().trim(), eventLocation = eventLocation.text.toString().trim(), eventDate = eventDate.editText?.text.toString().trim() ?: "", eventType = eventType.text.toString().trim(), eventDescription = eventDescription.text.toString().trim() ) showMessage(event) } } } /** * The dateRangePicker method lets the user choose the dates for the event. * The selection is set to the current month's beginning and today's date in UTC milliseconds. * * @see [MaterialDatePicker](https://github.com/material-components/material-components-android/blob/master/docs/components/DatePicker.md) */ private fun showDateRangePicker() { val dateRangePicker = MaterialDatePicker.Builder.dateRangePicker() .setTitleText("Select dates") .setSelection( //pair is a container to ease passing around a tuple of two objects. //https://developer.android.com/reference/kotlin/androidx/core/util/package-summary Pair( MaterialDatePicker.thisMonthInUtcMilliseconds(), MaterialDatePicker.todayInUtcMilliseconds() ) ) .build() dateRangePicker.show(supportFragmentManager, "DATE_RANGE_PICKER") // stitched together from // https://www.geeksforgeeks.org/how-to-implement-date-range-picker-in-android/ dateRangePicker.addOnPositiveButtonClickListener { selection: Pair<Long, Long> -> val startDate = Date(selection.first) val endDate = Date(selection.second) val formatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) //format the picked dates val formattedStartDate = formatter.format(startDate) val formattedEndDate = formatter.format(endDate) //shows the two dates in the right format val dateRangeText = "$formattedStartDate - $formattedEndDate" val eventDate = binding.contentMain.fieldEventDate eventDate.editText?.setText(dateRangeText) } } /** * After the event has been added, the showMessage functions shows the message * with the event info. It uses Android's Snackbar component to present the message * to the user. * * @param event The Event object containing information about the event that has been added. * * @see [Snackbar](https://developer.android.com/reference/com/google/android/material/snackbar/Snackbar) * */ private fun showMessage(event: Event) { // Convert the event details to a string message val message = "Event created: \nName: ${event.eventName} " + "Location: ${event.eventLocation} " + "Date: ${event.eventDate} " + "Type: ${event.eventType} " + "Description: ${event.eventDescription}" // Show Snackbar with the message Snackbar.make(binding.root, message, Snackbar.LENGTH_INDEFINITE).apply { show() } } }
0
Kotlin
0
0
53bde236129243e55f4435c0ff61b76e33b5bc2f
6,213
CopenhagenBuzz
MIT License
data/local/src/main/java/com/redcatgames/movies/data/local/dao/GenreDao.kt
v-kravchenko
484,328,569
false
null
package com.redcatgames.movies.data.local.dao import androidx.room.* import com.redcatgames.movies.data.local.entity.GenreEntity import kotlinx.coroutines.flow.Flow @Dao interface GenreDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(genre: GenreEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(genre: List<GenreEntity>) @Delete suspend fun delete(genre: GenreEntity) @Query("DELETE FROM genres") suspend fun deleteAll() @Update suspend fun update(genre: GenreEntity) @Query("SELECT * FROM genres") fun all(): Flow<List<GenreEntity>> @Query("SELECT * FROM genres") suspend fun getAll(): List<GenreEntity> @Query("SELECT COUNT(1) FROM genres") suspend fun getCount(): Int }
0
Kotlin
0
1
b06edc260f656e07fa220eefcb4333f8478c7204
807
android-movie-lib
MIT License
TIM-Android-lib/src/test/kotlin/com/trifork/timandroid/models/errors/TIMErrorTests.kt
trifork
399,110,548
false
{"Kotlin": 121512}
package com.trifork.timandroid.models.errors import com.trifork.timandroid.testHelpers.* import com.trifork.timencryptedstorage.models.errors.* import org.junit.* class TIMErrorTests { } class TIMStorageErrorTests { companion object { val encryptedStorageFailed = TIMStorageError.EncryptedStorageFailed( TIMEncryptedStorageError.SecureStorageFailed( TIMSecureStorageError.FailedToLoadData( Throwable("Test error!") ) ) ) val badInternet = TIMStorageError.EncryptedStorageFailed( TIMEncryptedStorageError.KeyServiceFailed( TIMKeyServiceError.BadInternet() ) ) val badPassword = TIMStorageError.EncryptedStorageFailed( TIMEncryptedStorageError.KeyServiceFailed( TIMKeyServiceError.BadPassword() ) ) val keyLocked = TIMStorageError.EncryptedStorageFailed( TIMEncryptedStorageError.KeyServiceFailed( TIMKeyServiceError.KeyLocked() ) ) } @Test fun isKeyLocked() { encryptedStorageFailed.isKeyLocked().assertFalse() badInternet.isKeyLocked().assertFalse() badPassword.isKeyLocked().assertFalse() keyLocked.isKeyLocked().assertTrue() } @Test fun isWrongPassword() { encryptedStorageFailed.isWrongPassword().assertFalse() badInternet.isWrongPassword().assertFalse() keyLocked.isWrongPassword().assertFalse() badPassword.isWrongPassword().assertTrue() } @Test fun isKeyServiceError() { encryptedStorageFailed.isKeyServiceError().assertFalse() badInternet.isKeyServiceError().assertTrue() keyLocked.isKeyServiceError().assertTrue() badPassword.isKeyServiceError().assertTrue() } @Test fun isBiometricFailedError() { encryptedStorageFailed.isBiometricFailedError().assertTrue() badInternet.isBiometricFailedError().assertFalse() keyLocked.isBiometricFailedError().assertFalse() badPassword.isBiometricFailedError().assertFalse() } }
3
Kotlin
4
5
136f75a69301e1be0658cb319d53ee8e0e83edad
2,176
TIM-Android
MIT License
app/src/main/java/com/waffiq/bazz_list/ui/notes/DetailNoteActivity.kt
waffiqaziz
837,464,394
false
{"Kotlin": 41811}
package com.waffiq.bazz_list.ui.notes import android.os.Build import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import com.waffiq.bazz_list.R import com.waffiq.bazz_list.databinding.ActivityDetailNoteBinding import com.waffiq.bazz_list.domain.model.Note import com.waffiq.bazz_list.ui.viewmodelfactory.ViewModelFactory import com.waffiq.bazz_list.utils.helper.DbResult import com.waffiq.bazz_list.utils.helper.Helpers.formatTimestamp import java.text.SimpleDateFormat import java.util.Date class DetailNoteActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailNoteBinding private lateinit var detailNoteViewModel: DetailNoteViewModel private lateinit var dataExtra: Note private var isUpdate = false // flag helper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailNoteBinding.inflate(layoutInflater) setContentView(binding.root) val factory = ViewModelFactory.getInstance(this) detailNoteViewModel = ViewModelProvider(this, factory)[DetailNoteViewModel::class.java] setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) onBackPressedDispatcher.addCallback( this /* lifecycle owner */, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { insertNote() finish() } }) getDataExtra() showData() getTotalCharacters() } private fun getDataExtra() { // check if intent hasExtra if (intent.hasExtra(EXTRA_NOTE)) { dataExtra = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(EXTRA_NOTE, Note::class.java) ?: error("No DataExtra") } else { @Suppress("DEPRECATION") intent.getParcelableExtra(EXTRA_NOTE) ?: error("No DataExtra") } } else finish() } // show data or blank data if added private fun showData() { if (dataExtra.id == 0 && dataExtra.dateModified == 0L) { isUpdate = false dateNow() } else { isUpdate = true binding.tvDateNow.text = formatTimestamp(dataExtra.dateModified) binding.etDescription.setText(dataExtra.description) binding.etTitle.setText(dataExtra.title) } // observe detailNoteViewModel.dbResult.observe(this) { it.getContentIfNotHandled().let { dbResult -> when (dbResult) { is DbResult.Success -> showToast( dbResult.message ?: getString(R.string.operation_successful) ) is DbResult.Error -> showToast(dbResult.errorMessage) else -> {} } } } } private fun dateNow() { val formatter = SimpleDateFormat("EEEE, MMMM dd yyyy | HH:mm ", java.util.Locale.getDefault()) val date = Date() binding.tvDateNow.text = formatter.format(date) } private fun getTotalCharacters() { // get total character before typing binding.tvTotalCharacters.text = getString( if (getTotalChar(binding.etDescription.text) == 1) R.string.character else R.string.characters, getTotalChar(binding.etDescription.text).toString() ) // get total character when before typing binding.etDescription.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, star: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, star: Int, count: Int, after: Int) { binding.tvTotalCharacters.text = getString( if (getTotalChar(s) == 1) R.string.character else R.string.characters, getTotalChar(s).toString() ) } override fun afterTextChanged(p0: Editable?) {} }) } private fun getTotalChar(s: CharSequence?): Int? { return s?.toString()?.trim()?.replace(" ", "")?.replace("\n", "")?.length } private fun getTotalChar(s: String?): Int? { return s?.trim()?.replace(" ", "")?.replace("\n", "")?.length } private fun insertNote() { if ((binding.etTitle.text.isNotEmpty() || binding.etDescription.text.isNotEmpty()) && (binding.etTitle.text.isNotBlank() || binding.etDescription.text.isNotBlank()) && !isUpdate ) { val note = Note( id = 0, title = binding.etTitle.text.toString(), description = binding.etDescription.text.toString(), dateModified = System.currentTimeMillis(), hide = false, ) detailNoteViewModel.insertNote(note) } else if (isUpdate) { val note = Note( id = dataExtra.id, title = binding.etTitle.text.toString(), description = binding.etDescription.text.toString(), dateModified = System.currentTimeMillis(), hide = false, ) detailNoteViewModel.updateNote(note) } } private fun showToast(text: String) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } // implement back button override fun onSupportNavigateUp(): Boolean { insertNote() finish() return true } companion object { const val EXTRA_NOTE = "NOTE" } }
0
Kotlin
0
0
c826cdf868e594a6a742c989b59b15336b4e6a66
5,405
BAZZ-List
MIT License
buildSrc/src/main/kotlin/Deps.kt
mazuninky
222,733,264
false
null
object Config { private const val kotlinVersion = "1.3.60" object Common { val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion" } }
0
Kotlin
0
0
f14943fca860873379ab7671ff5b2b1f98b12d8b
172
kotlinx.scraper
MIT License
app/src/main/java/com/perracolabs/yasc/ui/screens/home/HomeScreen.kt
perracodex
714,243,421
false
{"Kotlin": 65172}
/* * Copyright (c) 2023 <NAME>. All rights reserved. * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT> */ package com.perracolabs.yasc.ui.screens.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.perracolabs.yasc.R import com.perracolabs.yasc.ui.LocalDrawerState import com.perracolabs.yasc.ui.components.bars.AppBarAction import com.perracolabs.yasc.ui.components.bars.MainAppBar import com.perracolabs.yasc.ui.navigation.Route import com.perracolabs.yasc.ui.themes.ThemeLayout import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @Composable fun HomeScreen() { val onAction = remember { mutableStateOf(false) } Scaffold( topBar = { TopBar(onAction = onAction) }, content = { innerPadding -> Content(innerPadding) } ) if (onAction.value) { ShowMessage(onDismiss = { onAction.value = false }) } } @Composable private fun TopBar(onAction: MutableState<Boolean>) { val drawerState: DrawerState = LocalDrawerState.current val scope: CoroutineScope = rememberCoroutineScope() val navigationAction: AppBarAction = remember { AppBarAction(iconId = R.drawable.ic_menu, callback = { scope.launch { drawerState.open() } }) } val overflowAction: AppBarAction = remember(drawerState.isClosed, onAction.value) { AppBarAction(iconId = R.drawable.ic_overflow, callback = { if (drawerState.isClosed) onAction.value = true }) } MainAppBar( title = stringResource(id = Route.HOME.resourceId), leadingAction = navigationAction, trailingAction = overflowAction ) } @Composable private fun Content(innerPadding: PaddingValues) { var selectedItem: Int by remember { mutableIntStateOf(0) } val items: List<String> = listOf("Songs", "Artists", "Playlists") Box( modifier = Modifier .background(MaterialTheme.colorScheme.surface) .fillMaxSize() .padding(innerPadding) ) { NavigationBar( modifier = Modifier.align(Alignment.BottomCenter) ) { items.forEachIndexed { index, item -> NavigationBarItem( icon = { Icon(Icons.Filled.Favorite, contentDescription = item) }, label = { Text(item) }, selected = selectedItem == index, onClick = { selectedItem = index } ) } } } } @Composable private fun ShowMessage(onDismiss: () -> Unit) { AlertDialog( onDismissRequest = onDismiss, shape = RoundedCornerShape(dimensionResource(id = R.dimen.button_radius)), confirmButton = { Button( onClick = onDismiss, shape = RoundedCornerShape(dimensionResource(id = R.dimen.button_radius)) ) { Text(text = "Close") } }, title = { Text(text = stringResource(id = R.string.app_name)) }, text = { Text(text = "Hello World") } ) } @Preview(showBackground = true) @Composable fun PreviewHomeScreen() { ThemeLayout { HomeScreen() } }
0
Kotlin
0
1
00dde714f354ee54bbd37d10b3bcf77c318a2843
3,965
yasc
MIT License
srcom/src/main/kotlin/dev/qixils/gdq/src/SpeedrunClient.kt
qixils
517,457,295
false
{"Kotlin": 222445, "Svelte": 33727, "TypeScript": 26237, "CSS": 13749, "HTML": 910, "JavaScript": 848}
package dev.qixils.gdq.src import dev.qixils.gdq.src.models.BulkGame import dev.qixils.gdq.src.models.FullGame import dev.qixils.gdq.src.models.Model import dev.qixils.gdq.src.models.Response import kotlinx.coroutines.delay import kotlinx.coroutines.future.await import kotlinx.serialization.KSerializer import kotlinx.serialization.json.Json import org.slf4j.LoggerFactory import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.charset.StandardCharsets import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit open class SpeedrunClient( private val apiKey: String? = null, ) { private val logger = LoggerFactory.getLogger(SpeedrunClient::class.java) private val json: Json = Json { ignoreUnknownKeys = true isLenient = true coerceInputValues = true } private val client: HttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20)).build() private val baseUrl = "https://www.speedrun.com/api/v1/" private val recentRequests = mutableListOf<Instant>() companion object : SpeedrunClient() private fun recentRequests(): List<Instant> { recentRequests.removeIf { it.isBefore(Instant.now().minus(1, ChronoUnit.MINUTES)) } return recentRequests } private suspend fun <M : Model> get(request: HttpRequest.Builder, serializer: KSerializer<M>): Response<M> { var delay = 1000L while (recentRequests().size >= 100) { delay(delay) delay *= 2 } recentRequests.add(Instant.now()) if (apiKey != null) request.header("X-API-Key", apiKey) val response = client.sendAsync(request.build(), HttpResponse.BodyHandlers.ofString()).await() if (response.statusCode() != 200) { logger.error("Request failed with status code ${response.statusCode()}: ${response.body()}") throw RuntimeException("Request failed with status code ${response.statusCode()}") } return json.decodeFromString(Response.serializer(serializer), response.body()) } private suspend fun <M : Model> get(uri: URI, serializer: KSerializer<M>): Response<M> { return get(HttpRequest.newBuilder(uri), serializer) } private suspend fun <M : Model> get(path: String, serializer: KSerializer<M>): Response<M> { return get(URI.create("$baseUrl$path"), serializer) } suspend fun getGames(): Response<FullGame> { return get("games", FullGame.serializer()) } suspend fun getBulkGames(): List<BulkGame> { val games = mutableListOf<BulkGame>() var response: Response<BulkGame> var offset = 0 do { response = get("games?_bulk=yes&max=1000&offset=$offset", BulkGame.serializer()) offset += response.pagination.size } while (response.pagination.size == response.pagination.max) return games } suspend fun getGame(id: String): FullGame? { return get("games/$id", FullGame.serializer()).data.firstOrNull() } suspend fun getGamesByName(name: String): List<FullGame> { return get("games?name=${name.encode()}", FullGame.serializer()).data } } fun String.encode(): String { return URLEncoder.encode(this, StandardCharsets.UTF_8) }
7
Kotlin
0
4
784c8d7e4809639bbb57ae56dd7ebbd485565432
3,404
kgdq
MIT License
app/src/main/java/com/weatherapp/presentation/navigation/BottomBarScreen.kt
AhmedZaki918
529,578,472
false
{"Kotlin": 142653}
package com.weatherapp.presentation.navigation import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.ui.graphics.vector.ImageVector import com.weatherapp.data.local.Constants.HOME import com.weatherapp.data.local.Constants.SEARCH import com.weatherapp.data.local.Constants.SETTINGS import com.weatherapp.data.local.Constants.WISHLIST sealed class BottomBarScreen( val route: String, val icon: ImageVector ) { data object Home : BottomBarScreen( route = HOME, icon = Icons.Default.Home ) data object Search : BottomBarScreen( route = SEARCH, icon = Icons.Default.Search ) data object Wishlist: BottomBarScreen( route = WISHLIST, icon = Icons.Default.Favorite ) data object Settings : BottomBarScreen( route = SETTINGS, icon = Icons.Default.Settings ) }
0
Kotlin
1
10
fdaf1ab7f8d5676517b584754c8306c75b41f90e
1,091
Weather-App
The Unlicense
ksol-keygen/src/test/kotlin/com/dgsd/ksol/keygen/DerivationPathTests.kt
dlgrech
524,875,633
false
null
package com.dgsd.ksol.keygen import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class DerivationPathTests { @Test fun solanaBip44_whenInvoked_createsExpectedPath() { val path = DerivationPath.solanaBip44(1337) Assertions.assertEquals(44, path.purpose) Assertions.assertEquals(501, path.coinType) Assertions.assertEquals(1337, path.account) Assertions.assertEquals(0, path.change) } }
0
Kotlin
2
9
153e922fa405d6ba6c33041002bcf53d6293c7cf
436
ksol
Apache License 2.0
ksol-keygen/src/test/kotlin/com/dgsd/ksol/keygen/DerivationPathTests.kt
dlgrech
524,875,633
false
null
package com.dgsd.ksol.keygen import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class DerivationPathTests { @Test fun solanaBip44_whenInvoked_createsExpectedPath() { val path = DerivationPath.solanaBip44(1337) Assertions.assertEquals(44, path.purpose) Assertions.assertEquals(501, path.coinType) Assertions.assertEquals(1337, path.account) Assertions.assertEquals(0, path.change) } }
0
Kotlin
2
9
153e922fa405d6ba6c33041002bcf53d6293c7cf
436
ksol
Apache License 2.0
core/src/jvmMain/kotlin/dev/inmo/kmppscriptbuilder/core/ui/GpgSigningOptionDrawer.kt
InsanusMokrassar
342,929,719
false
{"Kotlin": 74639, "HTML": 4156, "CSS": 45}
package dev.inmo.kmppscriptbuilder.core.ui import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import dev.inmo.kmppscriptbuilder.core.models.GpgSigning import dev.inmo.kmppscriptbuilder.core.ui.utils.CommonTextField import dev.inmo.kmppscriptbuilder.core.ui.utils.Drawer import dev.inmo.kmppscriptbuilder.core.ui.utils.SwitchWithLabel actual class GpgSigningOptionDrawer( private val mavenInfoView: MavenInfoView ) : Drawer<GpgSigning> { @Composable override fun GpgSigning.draw() { if (mavenInfoView.gpgSignProperty == this) { Button({}, Modifier.padding(8.dp, 0.dp)) { Text(name) } } else { OutlinedButton( { mavenInfoView.gpgSignProperty = this }, Modifier.padding(8.dp, 0.dp) ) { Text(name) } } } } actual fun GpgSigningOptionDrawerWithView(view: MavenInfoView): GpgSigningOptionDrawer = GpgSigningOptionDrawer(mavenInfoView = view)
2
Kotlin
0
3
87f77543e2fb3525acdfa397b5d8c483e4db1599
1,361
KotlinPublicationScriptsBuilder
Apache License 2.0
cottontaildb-core/src/main/kotlin/org/vitrivr/cottontail/core/queries/planning/cost/AtomicCostEstimator.kt
vitrivr
160,775,368
false
{"Kotlin": 2769415, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548}
package org.vitrivr.cottontail.core.queries.planning.cost import java.util.* import kotlin.system.measureNanoTime /** * The atomic [AtomicCostEstimator]. * * @author <NAME> * @version 1.0.0 */ object AtomicCostEstimator { /** Number of repetitions to run when estimating atomic [Cost]s. */ private const val ESTIMATION_REPETITION = 1_000_000 /** * Estimates the cost of memory access based on a series of measurements. */ fun estimateAtomicMemoryAccessCost(): Cost { val random = SplittableRandom() var time = 0L repeat(ESTIMATION_REPETITION) { var a = random.nextLong() var b = random.nextLong() var c: Long time += measureNanoTime { c = a a = b b = c } c + b } return Cost(cpu =((time) / (ESTIMATION_REPETITION * 3)) * 1e-9f) } /** * Estimates the cost of a single floating point operation based on a series of measurements * for add, subtraction, multiplication and division */ fun estimateAtomicFlopCost(): Cost { val random = SplittableRandom() var timeAdd = 0L repeat(ESTIMATION_REPETITION) { val a = random.nextDouble() val b = random.nextDouble() timeAdd += measureNanoTime { a + b } } var timeSubtract = 0L repeat(ESTIMATION_REPETITION) { val a = random.nextDouble() val b = random.nextDouble() timeSubtract += measureNanoTime { a - b } } var timeMultiply = 0L repeat(ESTIMATION_REPETITION) { val a = random.nextDouble() val b = random.nextDouble() timeMultiply += measureNanoTime { a * b } } var timeDivide = 0L repeat(ESTIMATION_REPETITION) { val a = random.nextDouble() val b = random.nextDouble(1.0) timeDivide += measureNanoTime { a / b } } return Cost(cpu = ((timeAdd + timeSubtract + timeMultiply + timeDivide) / (ESTIMATION_REPETITION * 4)) * 1e-9f) } }
24
Kotlin
20
38
bc4d0aa435aac78628fa7771dbf8333f1fe5a971
2,270
cottontaildb
MIT License
kotlin/src/katas/kotlin/leetcode/longest_substring_palindrome/LongestPalindromeTests.kt
dkandalov
2,517,870
false
null
@file:Suppress("DuplicatedCode", "unused") package katas.kotlin.leetcode.longest_substring_palindrome import nonstdlib.measureDuration import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/longest-palindromic-substring */ class LongestPalindromeTests { @Test fun `trivial examples`() { findLongestPalindrome("") shouldEqual "" findLongestPalindrome("a") shouldEqual "a" findLongestPalindrome("b") shouldEqual "b" findLongestPalindrome("c") shouldEqual "c" } @Test fun `match at the beginning of the string`() { findLongestPalindrome("abc") shouldEqual "a" findLongestPalindrome("aabc") shouldEqual "aa" findLongestPalindrome("ababc") shouldEqual "aba" } @Test fun `match in the middle of the string`() { findLongestPalindrome("abbc") shouldEqual "bb" findLongestPalindrome("aabbbc") shouldEqual "bbb" findLongestPalindrome("abaabc") shouldEqual "baab" } @Test fun `match at the end of the string`() { findLongestPalindrome("abcc") shouldEqual "cc" findLongestPalindrome("abaab") shouldEqual "baab" } @Test fun `match long palindrome`() { findLongestPalindrome(longPalindrome) shouldEqual longPalindrome } } private val chars = (0..100_000).map { it.toChar() } private val longChars = chars.joinToString("") private val longPalindrome = chars .let { chars -> (chars + chars.reversed()).joinToString("") } class PalindromeTests { @Test fun `check that string is a palindrome`() { "".isPalindrome() shouldEqual true "a".isPalindrome() shouldEqual true "ab".isPalindrome() shouldEqual false "aba".isPalindrome() shouldEqual true "abba".isPalindrome() shouldEqual true "abcba".isPalindrome() shouldEqual true "abccba".isPalindrome() shouldEqual true "abcba_".isPalindrome() shouldEqual false } @Test fun `check that long string is a palindrome`() { measureDuration { longPalindrome.isPalindrome() shouldEqual true } } } private fun findLongestPalindrome(s: String): String { val map = HashMap<Char, MutableList<Int>>() (0 until s.length).forEach { i -> map.getOrPut(s[i], { ArrayList() }).add(i) } var result = "" (0 until s.length).forEach { i -> println(i) if (s.length - i <= result.length) return result val nextIndices = map[s[i]]!! for (j in nextIndices.asReversed()) { val substringLength = j + 1 - i if (j < i || substringLength <= result.length) break val substring = s.subSequence(i, j + 1) if (substring.length > result.length && substring.isPalindrome()) { result = s.substring(i, j + 1) } } } return result } private fun CharSequence.isPalindrome(): Boolean { if (length <= 1) return true var i = 0 var j = length - 1 while (i <= j) { if (this[i] != this[j]) return false i++ j-- } return true } private fun findLongestPalindrome_func(s: String): String { return (0..s.length) .flatMap { start -> (start..s.length).map { end -> start..end } } .map { range -> s.substring(range.first, range.last) } .filter { it.isPalindrome() } .fold("") { acc, it -> if (it.length > acc.length) it else acc } } private fun String.isPalindrome_(): Boolean { if (length <= 1) return true var i = 0 var j = length - 1 while (i <= j) { if (this[i] != this[j]) return false i++ j-- } return true }
7
null
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,694
katas
The Unlicense
Retos/Reto #3 - EL GENERADOR DE CONTRASEÑAS [Media]/kotlin/ivancordonm.kt
mouredev
581,049,695
false
{"Python": 4194087, "JavaScript": 1590517, "Java": 1408944, "C#": 782329, "Kotlin": 533858, "TypeScript": 479964, "Rust": 357628, "Go": 322940, "PHP": 288620, "Swift": 278290, "C": 223896, "Jupyter Notebook": 221090, "C++": 175187, "Dart": 159755, "Ruby": 71132, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 33508, "Haskell": 27994, "Shell": 27979, "R": 19771, "Lua": 16964, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12839, "F#": 12816, "Pascal": 12673, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Carbon": 2611, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1394, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "Haxe": 112, "HolyC": 110, "OpenEdge ABL": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "TeX": 72, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Mojo": 37, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
import java.util.* fun main() { val reader = Scanner(System.`in`) fun question(q: String): Boolean { var response = "X" while (response != "N" && response != "S") { print(q) response = reader.next().uppercase(Locale.getDefault()) } return response == "S" } var len = 0 while (len < 8 || len > 16) { print("Longitud: Entre 8 y 16: ") len = reader.nextInt() } val withCapitals = question("¿Incluir mayúsculas? (S/N): ") val withNumbers = question("¿Incluir números? (S/N): ") val withSymbols = question("¿Incluir símbolos? (S/N): ") var chars = ('a'..'z').toList() val capitals = ('A'..'Z').toList() val numbers = ('0'..'9').toList() val symbols = listOf(':', '.', ';', '_', '-', '$', '%', '&') val message = buildString { append("Contraseña de longitud $len ") if (withCapitals) { chars = chars + capitals append("que incluye mayúsculas ") } if (withNumbers) { chars = chars + numbers append("que incluye números ") } if (withSymbols) { chars = chars + symbols append("que incluye símbolos ") } append(": ") } val password = (1..len).map { chars[(0..chars.lastIndex).random()] }.joinToString("") println("$message $password") }
1
Python
2974
5,192
f8c44ac12756b14a32abf57cbf4e0cd06ad58088
1,413
retos-programacion-2023
Apache License 2.0
workflows/src/main/kotlin/com/flows/TriggerRobberFlow.kt
rajeshso
197,255,576
true
{"Kotlin": 288198, "HTML": 168, "JavaScript": 53}
package com.flows import com.contractsAndStates.contracts.RobberContract import com.contractsAndStates.states.HexTileIndex import com.oracleClientStatesAndContracts.states.DiceRollState import net.corda.core.contracts.ReferencedStateAndRef import net.corda.core.contracts.UniqueIdentifier import net.corda.core.flows.* import net.corda.core.node.services.queryBy import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder @InitiatingFlow(version = 1) @StartableByRPC class TriggerRobberFlow(val gameBoardLinearId: UniqueIdentifier, val updatedRobberLocation: Int) : FlowLogic<SignedTransaction>() { override fun call(): SignedTransaction { // Step 1. Get a reference to the notary service on the network val notary = serviceHub.networkMapCache.notaryIdentities.first() // Step 2. Retrieve the Game Board State from the vault. val gameBoardStateAndRef = getGameBoardStateFromLinearID(gameBoardLinearId, serviceHub) val gameBoardState = gameBoardStateAndRef.state.data val gameBoardReferenceStateAndRef = ReferencedStateAndRef(gameBoardStateAndRef) // Step 3. Retrieve the Turn Tracker State from the vault val turnTrackerStateAndRef = getTurnTrackerStateFromLinearID(gameBoardState.linearId, serviceHub) val turnTrackerReferenceStateAndRef = ReferencedStateAndRef(turnTrackerStateAndRef) // Step 4. Retrieve the Dice Roll State from the vault val diceRollStateAndRef = serviceHub.vaultService.queryBy<DiceRollState>().states.filter { it.state.data.gameBoardStateUniqueIdentifier == gameBoardLinearId }.single() // Step 5. Add the existing robber state as an input state val robberStateAndRef = getRobberStateFromLinearID(gameBoardState.linearId, serviceHub) // Step 6. Create a new robber state val movedRobberState = robberStateAndRef.state.data.move(HexTileIndex(updatedRobberLocation)) // Step 7. Create the appropriate command val command = RobberContract.Commands.MoveRobber() // Step 8. Create a transaction builder and add all input/output states val tb = TransactionBuilder(notary) tb.addInputState(robberStateAndRef) tb.addInputState(diceRollStateAndRef) tb.addOutputState(movedRobberState) tb.addReferenceState(gameBoardReferenceStateAndRef) tb.addReferenceState(turnTrackerReferenceStateAndRef) tb.addCommand(command, gameBoardState.players.map { it.owningKey }) // Step 9. Verify and sign the transaction tb.verify(serviceHub) val ptx = serviceHub.signInitialTransaction(tb) // Step 10. Collect Signatures on the transaction val sessions = (gameBoardState.players - ourIdentity).map { initiateFlow(it) } val stx = subFlow(CollectSignaturesFlow(ptx, sessions)) // Step 11. Finalize the transaction return subFlow(FinalityFlow(stx, sessions)) } }
0
Kotlin
0
0
572f42d593b1728d87b682275d5b8b9ada281d9b
3,013
SettlersOfCordan
Apache License 2.0
app/src/main/java/com/bogdanlonchuk/modernapp/base/BaseViewModel.kt
bgdlnchk
330,440,060
false
null
package com.bogdanlonchuk.modernapp.base import androidx.lifecycle.ViewModel import com.bogdanlonchuk.modernapp.injection.NetworkModule import com.bogdanlonchuk.modernapp.injection.DaggerViewModelInjector import com.bogdanlonchuk.modernapp.injection.ViewModelInjector import com.bogdanlonchuk.modernapp.ui.PostListViewModel abstract class BaseViewModel: ViewModel() { private val injector: ViewModelInjector = DaggerViewModelInjector .builder() .networkModule(NetworkModule) .build() init { inject() } private fun inject() { when (this) { is PostListViewModel -> injector.inject(this) } } }
0
Kotlin
0
0
da8dbbaece3f1246993baa089f84f1290e681629
687
ModernAndroidApp
Apache License 2.0
app/src/main/java/eu/caraus/dynamo/application/data/local/udacity/converters/FlagsTypeConverter.kt
alexandrucaraus
140,244,389
false
{"Kotlin": 69803, "Java": 19004}
package eu.caraus.dynamo.application.data.local.udacity.converters import android.arch.persistence.room.TypeConverter import com.google.common.reflect.TypeToken import com.google.gson.Gson import eu.caraus.dynamo.application.data.domain.udacity.Flags class FlagsTypeConverter { @TypeConverter fun toFlags( flagsAsString : String? ) : Flags { if( flagsAsString == null){ Flags(0,false,false,false,false,false,false) } return Gson().fromJson<Flags>( flagsAsString!! ) } @TypeConverter fun fromFlags( flags : Flags ) : String? { return Gson().toJson( flags ) } inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type) }
0
Kotlin
0
0
e0ab8096448088b23ee908abda7ec2d9791cd099
749
ShowCase-UdacityApiMvvm
MIT License
src/main/kotlin/no/nav/syfo/persistering/HandleRecivedMessage.kt
janzh
381,036,344
true
{"Kotlin": 381912, "Dockerfile": 105}
package no.nav.syfo.persistering import io.ktor.util.KtorExperimentalAPI import java.time.LocalDate import net.logstash.logback.argument.StructuredArguments import net.logstash.logback.argument.StructuredArguments.fields import no.nav.syfo.client.OppgaveClient import no.nav.syfo.client.finnFristForFerdigstillingAvOppgave import no.nav.syfo.db.Database import no.nav.syfo.log import no.nav.syfo.metrics.INCOMING_MESSAGE_COUNTER import no.nav.syfo.metrics.MESSAGE_STORED_IN_DB_COUNTER import no.nav.syfo.metrics.OPPRETT_OPPGAVE_COUNTER import no.nav.syfo.model.OpprettOppgave import no.nav.syfo.model.PapirSmRegistering import no.nav.syfo.persistering.db.erOpprettManuellOppgave import no.nav.syfo.persistering.db.opprettManuellOppgave import no.nav.syfo.util.LoggingMeta import no.nav.syfo.util.wrapExceptions @KtorExperimentalAPI suspend fun handleRecivedMessage( papirSmRegistering: PapirSmRegistering, database: Database, oppgaveClient: OppgaveClient, loggingMeta: LoggingMeta ) { wrapExceptions(loggingMeta) { log.info("Mottok ein manuell papirsykmelding registerings, {}", fields(loggingMeta)) INCOMING_MESSAGE_COUNTER.inc() if (database.erOpprettManuellOppgave(papirSmRegistering.sykmeldingId)) { log.warn( "Manuell papirsykmelding registerings oppgave med sykmeldingsid {}, er allerede lagret i databasen, {}", papirSmRegistering.sykmeldingId, fields(loggingMeta) ) } else { val opprettOppgave = OpprettOppgave( aktoerId = papirSmRegistering.aktorId, opprettetAvEnhetsnr = "9999", behandlesAvApplikasjon = "SMR", beskrivelse = "Manuell registrering av sykmelding mottatt på papir", tema = "SYM", oppgavetype = "JFR", aktivDato = LocalDate.now(), fristFerdigstillelse = finnFristForFerdigstillingAvOppgave( LocalDate.now().plusDays(4) ), prioritet = "HOY", journalpostId = papirSmRegistering.journalpostId ) val oppgave = oppgaveClient.opprettOppgave(opprettOppgave, papirSmRegistering.sykmeldingId) OPPRETT_OPPGAVE_COUNTER.inc() log.info( "Opprettet manuell papir sykmeldingoppgave med {}, {}", StructuredArguments.keyValue("oppgaveId", oppgave.id), fields(loggingMeta) ) database.opprettManuellOppgave(papirSmRegistering, oppgave.id!!) log.info( "Manuell papir sykmeldingoppgave lagret i databasen, for {}, {}", StructuredArguments.keyValue("oppgaveId", oppgave.id), fields(loggingMeta) ) MESSAGE_STORED_IN_DB_COUNTER.inc() } } }
0
null
0
0
d075df24dba4afcb82e248651eb3c0a3edf4448f
2,876
smregistrering-backend
MIT License
src/main/java/com/sdk/application/apis/logistic/LogisticApiList.kt
gofynd
337,940,340
false
null
package com.sdk.application.apis.logistic import kotlinx.coroutines.Deferred import retrofit2.Response import okhttp3.ResponseBody import retrofit2.http.* import retrofit2.http.Url import com.sdk.application.* import com.sdk.application.models.logistic.* interface LogisticApiList { @GET fun getPincodeCity(@Url url1: String? , @Query("country_code") countryCode: String?) : Deferred<Response<PincodeApiResponse>> @POST fun getTatProduct(@Url url1: String? ,@Body body: TATViewRequest) : Deferred<Response<TATViewResponse>> @GET fun getAllCountries(@Url url1: String? ) : Deferred<Response<CountryListResponse>> @POST fun getPincodeZones(@Url url1: String? ,@Body body: GetZoneFromPincodeViewRequest) : Deferred<Response<GetZoneFromPincodeViewResponse>> }
0
Kotlin
4
3
2a590efaf7f7e2742c72fe4613b4e8b5e2551945
865
fdk-client-kotlin
MIT License