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
core/base/src/main/kotlin/ai/flox/arch/MutableStateFlowStore.kt
saumye
740,020,576
false
{"Kotlin": 110084}
package ai.flox.arch import ai.flox.state.Action import ai.flox.state.State import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch internal class MutableStateFlowStore<S : State, A : Action> private constructor( override val state: StateFlow<S>, private val sendFn: (List<A>) -> Unit, ) : Store<S, A> { // override fun <ViewState: S, ViewAction : A> view( // mapToLocalState: (State) -> ViewState, // mapToGlobalAction: (ViewAction) -> A?, // ): Store<ViewState, ViewAction> = MutableStateFlowStore( // state = state.map { mapToLocalState(it) }.distinctUntilChanged(), // sendFn = { actions -> // val globalActions = actions.mapNotNull(mapToGlobalAction) // sendFn(globalActions) // }, // ) companion object { fun <S : State, A : Action> create( initialState: S, reducer: Reducer<S, A> ): Store<S, A> { val state = MutableStateFlow(initialState) val noEffect = NoEffect lateinit var send: (List<A>) -> Unit send = { actions -> CoroutineScope(Dispatchers.Main).launch(context = Dispatchers.Main) { val result: ReduceResult<S, A> = actions.fold(ReduceResult(state.value, noEffect)) { accResult, action -> val (nextState, nextEffect) = reducer.reduce( accResult.state, action ) return@fold ReduceResult( nextState, accResult.effect mergeWith nextEffect ) } state.value = result.state result.effect.run() .onEach { action -> send(listOf(action)) } .launchIn(CoroutineScope(Dispatchers.Main)) } } return MutableStateFlowStore(state, send) } } override fun dispatch(vararg actions: A) { sendFn(actions.asList()) } }
0
Kotlin
0
1
aefa8a4a526594fde635a0f33d9d95bacb339798
2,387
flox
Apache License 2.0
src/jsMain/kotlin/com/jeffpdavidson/kotwords/web/JellyRollForm.kt
jpd236
143,651,464
false
null
package com.jeffpdavidson.kotwords.web import com.jeffpdavidson.kotwords.KotwordsInternal import com.jeffpdavidson.kotwords.model.JellyRoll import com.jeffpdavidson.kotwords.model.Puzzle import com.jeffpdavidson.kotwords.util.trimmedLines import com.jeffpdavidson.kotwords.web.html.FormFields import com.jeffpdavidson.kotwords.web.html.Html import kotlinx.html.InputType import kotlinx.html.div @JsExport @KotwordsInternal class JellyRollForm { private val form = PuzzleFileForm("jelly-roll", ::createPuzzle) private val jellyRollAnswers: FormFields.TextBoxField = FormFields.TextBoxField("jelly-roll-answers") private val jellyRollClues: FormFields.TextBoxField = FormFields.TextBoxField("jelly-roll-clues") private val lightSquaresAnswers: FormFields.TextBoxField = FormFields.TextBoxField("light-squares-answers") private val lightSquaresClues: FormFields.TextBoxField = FormFields.TextBoxField("light-squares-clues") private val lightSquaresColor: FormFields.InputField = FormFields.InputField("light-squares-color") private val darkSquaresAnswers: FormFields.TextBoxField = FormFields.TextBoxField("dark-squares-answers") private val darkSquaresClues: FormFields.TextBoxField = FormFields.TextBoxField("dark-squares-clues") private val darkSquaresColor: FormFields.InputField = FormFields.InputField("dark-squares-color") private val combineJellyRollClues: FormFields.CheckBoxField = FormFields.CheckBoxField("combine-jelly-roll-clues") init { Html.renderPage { form.render(this, bodyBlock = { jellyRollAnswers.render(this, "Jelly roll answers") { placeholder = "In sequential order, separated by whitespace. " + "Non-alphabetical characters are ignored." rows = "5" } jellyRollClues.render(this, "Jelly roll clues") { placeholder = "One clue per row. Omit clue numbers." rows = "10" } lightSquaresAnswers.render(this, "Light squares answers (first, fourth, fifth, seventh, etc.)") { placeholder = "In sequential order, separated by whitespace. " + "Non-alphabetical characters are ignored." rows = "5" } lightSquaresClues.render(this, "Light squares clues") { placeholder = "One clue per row. Omit clue numbers." rows = "10" } darkSquaresAnswers.render(this, "Dark squares answers (second, third, sixth, etc.)") { placeholder = "In sequential order, separated by whitespace. " + "Non-alphabetical characters are ignored." rows = "5" } darkSquaresClues.render(this, "Dark squares clues") { placeholder = "One clue per row. Omit clue numbers." rows = "10" } }, advancedOptionsBlock = { combineJellyRollClues.render(this, "Combine Jelly Roll clues into one large clue") div(classes = "form-row") { lightSquaresColor.render(this, "Light squares color", flexCols = 6) { type = InputType.color value = "#FFFFFF" } darkSquaresColor.render(this, "Dark squares color", flexCols = 6) { type = InputType.color value = "#C0C0C0" } } }) } } private suspend fun createPuzzle(): Puzzle { val jellyRoll = JellyRoll( title = form.title, creator = form.creator, copyright = form.copyright, description = form.description, jellyRollAnswers = jellyRollAnswers.value.uppercase().split("\\s+".toRegex()), jellyRollClues = jellyRollClues.value.trimmedLines(), lightSquaresAnswers = lightSquaresAnswers.value.uppercase().split("\\s+".toRegex()), lightSquaresClues = lightSquaresClues.value.trimmedLines(), darkSquaresAnswers = darkSquaresAnswers.value.uppercase().split("\\s+".toRegex()), darkSquaresClues = darkSquaresClues.value.trimmedLines(), lightSquareBackgroundColor = lightSquaresColor.value, darkSquareBackgroundColor = darkSquaresColor.value, combineJellyRollClues = combineJellyRollClues.value, ) return jellyRoll.asPuzzle() } }
7
Kotlin
2
12
28a3940e6268118be5496f8d21ce0e965f8641da
4,653
kotwords
Apache License 2.0
src/main/kotlin/counters/minter/sdk/minter_api/parse/ParsePool.kt
counters
196,465,317
false
null
package counters.minter.sdk.minter_api.parse import counters.minter.sdk.minter.CoinObjClass import counters.minter.sdk.minter.MinterMatch import counters.minter.sdk.minter.MinterRaw import org.json.JSONObject class ParsePool { private val minterMatch = MinterMatch() fun getRaw(result: JSONObject): MinterRaw.PoolRaw? { val data = result.getJSONObject("data") val coin0 = CoinObjClass.fromJson(data.getJSONObject("coin0")) val coin1 = CoinObjClass.fromJson(data.getJSONObject("coin1")) val volume0 = data.getString("volume0") val volume1 = data.getString("volume1") val tags = result.getJSONObject("tags") val id = tags.getInt("tx.pool_id") val liquidity = tags.getString("tx.liquidity") val pool_token = tags.getString("tx.pool_token") val pool_token_id = tags.getLong("tx.pool_token_id") val token = CoinObjClass.CoinObj(pool_token_id, pool_token) if (coin0!=null && coin1!=null) return MinterRaw.PoolRaw( id, coin0, coin1, minterMatch.getAmount(volume0), minterMatch.getAmount(volume1), minterMatch.getAmount(liquidity), token, ) return null } }
0
Kotlin
3
7
dd03cc8a1e0b4c21ceb03dbceff7b0fe4136d4ca
1,277
minter-kotlin-sdk
Apache License 2.0
server/src/main/kotlin/nl/knaw/huc/annorepo/resources/tools/AggregateStageGenerator.kt
knaw-huc
473,687,323
false
null
package nl.knaw.huc.annorepo.resources.tools import jakarta.json.JsonNumber import jakarta.json.JsonString import jakarta.ws.rs.BadRequestException import com.mongodb.client.model.Aggregates import com.mongodb.client.model.Filters import org.bson.conversions.Bson import org.slf4j.Logger import org.slf4j.LoggerFactory import nl.knaw.huc.annorepo.config.AnnoRepoConfiguration class AggregateStageGenerator(val configuration: AnnoRepoConfiguration) { val log: Logger = LoggerFactory.getLogger(this::class.java) fun generateStage(key: Any, value: Any): Bson = when (key) { !is String -> throw BadRequestException("Unexpected field: '$key' ; query root fields should be strings") WITHIN_RANGE -> withinRangeStage(value) OVERLAPPING_WITH_RANGE -> overlappingWithRangeStage(value) else -> { if (key.startsWith(":")) { throw BadRequestException("Unknown query function: '$key'") } else { log.debug("key={}, value={} ({})", key, value, value.javaClass) fieldMatchStage(key, value) } } } @Suppress("UNCHECKED_CAST") private fun fieldMatchStage(key: String, value: Any): Bson = when (value) { is Map<*, *> -> specialFieldMatchStage(key, value as Map<String, Any>) else -> Aggregates.match(Filters.eq("$ANNOTATION_FIELD_PREFIX$key", value)) } private fun specialFieldMatchStage(field: String, value: Map<String, Any>): Bson = Filters.and(value.map { (k, v) -> return when (k) { IS_NOT_IN -> try { val valueAsList = (v as Array<Any>).toList() Aggregates.match( Filters.nin("$ANNOTATION_FIELD_PREFIX$field", valueAsList) ) } catch (e: ClassCastException) { throw BadRequestException("$IS_NOT_IN parameter must be a list") } IS_IN -> try { val valueAsList = (v as Array<Any>).toList() Aggregates.match( Filters.`in`("$ANNOTATION_FIELD_PREFIX$field", valueAsList) ) } catch (e: ClassCastException) { throw BadRequestException("$IS_IN parameter must be a list") } IS_GREATER -> Aggregates.match( Filters.gt("$ANNOTATION_FIELD_PREFIX$field", v) ) IS_GREATER_OR_EQUAL -> Aggregates.match( Filters.gte("$ANNOTATION_FIELD_PREFIX$field", v) ) IS_LESS -> Aggregates.match( Filters.lt("$ANNOTATION_FIELD_PREFIX$field", v) ) IS_LESS_OR_EQUAL -> Aggregates.match( Filters.lte("$ANNOTATION_FIELD_PREFIX$field", v) ) IS_EQUAL_TO -> Aggregates.match( Filters.eq("$ANNOTATION_FIELD_PREFIX$field", v) ) IS_NOT -> Aggregates.match( Filters.ne("$ANNOTATION_FIELD_PREFIX$field", v) ) else -> throw BadRequestException("unknown selector '$k'") } }) private fun overlappingWithRangeStage(rawParameters: Any): Bson = when (rawParameters) { is Map<*, *> -> { val rangeParameters = rangeParameters(rawParameters) Aggregates.match( Filters.and( Filters.eq("${ANNOTATION_FIELD_PREFIX}target.source", rangeParameters.source), Filters.eq("${ANNOTATION_FIELD_PREFIX}target.selector.type", configuration.rangeSelectorType), Filters.lte("${ANNOTATION_FIELD_PREFIX}target.selector.start", rangeParameters.end), Filters.gte("${ANNOTATION_FIELD_PREFIX}target.selector.end", rangeParameters.start), ) ) } else -> throw BadRequestException("invalid parameter: $rawParameters") } private fun withinRangeStage(rawParameters: Any): Bson = when (rawParameters) { is Map<*, *> -> { val rangeParameters = rangeParameters(rawParameters) Aggregates.match( Filters.and( Filters.eq("${ANNOTATION_FIELD_PREFIX}target.source", rangeParameters.source), Filters.eq("${ANNOTATION_FIELD_PREFIX}target.selector.type", configuration.rangeSelectorType), Filters.gte("${ANNOTATION_FIELD_PREFIX}target.selector.start", rangeParameters.start), Filters.lte("${ANNOTATION_FIELD_PREFIX}target.selector.end", rangeParameters.end), ) ) } else -> throw BadRequestException("invalid parameter: $rawParameters") } private fun rangeParameters(v: Map<*, *>): RangeParameters { val source: String = v.stringValue("source") val start: Float = v.floatValue("start") val end: Float = v.floatValue("end") return RangeParameters(source, start, end) } private fun Map<*, *>.floatValue(key: String): Float { if (!containsKey(key)) { throw BadRequestException("missing float parameter '$key'") } return when (val startValue = get(key)) { is Number -> startValue.toFloat() is JsonNumber -> startValue.numberValue().toFloat() else -> throw BadRequestException("parameter '$key' should be a float, but is ${startValue?.javaClass}") } } private fun Map<*, *>.stringValue(key: String): String { if (!containsKey(key)) { throw BadRequestException("missing string parameter '$key'") } return when (val sourceValue = get(key)) { is String -> sourceValue is JsonString -> sourceValue.string else -> throw BadRequestException("parameter '$key' should be a string, but is ${sourceValue?.javaClass}") } } }
18
null
1
8
0eaf7bf4da925385ff52d7e5822a8ce6b83c36b5
6,334
annorepo
Apache License 2.0
src/commonMain/kotlin/com/ashampoo/kim/format/tiff/fieldtype/FieldTypeSRational.kt
Ashampoo
647,186,626
false
{"Kotlin": 954298}
/* * Copyright 2024 Ashampoo GmbH & Co. KG * Copyright 2007-2023 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ashampoo.kim.format.tiff.fieldtype import com.ashampoo.kim.common.ByteOrder import com.ashampoo.kim.common.RationalNumbers import com.ashampoo.kim.common.toBytes import com.ashampoo.kim.common.toRationals import com.ashampoo.kim.format.tiff.constant.TiffConstants /** * Two SLONG’s: the first represents the numerator of a * fraction, the second the denominator. */ object FieldTypeSRational : FieldType<RationalNumbers> { override val type: Int = TiffConstants.FIELD_TYPE_SRATIONAL_INDEX override val name: String = "SRational" override val size: Int = 8 override fun getValue(bytes: ByteArray, byteOrder: ByteOrder): RationalNumbers = bytes.toRationals(byteOrder, unsignedType = false) override fun writeData(data: Any, byteOrder: ByteOrder): ByteArray = (data as RationalNumbers).toBytes(byteOrder) }
8
Kotlin
8
172
5e6cd23c52abf8c840b235eb68744a9ab135c235
1,522
kim
Apache License 2.0
PhoenixPenNG/libgame/src/main/java/com/phoenixpen/game/data/ItemType.kt
nshcat
182,317,693
false
null
package com.phoenixpen.game.data import com.phoenixpen.game.graphics.DrawInfo import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * An enumeration describing all the possible item categories. */ enum class ItemCategory { /** * General item category */ Unspecified } /** * A class describing the properties of an item, using the type class pattern. * * @property identifier Unique identifier of this item type * @property displayName A string used as a name for this item in in-game UI * @property description A short description text describing this type of item * @property category Item category, e.g. food * @property isDrawn Whether the item is drawn when it is outside of an inventory * @property tile Tile draw info representing this item. Only used if [isDrawn] is true.# * @property tileFancy Tile draw info representing this item, for fancy graphics mode */ @Serializable data class ItemType( val identifier: String, @SerialName("display_name") val displayName: String, val description: String = "", val category: ItemCategory = ItemCategory.Unspecified, @SerialName("is_drawn") val isDrawn: Boolean = false, val tile: DrawInfo = DrawInfo(), @SerialName("tile_fancy") val tileFancy: DrawInfo = DrawInfo() ) { companion object { /** * Placeholder type used for missing item types */ val placeholder: ItemType = ItemType( "placeholder", "UNKNOWN ITEM", "Missing item data" ) } }
0
Kotlin
0
1
8e29e78b8f3d1ff7bdfedfd7c872b1ac69dd665d
1,611
phoenixpen_ng
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Script.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Script: ImageVector get() { if (_script != null) { return _script!! } _script = Builder(name = "Script", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(12.0f, 12.0f) horizontalLineToRelative(4.242f) lineToRelative(6.879f, -6.879f) curveToRelative(1.17f, -1.17f, 1.17f, -3.072f, 0.0f, -4.242f) reflectiveCurveToRelative(-3.072f, -1.17f, -4.242f, 0.0f) lineToRelative(-6.879f, 6.879f) verticalLineToRelative(4.242f) close() moveTo(14.0f, 8.586f) lineToRelative(6.293f, -6.293f) curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f) reflectiveCurveToRelative(0.39f, 1.024f, 0.0f, 1.414f) lineToRelative(-6.293f, 6.293f) horizontalLineToRelative(-1.414f) verticalLineToRelative(-1.414f) close() moveTo(20.0f, 17.0f) verticalLineToRelative(-5.93f) lineToRelative(-2.0f, 2.0f) verticalLineToRelative(3.93f) horizontalLineToRelative(-8.0f) verticalLineToRelative(3.5f) curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f) reflectiveCurveToRelative(-1.5f, -0.673f, -1.5f, -1.5f) lineTo(7.0f, 3.5f) curveToRelative(0.0f, -0.539f, -0.133f, -1.044f, -0.351f, -1.5f) horizontalLineToRelative(8.281f) lineTo(16.89f, 0.039f) curveToRelative(-0.13f, -0.015f, -0.257f, -0.039f, -0.39f, -0.039f) lineTo(3.5f, 0.0f) curveTo(1.57f, 0.0f, 0.0f, 1.57f, 0.0f, 3.5f) verticalLineToRelative(3.5f) horizontalLineToRelative(5.0f) verticalLineToRelative(13.5f) curveToRelative(0.0f, 1.93f, 1.57f, 3.5f, 3.5f, 3.5f) horizontalLineToRelative(12.0f) curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f) verticalLineToRelative(-3.5f) horizontalLineToRelative(-4.0f) close() moveTo(5.0f, 5.0f) horizontalLineToRelative(-3.0f) verticalLineToRelative(-1.5f) curveToRelative(0.0f, -0.827f, 0.673f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.673f, 1.5f, 1.5f) verticalLineToRelative(1.5f) close() moveTo(22.0f, 20.5f) curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f) horizontalLineToRelative(-8.838f) curveToRelative(0.217f, -0.455f, 0.338f, -0.964f, 0.338f, -1.5f) verticalLineToRelative(-1.5f) horizontalLineToRelative(10.0f) verticalLineToRelative(1.5f) close() } } .build() return _script!! } private var _script: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,006
icons
MIT License
libs/hops-common-fhir/src/main/kotlin/no/nav/helse/hops/fhir/ResourceExt.kt
ybelMekk
375,614,053
true
{"Gradle Kotlin DSL": 11, "Markdown": 6, "Ignore List": 3, "CODEOWNERS": 1, "Dockerfile": 1, "INI": 3, "Shell": 1, "Batchfile": 1, "YAML": 19, "XML": 16, "Kotlin": 132, "JSON": 24, "Python": 1, "Dotenv": 1, "Java": 19}
package no.nav.helse.hops.fhir import org.hl7.fhir.r4.model.Resource import java.util.UUID /** See https://www.hl7.org/fhir/http.html#versioning **/ fun Resource.weakEtag() = "W/\"${meta?.versionId ?: "0"}\"" /** IdPart as UUID. **/ fun Resource.idAsUUID() = UUID.fromString(idElement.idPart)!!
0
null
0
0
664e2248c97b020370e5c11230c020ddafd2d41d
298
helseopplysninger
MIT License
src/main/kotlin/com/atlassian/performance/tools/jiraactions/api/action/ActionSequence.kt
atlassian
162,422,950
false
{"Kotlin": 214499, "Java": 1959}
package com.atlassian.performance.tools.jiraactions.api.action class ActionSequence( private vararg val actions: Action ) : Action { override fun run() { actions.forEach { it.run() } } } fun Action.then(vararg another: Action) = ActionSequence(this, *another)
8
Kotlin
31
26
10b363eda1e171f8342eaeeb6deac843b1d34df3
283
jira-actions
Apache License 2.0
compiler/testData/ir/irText/lambdas/extensionLambda.kt
JakeWharton
99,388,807
false
null
fun test1() = "42".run { length }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
33
kotlin
Apache License 2.0
godot-kotlin/src/nativeGen/kotlin/godot/VisualShaderNodeTexture.kt
raniejade
166,207,411
false
null
// DO NOT EDIT, THIS FILE IS GENERATED FROM api.json package godot import gdnative.godot_method_bind import gdnative.godot_string import godot.core.Allocator import godot.core.Godot import godot.core.Variant import godot.core.VariantArray import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.reflect.KCallable import kotlinx.cinterop.BooleanVar import kotlinx.cinterop.CFunction import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.COpaquePointerVar import kotlinx.cinterop.CPointer import kotlinx.cinterop.DoubleVar import kotlinx.cinterop.IntVar import kotlinx.cinterop.alloc import kotlinx.cinterop.cstr import kotlinx.cinterop.invoke import kotlinx.cinterop.pointed import kotlinx.cinterop.ptr import kotlinx.cinterop.readValue import kotlinx.cinterop.reinterpret import kotlinx.cinterop.value open class VisualShaderNodeTexture( @Suppress("UNUSED_PARAMETER") __ignore: String? ) : VisualShaderNode(null) { var source: Source get() { return getSource() } set(value) { setSource(value.value) } var texture: Texture get() { return getTexture() } set(value) { setTexture(value) } var textureType: TextureType get() { return getTextureType() } set(value) { setTextureType(value.value) } constructor() : this(null) { if (Godot.shouldInitHandle()) { _handle = __new() } } fun getSource(): Source { val self = this return Allocator.allocationScope { val _ret = alloc<IntVar>() val _retPtr = _ret.ptr __method_bind.getSource.call(self._handle, emptyList(), _retPtr) VisualShaderNodeTexture.Source.from(_ret.value) } } fun getTexture(): Texture { val self = this return Allocator.allocationScope { lateinit var _ret: Texture val _tmp = alloc<COpaquePointerVar>() val _retPtr = _tmp.ptr __method_bind.getTexture.call(self._handle, emptyList(), _retPtr) _ret = objectToType<Texture>(_tmp.value!!) _ret } } fun getTextureType(): TextureType { val self = this return Allocator.allocationScope { val _ret = alloc<IntVar>() val _retPtr = _ret.ptr __method_bind.getTextureType.call(self._handle, emptyList(), _retPtr) VisualShaderNodeTexture.TextureType.from(_ret.value) } } fun setSource(value: Int) { val self = this return Allocator.allocationScope { __method_bind.setSource.call(self._handle, listOf(value), null) } } fun setTexture(value: Texture) { val self = this return Allocator.allocationScope { __method_bind.setTexture.call(self._handle, listOf(value), null) } } fun setTextureType(value: Int) { val self = this return Allocator.allocationScope { __method_bind.setTextureType.call(self._handle, listOf(value), null) } } enum class TextureType( val value: Int ) { TYPE_DATA(0), TYPE_COLOR(1), TYPE_NORMALMAP(2); companion object { fun from(value: Int): TextureType { for (enumValue in values()) { if (enumValue.value == value) { return enumValue } } throw AssertionError("""Unsupported enum value: $value""") } } } enum class Source( val value: Int ) { TEXTURE(0), SCREEN(1), `2D_TEXTURE`(2), `2D_NORMAL`(3), DEPTH(4), PORT(5); companion object { fun from(value: Int): Source { for (enumValue in values()) { if (enumValue.value == value) { return enumValue } } throw AssertionError("""Unsupported enum value: $value""") } } } companion object { internal fun __new(): COpaquePointer = Allocator.allocationScope { val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("VisualShaderNodeTexture".cstr.ptr) requireNotNull(fnPtr) { "No instance found for VisualShaderNodeTexture" } val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>() fn() } /** * Container for method_bind pointers for VisualShaderNodeTexture */ private object __method_bind { val getSource: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "get_source".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_source" } } val getTexture: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "get_texture".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_texture" } } val getTextureType: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "get_texture_type".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method get_texture_type" } } val setSource: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "set_source".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_source" } } val setTexture: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "set_texture".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_texture" } } val setTextureType: CPointer<godot_method_bind> get() = Allocator.allocationScope { val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("VisualShaderNodeTexture".cstr.ptr, "set_texture_type".cstr.ptr) requireNotNull(ptr) { "No method_bind found for method set_texture_type" } }} } }
12
Kotlin
4
51
5c1bb2a1f1d2187375bf50c0445b42c88f37989f
6,307
godot-kotlin
MIT License
src/main/kotlin/dev/kosmx/vikauthfabric/EventHandler.kt
KosmX
840,712,930
false
{"Kotlin": 7270, "Java": 1665}
package dev.kosmx.vikauthfabric import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import com.mojang.authlib.GameProfile import dev.kosmx.vikauth.api.APIData import dev.kosmx.vikauthfabric.api.* import dev.kosmx.vikauthfabric.mixin.ServerLoginHandlerAccessInterface import net.minecraft.network.packet.c2s.login.LoginHelloC2SPacket import net.minecraft.server.MinecraftServer import net.minecraft.server.network.ServerLoginNetworkHandler import net.minecraft.server.network.ServerPlayNetworkHandler import net.minecraft.text.Text import net.minecraft.text.TranslatableText import java.util.concurrent.TimeUnit object AuthEvents { val api: APIData get() = Main.api private val cache: Cache<ServerLoginNetworkHandler, S2CVikAuthPacket> = CacheBuilder.newBuilder() .maximumSize(512) .weakKeys() .expireAfterAccess(20, TimeUnit.SECONDS) .build() @JvmStatic fun ServerLoginNetworkHandler.playerPreJoin(onlineMode: Boolean, helloPacket: LoginHelloC2SPacket): Boolean { return if (onlineMode) { val res = api.fetchOffline(helloPacket.profile.name) if (res.allowed) { cache.put(this, res) this.profile = GameProfile(res.uuid, res.displayName) false } else true } else false } @JvmStatic fun ServerLoginNetworkHandler.playerJoin(original: Text?): Text? { return original ?: let { if (this in cache) { cache.invalidate(this) null } else if (api.fetchOnline(profile!!).allowed) { null } else { TranslatableText("multiplayer.disconnect.not_whitelisted") } } } fun playerLeave(handler: ServerPlayNetworkHandler, minecraft: MinecraftServer) { api.fireLogout(handler.player.gameProfile) } } var ServerLoginNetworkHandler.profile: GameProfile? get() = (this as ServerLoginHandlerAccessInterface).profile set(value) { (this as ServerLoginHandlerAccessInterface).profile = value } private operator fun <K: Any, V> Cache<K, V>.contains(k: K): Boolean = getIfPresent(k) != null
0
Kotlin
0
0
be8e7947eef32c88fb1b1db6b3dca018918e8967
2,246
vikauth-fabric
Creative Commons Zero v1.0 Universal
app/src/main/java/com/ozaltun/marvel/model/comics/ComicsResponse.kt
ReasonablePhantom
625,132,731
false
null
package com.ozaltun.marvel.model.comics data class ComicsResponse( val code: Int, val data: Data, val status: String )
0
Kotlin
0
0
03c6f16ee4cf52c19f1b1291984a87bb7924c5f9
131
MarvelHero
Apache License 2.0
app/src/test/java/com/depoza/util/timeperiod/MonthTimeBoundsCalculatorTest.kt
amagda
135,312,085
false
{"Kotlin": 40877, "Java": 26596}
package com.depoza.util.timeperiod import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import java.util.* import java.util.Calendar.* @TestInstance(PER_CLASS) class MonthTimeBoundsCalculatorTest : BaseTimeBoundsCalculatorTest() { private val calculator = MonthPeriod.MonthTimeBoundsCalculator(timeProvider) private val cal5Apr2018 = Calendar.getInstance().apply { set(DAY_OF_MONTH, 5) set(MONTH, 3) set(YEAR, 2018) set(HOUR_OF_DAY, 13) set(MINUTE, 25) set(SECOND, 50) set(MILLISECOND, 55) } private val cal5Mar2018 = Calendar.getInstance().apply { set(DAY_OF_MONTH, 5) set(MONTH, 2) set(YEAR, 2018) set(HOUR_OF_DAY, 13) set(MINUTE, 25) set(SECOND, 50) set(MILLISECOND, 55) } @ParameterizedTest @CsvSource( "1, 1, 4, 2018, 30, 4, 2018", "2, 2, 4, 2018, 1, 5, 2018", "3, 3, 4, 2018, 2, 5, 2018", "4, 4, 4, 2018, 3, 5, 2018", "5, 5, 4, 2018, 4, 5, 2018", "6, 6, 3, 2018, 5, 4, 2018", "7, 7, 3, 2018, 6, 4, 2018", "8, 8, 3, 2018, 7, 4, 2018", "9, 9, 3, 2018, 8, 4, 2018", "10, 10, 3, 2018, 9, 4, 2018", "11, 11, 3, 2018, 10, 4, 2018", "12, 12, 3, 2018, 11, 4, 2018", "13, 13, 3, 2018, 12, 4, 2018", "14, 14, 3, 2018, 13, 4, 2018", "15, 15, 3, 2018, 14, 4, 2018", "16, 16, 3, 2018, 15, 4, 2018", "17, 17, 3, 2018, 16, 4, 2018", "18, 18, 3, 2018, 17, 4, 2018", "19, 19, 3, 2018, 18, 4, 2018", "20, 20, 3, 2018, 19, 4, 2018", "21, 21, 3, 2018, 20, 4, 2018", "22, 22, 3, 2018, 21, 4, 2018", "23, 23, 3, 2018, 22, 4, 2018", "24, 24, 3, 2018, 23, 4, 2018", "25, 25, 3, 2018, 24, 4, 2018", "26, 26, 3, 2018, 25, 4, 2018", "27, 27, 3, 2018, 26, 4, 2018", "28, 28, 3, 2018, 27, 4, 2018", "29, 29, 3, 2018, 28, 4, 2018", "30, 30, 3, 2018, 29, 4, 2018", "31, 31, 3, 2018, 30, 4, 2018" ) fun curMonth(lowerBound: Int, startDay: Int, startMonth: Int, startYear: Int, endDay: Int, endMonth: Int, endYear: Int) { provideTimeOf(cal5Apr2018) val period = MonthPeriod(lowerBound, 0) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(startDay, startMonth, startYear) .upperBound(endDay, endMonth, endYear) .verify() } @ParameterizedTest @CsvSource( "1, -1, 1, 3, 2018, 31, 3, 2018", "2, -1, 2, 3, 2018, 1, 4, 2018", "3, -1, 3, 3, 2018, 2, 4, 2018", "4, -1, 4, 3, 2018, 3, 4, 2018", "5, -1, 5, 3, 2018, 4, 4, 2018", "6, -1, 6, 2, 2018, 5, 3, 2018", "7, -1, 7, 2, 2018, 6, 3, 2018", "8, -1, 8, 2, 2018, 7, 3, 2018", "9, -1, 9, 2, 2018, 8, 3, 2018", "10, -1, 10, 2, 2018, 9, 3, 2018", "11, -2, 11, 1, 2018, 10, 2, 2018", "12, -2, 12, 1, 2018, 11, 2, 2018", "13, -2, 13, 1, 2018, 12, 2, 2018", "14, -2, 14, 1, 2018, 13, 2, 2018", "15, -2, 15, 1, 2018, 14, 2, 2018", "16, -2, 16, 1, 2018, 15, 2, 2018", "17, -2, 17, 1, 2018, 16, 2, 2018", "18, -2, 18, 1, 2018, 17, 2, 2018", "19, -2, 19, 1, 2018, 18, 2, 2018", "20, -2, 20, 1, 2018, 19, 2, 2018", "21, -3, 21, 12, 2017, 20, 1, 2018", "22, -3, 22, 12, 2017, 21, 1, 2018", "23, -3, 23, 12, 2017, 22, 1, 2018", "24, -3, 24, 12, 2017, 23, 1, 2018", "25, -3, 25, 12, 2017, 24, 1, 2018", "26, -3, 26, 12, 2017, 25, 1, 2018", "27, -3, 27, 12, 2017, 26, 1, 2018", "28, -3, 28, 12, 2017, 27, 1, 2018", "29, -3, 29, 12, 2017, 28, 1, 2018", "30, -3, 30, 12, 2017, 29, 1, 2018", "31, -4, 30, 11, 2017, 29, 12, 2017" ) fun prevMonth(lowerBound: Int, quantity: Int, startDay: Int, startMonth: Int, startYear: Int, endDay: Int, endMonth: Int, endYear: Int) { provideTimeOf(cal5Apr2018) val period = MonthPeriod(lowerBound, quantity) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(startDay, startMonth, startYear) .upperBound(endDay, endMonth, endYear) .verify() } @ParameterizedTest @CsvSource( "1, 1, 1, 5, 2018, 31, 5, 2018", "2, 1, 2, 5, 2018, 1, 6, 2018", "3, 1, 3, 5, 2018, 2, 6, 2018", "4, 1, 4, 5, 2018, 3, 6, 2018", "5, 1, 5, 5, 2018, 4, 6, 2018", "6, 1, 6, 4, 2018, 5, 5, 2018", "7, 1, 7, 4, 2018, 6, 5, 2018", "8, 1, 8, 4, 2018, 7, 5, 2018", "9, 1, 9, 4, 2018, 8, 5, 2018", "10, 1, 10, 4, 2018, 9, 5, 2018", "11, 2, 11, 5, 2018, 10, 6, 2018", "12, 2, 12, 5, 2018, 11, 6, 2018", "13, 2, 13, 5, 2018, 12, 6, 2018", "14, 2, 14, 5, 2018, 13, 6, 2018", "15, 2, 15, 5, 2018, 14, 6, 2018", "16, 2, 16, 5, 2018, 15, 6, 2018", "17, 2, 17, 5, 2018, 16, 6, 2018", "18, 2, 18, 5, 2018, 17, 6, 2018", "19, 2, 19, 5, 2018, 18, 6, 2018", "20, 2, 20, 5, 2018, 19, 6, 2018", "21, 3, 21, 6, 2018, 20, 7, 2018", "22, 3, 22, 6, 2018, 21, 7, 2018", "23, 3, 23, 6, 2018, 22, 7, 2018", "24, 3, 24, 6, 2018, 23, 7, 2018", "25, 3, 25, 6, 2018, 24, 7, 2018", "26, 3, 26, 6, 2018, 25, 7, 2018", "27, 3, 27, 6, 2018, 26, 7, 2018", "28, 3, 28, 6, 2018, 27, 7, 2018", "29, 3, 29, 6, 2018, 28, 7, 2018", "30, 3, 30, 6, 2018, 29, 7, 2018", "31, 4, 31, 7, 2018, 30, 8, 2018" ) fun nextMonth(lowerBound: Int, quantity: Int, startDay: Int, startMonth: Int, startYear: Int, endDay: Int, endMonth: Int, endYear: Int) { provideTimeOf(cal5Apr2018) val period = MonthPeriod(lowerBound, quantity) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(startDay, startMonth, startYear) .upperBound(endDay, endMonth, endYear) .verify() } @Test fun curPeriod_LowerBound31_Now5Mar() { provideTimeOf(cal5Mar2018) val period = MonthPeriod(31, 0) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(28, 2, 2018) .upperBound(27, 3, 2018) .verify() } @Test fun prevPeriod_LowerBound31_Now5Mar() { provideTimeOf(cal5Mar2018) val period = MonthPeriod(31, -1) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(31, 1, 2018) .upperBound(28, 2, 2018) .verify() } @Test fun nextPeriod_LowerBound31_Now5Mar() { provideTimeOf(cal5Mar2018) val period = MonthPeriod(31, 1) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(31, 3, 2018) .upperBound(30, 4, 2018) .verify() } @Test fun prev30Days_Now1Mar() { val cal = Calendar.getInstance().apply { set(DAY_OF_MONTH, 1) set(MONTH, 2) set(YEAR, 2018) set(HOUR_OF_DAY, 13) set(MINUTE, 25) set(SECOND, 50) set(MILLISECOND, 55) } provideTimeOf(cal) val period = MonthPeriod(0, -1) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(30, 1, 2018) .upperBound(28, 2, 2018) .verify() } @Test fun prev30Days_Now5Mar() { provideTimeOf(cal5Mar2018) val period = MonthPeriod(0, -1) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(3, 2, 2018) .upperBound(4, 3, 2018) .verify() } @Test fun prev30Days_Now31Mar() { val cal = Calendar.getInstance().apply { set(DAY_OF_MONTH, 31) set(MONTH, 2) set(YEAR, 2018) set(HOUR_OF_DAY, 13) set(MINUTE, 25) set(SECOND, 50) set(MILLISECOND, 55) } provideTimeOf(cal) val period = MonthPeriod(0, -1) val timeBounds = calculator.calculateFor(period) PeriodTimeBoundsVerifier(timeBounds) .lowerBound(1, 3, 2018) .upperBound(30, 3, 2018) .verify() } }
1
Kotlin
1
7
8393962011bec931e5db446c438376aa2a06b7e0
9,458
TimePeriod
MIT License
s2-test/s2-test-bdd/src/main/kotlin/s2/bdd/assertion/AssertionApplicationEvents.kt
komune-io
746,796,094
false
{"Kotlin": 123095, "Makefile": 4208, "JavaScript": 1453, "Dockerfile": 963, "CSS": 102}
package s2.bdd.assertion import org.assertj.core.api.Assertions import s2.bdd.data.TestContext import kotlin.reflect.KClass fun AssertionBdd.events(testContext: TestContext) = AssertionApplicationEvents(testContext) class AssertionApplicationEvents( private val context: TestContext ) { fun <Event: Any> assertThat(eventClass: KClass<Event>) = ApplicationEventAssert(eventClass) inner class ApplicationEventAssert<Event: Any>( eventClass: KClass<Event> ) { private val events = context.events.filterIsInstance(eventClass.java) fun hasNotBeenSent(matcher: (Event) -> Boolean = { true }) { hasBeenSent(0, matcher) } fun hasBeenSent(times: Int = 1, matcher: (Event) -> Boolean = { true }) { matching(matcher).hasSize(times) } fun hasBeenSentAtLeast(times: Int, matcher: (Event) -> Boolean = { true }) { matching(matcher).hasSizeGreaterThanOrEqualTo(times) } fun hasBeenSentAtMost(times: Int, matcher: (Event) -> Boolean = { true }) { matching(matcher).hasSizeLessThanOrEqualTo(times) } fun matching(matcher: (Event) -> Boolean) = Assertions.assertThat(events.filter(matcher)) } }
0
Kotlin
0
0
14e94bb751f68efe2cd487f877bda881a7a0509f
1,243
fixers-s2
Apache License 2.0
app/src/main/java/com/cuetmart/user/SplashScreen.kt
raykibul
440,553,003
false
{"Kotlin": 36207, "Java": 15832}
package com.cuetmart.user import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.view.Window import android.view.WindowManager class SplashScreen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_splash_screen) var handler = Handler() handler.postDelayed(kotlinx.coroutines.Runnable { startActivity(Intent(this, MainActivity::class.java)) finish() },3000) } }
0
Kotlin
0
1
3434ad33f7e0dc9f6724aad858326ba56a3ddf53
809
CUETmart
MIT License
src/main/kotlin/com/example/numbletimedealserver/domain/Customer.kt
inudev5
608,232,045
false
null
package com.example.numbletimedealserver.domain import com.fasterxml.jackson.annotation.JsonManagedReference import jakarta.persistence.CascadeType import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.OneToMany import org.hibernate.annotations.BatchSize @Entity class Customer ( name:String, @Column var password:String, @Column(nullable = false) val role:ROLE, @JsonManagedReference @OneToMany(mappedBy = "customer") @BatchSize(size = 100) private val _orders:MutableList<Order> = mutableListOf(), ):PrimaryKeyEntity(){ @Column(nullable = false) var name:String = name protected set val orders:List<Order> get() = _orders }
0
Kotlin
0
1
188440f6f79c75ea066b22ad5b19dff51837559d
725
NumbleTimeDealServer
MIT License
app/src/main/java/com/vitorpamplona/amethyst/ui/actions/ImageSaver.kt
vitorpamplona
587,850,619
false
null
/** * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.vitorpamplona.amethyst.ui.actions import android.content.ContentResolver import android.content.ContentValues import android.content.Context import android.media.MediaScannerConnection import android.os.Build import android.os.Environment import android.provider.MediaStore import android.webkit.MimeTypeMap import androidx.annotation.RequiresApi import com.vitorpamplona.amethyst.BuildConfig import com.vitorpamplona.amethyst.service.HttpClient import okhttp3.Call import okhttp3.Callback import okhttp3.Request import okhttp3.Response import okio.BufferedSource import okio.IOException import okio.buffer import okio.sink import okio.source import java.io.File import java.util.UUID object ImageSaver { /** * Saves the image to the gallery. May require a storage permission. * * @see PICTURES_SUBDIRECTORY */ fun saveImage( url: String, context: Context, onSuccess: () -> Any?, onError: (Throwable) -> Any?, ) { val client = HttpClient.getHttpClient() val request = Request.Builder() .header("User-Agent", "Amethyst/${BuildConfig.VERSION_NAME}") .get() .url(url) .build() client .newCall(request) .enqueue( object : Callback { override fun onFailure( call: Call, e: IOException, ) { e.printStackTrace() onError(e) } override fun onResponse( call: Call, response: Response, ) { try { check(response.isSuccessful) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val contentType = response.header("Content-Type") checkNotNull(contentType) { "Can't find out the content type" } saveContentQ( displayName = File(url).nameWithoutExtension, contentType = contentType, contentSource = response.body.source(), contentResolver = context.contentResolver, ) } else { saveContentDefault( fileName = File(url).name, contentSource = response.body.source(), context = context, ) } onSuccess() } catch (e: Exception) { e.printStackTrace() onError(e) } } }, ) } fun saveImage( localFile: File, mimeType: String?, context: Context, onSuccess: () -> Any?, onError: (Throwable) -> Any?, ) { try { val extension = mimeType?.let { MimeTypeMap.getSingleton().getExtensionFromMimeType(it) } ?: "" val buffer = localFile.inputStream().source().buffer() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { saveContentQ( displayName = UUID.randomUUID().toString(), contentType = mimeType ?: "", contentSource = buffer, contentResolver = context.contentResolver, ) } else { saveContentDefault( fileName = UUID.randomUUID().toString() + ".$extension", contentSource = buffer, context = context, ) } onSuccess() } catch (e: Exception) { e.printStackTrace() onError(e) } } @RequiresApi(Build.VERSION_CODES.Q) private fun saveContentQ( displayName: String, contentType: String, contentSource: BufferedSource, contentResolver: ContentResolver, ) { val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, displayName) put(MediaStore.MediaColumns.MIME_TYPE, contentType) put( MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separatorChar + PICTURES_SUBDIRECTORY, ) } val masterUri = if (contentType.startsWith("image")) { MediaStore.Images.Media.EXTERNAL_CONTENT_URI } else { MediaStore.Video.Media.EXTERNAL_CONTENT_URI } val uri = contentResolver.insert(masterUri, contentValues) checkNotNull(uri) { "Can't insert the new content" } try { val outputStream = contentResolver.openOutputStream(uri) checkNotNull(outputStream) { "Can't open the content output stream" } outputStream.use { contentSource.readAll(it.sink()) } } catch (e: Exception) { contentResolver.delete(uri, null, null) throw e } } private fun saveContentDefault( fileName: String, contentSource: BufferedSource, context: Context, ) { val subdirectory = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), PICTURES_SUBDIRECTORY, ) if (!subdirectory.exists()) { subdirectory.mkdirs() } val outputFile = File(subdirectory, fileName) outputFile.outputStream().use { contentSource.readAll(it.sink()) } // Call the media scanner manually, so the image // appears in the gallery faster. MediaScannerConnection.scanFile(context, arrayOf(outputFile.toString()), null, null) } private const val PICTURES_SUBDIRECTORY = "Amethyst" }
5
null
3
995
0bb39f91b9dddf81dcec63f3d97674f26872fbd0
7,432
amethyst
MIT License
core/src/main/kotlin/no/nav/amt/tiltak/core/domain/arrangor/TilknyttetArrangor.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.core.domain.arrangor import java.util.* data class TilknyttetArrangor( val id: UUID, val navn: String, val organisasjonsnummer: String, val overordnetEnhetOrganisasjonsnummer: String?, val overordnetEnhetNavn: String?, val roller: List<String> )
2
Kotlin
3
3
59ebfd42eb4b8bcea2350e501058584fb80287b9
280
amt-tiltak
MIT License
node-api/src/main/kotlin/net/corda/nodeapi/exceptions/OutdatedNetworkParameterHashException.kt
roastario
132,010,309
true
{"Gradle": 49, "INI": 27, "Markdown": 56, "Shell": 12, "Text": 12, "Ignore List": 4, "Batchfile": 4, "XML": 48, "Java": 84, "Kotlin": 1164, "Java Properties": 2, "Gherkin": 3, "Groovy": 2, "RPM Spec": 1, "CSS": 10, "SVG": 5, "PowerShell": 1, "JSON": 3, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "Makefile": 1, "reStructuredText": 114, "Python": 1, "Graphviz (DOT)": 1, "TeX": 5, "BibTeX": 1}
package net.corda.nodeapi.exceptions import net.corda.core.CordaRuntimeException import net.corda.core.crypto.SecureHash class OutdatedNetworkParameterHashException(old: SecureHash, new: SecureHash) : CordaRuntimeException(TEMPLATE.format(old, new)), RpcSerializableError { private companion object { private const val TEMPLATE = "Refused to accept parameters with hash %s because network map advertises update with hash %s. Please check newest version" } }
0
Kotlin
0
0
db22c5259db30496b930a9112b5055f9837b94a1
476
corda
Apache License 2.0
app/src/main/java/com/revolgenx/anilib/staff/data/constant/StaffMediaRoleSort.kt
AniLibApp
244,410,204
false
{"Kotlin": 1593083, "Shell": 52}
package com.revolgenx.anilib.staff.data.constant enum class StaffMediaCharacterSort { POPULARITY_DESC, SCORE_DESC, FAVOURITES_DESC, START_DATE_DESC, START_DATE, TITLE_ROMAJI, CHARACTER_SORT }
36
Kotlin
3
76
b3caec5c00779c878e4cf22fb7d2034aefbeee54
220
AniLib
Apache License 2.0
src/main/kotlin/com/moneysearch/services/UserService.kt
glebArkhipov
467,516,649
false
null
package com.moneysearch.services import com.moneysearch.repositories.Currency import com.moneysearch.repositories.Location import com.moneysearch.repositories.SearchArea import com.moneysearch.repositories.SearchAreaType import com.moneysearch.repositories.SearchAreaType.CUSTOM import com.moneysearch.repositories.User import com.moneysearch.repositories.UserRepository import com.moneysearch.services.dialogstate.DialogState import org.springframework.stereotype.Component @Component class UserService( private val userRepository: UserRepository ) { fun findUserByTelegramId(telegramId: Long): User = userRepository.findUserByTelegramId(telegramId) fun setPredefinedSearchArea(user: User, searchAreaType: SearchAreaType) { user.searchArea = SearchArea(searchAreaType) userRepository.save(user) } fun setCustomLocation(user: User, location: Location) { user.searchArea = SearchArea( type = CUSTOM, location = location, distanceFromLocation = user.searchArea.distanceFromLocation ) userRepository.save(user) } fun setDistanceFromLocation(user: User, distance: Long) { user.searchArea = SearchArea( type = user.searchArea.type, location = user.searchArea.location, distanceFromLocation = distance ) userRepository.save(user) } fun setDialogState(user: User, dialogState: DialogState) { user.dialogState = dialogState userRepository.save(user) } fun setCurrencies(user: User, currencies: Set<Currency>) { user.currencies = currencies userRepository.save(user) } fun removeCurrency(user: User, currency: Currency) { val currentCurrencies = user.currencies val newCurrencies = currentCurrencies.minus(currency) setCurrencies(user, newCurrencies) } fun addCurrency(user: User, currency: Currency) { val currentCurrencies = user.currencies val newCurrencies = currentCurrencies.plus(currency) setCurrencies(user, newCurrencies) } fun turnNotificationOn(user: User) { user.notificationsTurnOn = true userRepository.save(user) } fun turnNotificationOff(user: User) { user.notificationsTurnOn = false userRepository.save(user) } }
0
Kotlin
0
0
17513bf63dec3f111617dd809d9c95e57353ab95
2,362
moneysearch
MIT License
server/src/main/kotlin/org/kryptonmc/krypton/server/StatisticsSerializer.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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 org.kryptonmc.krypton.server import ca.spottedleaf.dataconverter.minecraft.datatypes.MCTypeRegistry import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.internal.Streams import com.google.gson.stream.JsonReader import net.kyori.adventure.key.InvalidKeyException import net.kyori.adventure.key.Key import org.apache.logging.log4j.LogManager import org.kryptonmc.api.registry.Registry import org.kryptonmc.api.statistic.Statistic import org.kryptonmc.api.statistic.StatisticType import org.kryptonmc.krypton.KryptonPlatform import org.kryptonmc.krypton.entity.player.KryptonPlayer import org.kryptonmc.krypton.registry.KryptonRegistries import org.kryptonmc.krypton.util.DataConversion import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption class StatisticsSerializer(private val folder: Path) { fun loadAll(player: KryptonPlayer) { val file = folder.resolve("${player.uuid}.json") loadAllInFile(player, file) } private fun loadAllInFile(player: KryptonPlayer, file: Path) { if (!Files.isRegularFile(file)) return val reader = Files.newInputStream(file, StandardOpenOption.READ).reader() try { val json = JsonReader(reader).apply { isLenient = false }.use(Streams::parse) if (json.isJsonNull) { LOGGER.error("Unable to parse statistics data from $file to JSON!") return } json as JsonObject if (!json.has(DATA_VERSION_KEY) || !json.get(DATA_VERSION_KEY).isJsonPrimitive) { json.addProperty(DATA_VERSION_KEY, OLD_VERSION) } val version = json.get(DATA_VERSION_KEY).asInt val data = if (version < KryptonPlatform.worldVersion) { DataConversion.upgrade(json, MCTypeRegistry.STATS, json.get("DataVersion").asInt) } else { json } if (data.get(STATS_KEY).asJsonObject.size() == 0) return val stats = data.get(STATS_KEY)?.asJsonObject ?: JsonObject() loadStatistics(player, file, stats) } catch (exception: IOException) { LOGGER.error("Failed to load statistics data from $file!", exception) } catch (exception: JsonParseException) { LOGGER.error("Failed to parse statistics data from $file to JSON!", exception) } } private fun loadStatistics(player: KryptonPlayer, file: Path, stats: JsonObject) { stats.keySet().forEach { key -> if (!stats.get(key).isJsonObject) return@forEach val type = KryptonRegistries.STATISTIC_TYPE.get(Key.key(key)) if (type == null) { LOGGER.warn("Invalid statistic type found in $file! Could not recognise $key!") return@forEach } val values = stats.get(key).asJsonObject values.keySet().forEach { valueKey -> loadStatisticValue(player, file, values, valueKey, type) } } } private fun loadStatisticValue(player: KryptonPlayer, file: Path, values: JsonObject, valueKey: String, type: StatisticType<*>) { val value = values.get(valueKey) if (!value.isJsonPrimitive) { LOGGER.warn("Invalid statistic found in $file! Could not recognise value ${values.get(valueKey)} for key $valueKey") return } val statistic = getStatistic(type, valueKey) if (statistic != null) { player.statisticsTracker.statistics.put(statistic, value.asInt) } else { LOGGER.warn("Invalid statistic found in $file! Could not recognise key $valueKey!") } } @Suppress("UNCHECKED_CAST") fun saveAll(player: KryptonPlayer) { val tracker = player.statisticsTracker val file = folder.resolve("${player.uuid}.json") try { val map = HashMap<StatisticType<*>, JsonObject>() tracker.statistics.object2IntEntrySet().forEach { val registry = it.key.type.registry as Registry<Any> map.computeIfAbsent(it.key.type) { JsonObject() }.addProperty(registry.getKey(it.key.value!!)!!.toString(), it.intValue) } val statsJson = JsonObject() map.forEach { statsJson.add(it.key.key().asString(), it.value) } val json = JsonObject().apply { add(STATS_KEY, statsJson) addProperty(DATA_VERSION_KEY, KryptonPlatform.worldVersion) }.toString() Files.newOutputStream(file).writer().use { it.write(json) } } catch (exception: IOException) { LOGGER.error("Failed to save statistics file $file!", exception) } } companion object { private val LOGGER = LogManager.getLogger() private const val OLD_VERSION = 1343 private const val STATS_KEY = "stats" private const val DATA_VERSION_KEY = "DataVersion" @JvmStatic private fun <T> getStatistic(type: StatisticType<T>, name: String): Statistic<T>? { val key = try { Key.key(name) } catch (_: InvalidKeyException) { return null } return type.registry.get(key)?.let(type::getStatistic) } } }
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
6,109
Krypton
Apache License 2.0
LogTool/src/main/java/me/ghost233/logtool/logtoolconfig/LogToolConfigFile.kt
Ghost233
762,079,603
false
{"Kotlin": 38402, "C++": 25825, "CMake": 1342}
package me.ghost233.logtool.logtoolconfig import me.ghost233.logtool.logtoolhandleinterface.LogToolHandleFileHandle import me.ghost233.logtool.logtoolhandleinterface.LogToolHandleInterface class LogToolConfigFile : LogToolConfigInterface() { var priority: Long = 0L var dirPath: String = "" var subDirPath: String = "" var filenamePrefix: String = "" var filenameSuffix: String = "" var fileMaxSize: Long = 0L var fileTimeIntervalWithSecond: Long = 0L ////定义一个block类型获取最新的文件名 //typedef void(^GetNowFilenameBlock)(NSString* _Nonnull); // @property(nonatomic, copy) GetNowFilenameBlock nowFilenameBlock; var nowFilenameBlock: ((String) -> Unit)? = null init { synchronized(handleLock) { handle = LogToolHandleFileHandle() } } override var handle: LogToolHandleInterface get() { if (!field.isInit) { field.initWithConfig(this) field.repairAllMMAP() } return field } override fun getLogToolConfigEnum(): LogToolConfigEnum { return LogToolConfigEnum.LogToolConfigEnumFile } }
0
Kotlin
0
0
3b8428326a6d4b1657291ab73884ae08a8161661
1,161
GhostTaskRemind
MIT License
app/src/main/java/com/papermoon/spaceapp/features/eventOverview/vm/EventOverviewViewModel.kt
papermoon-ai
583,742,280
false
{"Kotlin": 197546}
package com.papermoon.spaceapp.features.eventOverview.vm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.papermoon.spaceapp.domain.model.event.Event import com.papermoon.spaceapp.domain.resource.doOnSuccess import com.papermoon.spaceapp.domain.usecase.event.GetUpcomingEventsFromLocalUseCase import com.papermoon.spaceapp.domain.usecase.event.GetUpcomingEventsFromNetworkUseCase import com.papermoon.spaceapp.domain.usecase.event.SaveUpcomingEventsToLocalUseCase import kotlinx.coroutines.launch class EventOverviewViewModel( private val getUpcomingEventsFromNetworkUseCase: GetUpcomingEventsFromNetworkUseCase, private val getUpcomingEventsFromLocalUseCase: GetUpcomingEventsFromLocalUseCase, private val saveUpcomingEventsToLocalUseCase: SaveUpcomingEventsToLocalUseCase ) : ViewModel() { private val _upcomingEvents = MutableLiveData<List<Event>>() val upcomingEvents: LiveData<List<Event>> get() = _upcomingEvents private val _showUnableToUpdateMessage = MutableLiveData(false) val showUnableToLoadEventsMessage: LiveData<Boolean> get() = _showUnableToUpdateMessage private val _showShimmer = MutableLiveData(false) val showShimmer: LiveData<Boolean> get() = _showShimmer init { updateUpcomingEvents() } fun updateUpcomingEvents() { _showShimmer.value = true viewModelScope.launch { updateEventsFromNetwork() _upcomingEvents.value ?: updateEventsFromLocal() if (_upcomingEvents.value == null || _upcomingEvents.value!!.isEmpty()) { _showUnableToUpdateMessage.value = true } } } private suspend fun updateEventsFromNetwork() { val result = getUpcomingEventsFromNetworkUseCase.execute(Unit) result.doOnSuccess { _upcomingEvents.value = result.data saveEventsToLocal() } } private suspend fun updateEventsFromLocal() { val result = getUpcomingEventsFromLocalUseCase.execute(Unit) result.doOnSuccess { _upcomingEvents.value = result.data } } private suspend fun saveEventsToLocal() { saveUpcomingEventsToLocalUseCase.execute(_upcomingEvents.value!!) } fun doneLoadingMessage() { _showShimmer.value = false } fun doneUnableToLoadMessage() { _showUnableToUpdateMessage.value = false } }
0
Kotlin
0
0
a0a4eb6bef933f910ef049b549a7200258b1c4d7
2,535
SpaceExplorer
MIT License
app/src/main/java/com/example/appstore/ui/shipping/adapters/AddressesAdapter.kt
rezakardan
779,591,568
false
{"Kotlin": 353707, "Java": 16027}
package com.example.appstore.ui.shipping.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.example.appstore.data.model.shipping.ResponseShippingList import com.example.appstore.databinding.ItemAddressesDialogBinding import com.example.appstore.databinding.ItemShippingProductBinding import com.example.appstore.utils.BASE_URL_IMAGE import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject class AddressesAdapter @Inject constructor(@ApplicationContext private val context: Context) : RecyclerView.Adapter<AddressesAdapter.ImagesViewHolder>() { lateinit var binding: ItemAddressesDialogBinding private var imagesList = emptyList<ResponseShippingList.Addresse>() inner class ImagesViewHolder(item: View) : RecyclerView.ViewHolder(item) { fun onBind(oneItem:ResponseShippingList.Addresse){ binding.itemNameTxt.text="${oneItem.receiverFirstname} ${oneItem.receiverLastname}" binding.itemAddressTxt.text=oneItem.postalAddress binding.root.setOnClickListener { addressesListener?.let { it(oneItem) } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImagesViewHolder { binding = ItemAddressesDialogBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ImagesViewHolder(binding.root) } override fun onBindViewHolder(holder: ImagesViewHolder, position: Int) { holder.onBind(imagesList[position]) } override fun getItemCount()=imagesList.size override fun getItemId(position: Int) = position.toLong() override fun getItemViewType(position: Int) = position private var addressesListener:((ResponseShippingList.Addresse)->Unit)?=null fun onAddressesClickListener(listener:(ResponseShippingList.Addresse)->Unit){ addressesListener=listener } fun setData(data:List<ResponseShippingList.Addresse>){ val diff= ImagesDiffUtils(imagesList,data) val diffU=DiffUtil.calculateDiff(diff) imagesList=data diffU.dispatchUpdatesTo(this) } class ImagesDiffUtils(private val oldItem: List<ResponseShippingList.Addresse>, private val newItem: List<ResponseShippingList.Addresse>) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldItem.size } override fun getNewListSize(): Int { return newItem.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItem[oldItemPosition] === newItem[newItemPosition] } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldItem[oldItemPosition] === newItem[newItemPosition] } } }
0
Kotlin
0
0
c64368f08faae5b50d158dadb79a8a1a3cd3e140
3,076
AppStore__Git
MIT License
app/src/main/java/com/flowfoundation/wallet/page/token/detail/model/TokenDetailChartModel.kt
Outblock
692,942,645
false
{"Kotlin": 1847105, "Java": 104150}
package com.flowfoundation.wallet.page.token.detail.model import com.flowfoundation.wallet.network.model.CryptowatchSummaryData import com.flowfoundation.wallet.page.token.detail.Quote class TokenDetailChartModel( val chartData: List<Quote>? = null, val summary: CryptowatchSummaryData.Result? = null, )
93
Kotlin
3
0
6ecc281292b80741d976c738b67da0c3384323c7
313
FRW-Android
Apache License 2.0
.teamcity/patches/templates/ReactUI_GitHubFeatures.kts
skbkontur
71,260,457
false
null
package patches.templates import jetbrains.buildServer.configs.kotlin.v2019_2.* import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.CommitStatusPublisher import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.PullRequests import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.commitStatusPublisher import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.pullRequests import jetbrains.buildServer.configs.kotlin.v2019_2.ui.* /* This patch script was generated by TeamCity on settings change in UI. To apply the patch, change the template with id = 'ReactUI_GitHubFeatures' accordingly, and delete the patch script. */ changeTemplate(RelativeId("ReactUI_GitHubFeatures")) { features { val feature1 = find<PullRequests> { pullRequests { id = "PULL_REQUESTS" provider = github { serverUrl = "" authType = token { token = "credentialsJSON:37119025-2749-4abf-8ed8-ff4221b59d50" } filterAuthorRole = PullRequests.GitHubRoleFilter.MEMBER_OR_COLLABORATOR } } } feature1.apply { provider = github { serverUrl = "" authType = token { token = "credentialsJSON:7fd959b6-0b07-4bf1-87d0-1ce9c443528e" } filterSourceBranch = "" filterTargetBranch = "" filterAuthorRole = PullRequests.GitHubRoleFilter.MEMBER_OR_COLLABORATOR } } val feature2 = find<CommitStatusPublisher> { commitStatusPublisher { id = "COMMIT_STATUS_PUBLISHER" publisher = github { githubUrl = "https://api.github.com" authType = personalToken { token = "credentialsJSON:753f3391-1e06-4223-8a34-70a7c9adb2af" } } } } feature2.apply { publisher = github { githubUrl = "https://api.github.com" authType = personalToken { token = "credentialsJSON:7fd959b6-0b07-4bf1-87d0-1ce9c443528e" } } } } }
191
TypeScript
105
199
5a0babee422904a08d5f01ebac52689203b39211
2,328
retail-ui
MIT License
tangem-sdk-core/src/main/java/com/tangem/crypto/hdWallet/masterkey/MaserKeyFactory.kt
tangem
218,994,149
false
{"Kotlin": 1222315, "Java": 13485, "Ruby": 911}
package com.tangem.crypto.hdWallet.masterkey import com.tangem.crypto.hdWallet.bip32.ExtendedPrivateKey interface MaserKeyFactory { fun makePrivateKey(): ExtendedPrivateKey }
4
Kotlin
38
64
2ea3795fd521f23ecc6414913ab5d207c256fe84
181
tangem-sdk-android
MIT License
code/PPPShared/src/commonMain/kotlin/view/CreateAccountView.kt
cybernetics
205,762,814
true
{"Kotlin": 152831, "Swift": 46332, "Shell": 501, "Dockerfile": 496}
package no.bakkenbaeck.pppshared.view import no.bakkenbaeck.pppshared.interfaces.IndefiniteLoadingIndicating /** * Interface to be implemented per platform. */ interface CreateAccountView: IndefiniteLoadingIndicating { /// The text the user has input as their email address. var email: String? /// The text the user has input as their password. var password: String? /// The confirmed password for the user (which should match `password`). var confirmPassword: String? fun emailErrorUpdated(toString: String?) fun passwordErrorUpdated(toString: String?) fun confirmPasswordErrorUpdated(toString: String?) fun apiErrorUpdated(toString: String?) fun setSubmitButtonEnabled(enabled: Boolean) /// Called when an account has been successfully created. fun accountSuccessfullyCreated() }
0
Kotlin
0
0
87372a86f95c3a53526d128f8395e8db662c6957
843
PorchPirateProtector
MIT License
remote/src/main/java/sk/kasper/remote/entity/RemoteLaunchSite.kt
ValterKasper
253,570,488
false
{"Kotlin": 293041, "Shell": 251}
package sk.kasper.remote.entity data class RemoteLaunchSite( val id: Long, val siteName: String, val padName: String?, val infoURL: String?, val latitude: Double, val longitude: Double )
1
Kotlin
17
152
4d4c6dda324393222434881d064cd6bbf1bbf622
211
space-app
Apache License 2.0
app/src/main/java/com/yugyd/idiomatic/android/gradle/domain/sample40/Sample40UseCase.kt
Yugyd
686,269,894
false
{"Kotlin": 313957, "Shell": 2314}
package com.yugyd.idiomatic.android.gradle.domain.sample40 import com.yugyd.idiomatic.android.gradle.data.sample40.Sample40Repository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOn class Sample40UseCase( private val sample40Repository: Sample40Repository, ) { operator fun invoke(): Flow<String> { return sample40Repository .getData() .flowOn(Dispatchers.IO) } }
0
Kotlin
1
2
9d5b99856a9e0cf3bbc7c40676725113236d73ac
475
idiomatic-android-gradle
Apache License 2.0
project/kimmer/src/main/kotlin/org/babyfish/kimmer/graphql/Connection.kt
babyfish-ct
447,936,858
false
null
package org.babyfish.kimmer.graphql import org.babyfish.kimmer.Immutable interface Connection<N>: Immutable { val totalCount: Int val edges: List<Edge<N>> val pageInfo: PageInfo interface Edge<N>: Immutable { val node: N val cursor: String } interface PageInfo: Immutable { val hasNextPage: Boolean val hasPreviousPage: Boolean val startCursor: String val endCursor: String } }
0
Kotlin
0
25
fe1b92b7fb5c3ac27557a8de4368cbef698f3fac
460
kimmer
MIT License
app/src/main/java/com/collection/dynamicwallpapers/GridRVAdapter.kt
rohandesilva8
749,109,614
false
{"Kotlin": 33943}
package com.collection.dynamicwallpapers import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import coil.load internal class GridRVAdapter( private var courseList: List<GridViewModal>, private val context: Context ) : BaseAdapter() { private var layoutInflater: LayoutInflater? = null override fun getCount(): Int { return courseList.size } override fun getItem(position: Int): Any? { return null } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var convertView = convertView if (layoutInflater == null) { layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } if (convertView == null) { convertView = layoutInflater!!.inflate(R.layout.gridview_item, null) } val courseIV: ImageView = convertView!!.findViewById(R.id.idIVCourse) courseIV.load(courseList[position].imageUrl) { crossfade(1000) // Enable crossfade animation placeholder(R.drawable.loading_indicator) // Set the placeholder image } return convertView } // Method to update the data in the adapter fun updateData(newData: List<GridViewModal>) { courseList = newData notifyDataSetChanged() } }
0
Kotlin
0
0
b09def6c09c14d97c6d14362c42df0b53bb446da
1,552
Wallpaper-App-Kotlin
MIT License
data/src/main/java/org/buffer/android/boilerplate/data/mapper/ArticleMapper.kt
mochadwi
221,054,893
true
{"Kotlin": 127635}
package org.buffer.android.boilerplate.data.mapper import org.buffer.android.boilerplate.data.model.ArticleEntity import org.buffer.android.boilerplate.data.model.BufferooEntity import org.buffer.android.boilerplate.domain.model.Article import org.buffer.android.boilerplate.domain.model.Bufferoo import javax.inject.Inject open class ArticleMapper @Inject constructor() : Mapper<ArticleEntity, Article> { /** * Map a [BufferooEntity] instance to a [Bufferoo] instance */ override fun mapFromEntity(article: ArticleEntity): Article { return Article(Article.Source(article.source.id, article.source.name), article.author, article.title, article.description, article.url, article.urlToImage, article.publishedAt, article.content) } /** * Map a [Bufferoo] instance to a [BufferooEntity] instance */ override fun mapToEntity(article: Article): ArticleEntity { return ArticleEntity(ArticleEntity.Source(article.source.id, article.source.name), article.author, article.title, article.description, article.url, article.urlToImage, article.publishedAt, article.content) } }
3
Kotlin
0
2
ac296340b50ca7494d6b72753e1e88624e440fc4
1,131
android-clean-architecture-mvi-boilerplate
MIT License
src/main/kotlin/com/yutakomura/entity/Role.kt
yuta-komura
584,065,354
false
null
package com.yutakomura.entity import com.yutakomura.security.SecurityConfiguration import org.seasar.doma.Column import org.seasar.doma.Entity import org.seasar.doma.Table @Entity(immutable = true) @Table(name = "role") data class Role( @Column(name = "user_id") val userId: Int, @Column(name = "role") val role: String = SecurityConfiguration.ROLE_NORMAL )
0
Kotlin
0
0
a43d506043858c54f517b5b505bd105cc1701beb
375
ddd-practice
MIT License
app/src/main/java/grack/dev/creditpointapp/preferences/UserPreferences.kt
Rarj
221,030,903
false
{"Java": 749973, "Kotlin": 125836, "Assembly": 18}
package grack.dev.creditpointapp.preferences data class UserPreferences( var alamatAdmin: String?, var emailAdmin: String?, var idAdmin: String?, var levelAdmin: String?, var namaAdmin: String?, var passwordAdmin: String?, var statusAdmin: String?, var foto: String? ) data class WaliMuridPreferences( var idSiswa: String?, var alamatAdmin: String?, var emailAdmin: String?, var idAdmin: String?, var namaAdmin: String?, var statusAdmin: String?, var sisaPointSiswa: String?, var idWaliMurid: String?, var passwordWaliMurid: String?, var jenisKelaminWaliMurid: String? ) data class UpdateWaliMuridPreferences( var id_wali_murid: String?, var nama_wali_murid: String?, var alamat_wali_murid: String?, var jenis_kelamin: String?, var email_wali_murid: String?, var password_wali_murid: String? )
1
null
1
1
e4c64581ac6f0edee85e758079a9ff713256b1c4
844
credit_point_apps
MIT License
app/src/main/java/xyz/thaihuynh/service/MessengerService.kt
thaihuynhxyz
126,955,811
false
null
package xyz.thaihuynh.service import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.os.Handler import android.os.IBinder import android.os.Message import android.os.Messenger import android.widget.Toast class MessengerService : Service() { /** * Handler of incoming messages from clients. */ @SuppressLint("HandlerLeak") internal inner class IncomingHandler : Handler() { override fun handleMessage(msg: Message) { when (msg.what) { MSG_SAY_HELLO -> Toast.makeText(applicationContext, "hello!", Toast.LENGTH_SHORT).show() else -> super.handleMessage(msg) } } } /** * Target we publish for clients to send messages to IncomingHandler. */ private val mMessenger = Messenger(IncomingHandler()) /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ override fun onBind(intent: Intent): IBinder? { Toast.makeText(applicationContext, "binding", Toast.LENGTH_SHORT).show() return mMessenger.binder } companion object { /** Command to the service to display a message */ const val MSG_SAY_HELLO = 1 } }
0
Kotlin
1
4
0b1d35bc205130d67e294acedca476ba9a84554e
1,305
android-service
Apache License 2.0
app/src/main/java/xyz/thaihuynh/service/MessengerService.kt
thaihuynhxyz
126,955,811
false
null
package xyz.thaihuynh.service import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.os.Handler import android.os.IBinder import android.os.Message import android.os.Messenger import android.widget.Toast class MessengerService : Service() { /** * Handler of incoming messages from clients. */ @SuppressLint("HandlerLeak") internal inner class IncomingHandler : Handler() { override fun handleMessage(msg: Message) { when (msg.what) { MSG_SAY_HELLO -> Toast.makeText(applicationContext, "hello!", Toast.LENGTH_SHORT).show() else -> super.handleMessage(msg) } } } /** * Target we publish for clients to send messages to IncomingHandler. */ private val mMessenger = Messenger(IncomingHandler()) /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ override fun onBind(intent: Intent): IBinder? { Toast.makeText(applicationContext, "binding", Toast.LENGTH_SHORT).show() return mMessenger.binder } companion object { /** Command to the service to display a message */ const val MSG_SAY_HELLO = 1 } }
0
Kotlin
1
4
0b1d35bc205130d67e294acedca476ba9a84554e
1,305
android-service
Apache License 2.0
src/test/kotlin/ch/unil/pafanalysis/common/ReadTableDataTests.kt
UNIL-PAF
419,229,519
false
null
package ch.unil.pafanalysis.common import ch.unil.pafanalysis.analysis.service.ColumnMappingParser import ch.unil.pafanalysis.results.model.ResultType import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import java.math.BigDecimal @SpringBootTest class ReadTableDataTests { @Autowired val colParser: ColumnMappingParser? = null private val readTableData = ReadTableData() private fun computeMean(col: List<Any>?): Double? { val ints = col?.map { it as? Double ?: Double.NaN }?.filter { !it.isNaN() } return ints?.average() } @Test fun readFluderTable() { val filePath = "./src/test/resources/results/spectronaut/20220707_114227_Fluder-14650-53_Report_Copy.txt" val commonRes = colParser!!.parse(filePath, null, ResultType.Spectronaut).second val table = readTableData.getTable(filePath, commonRes.headers) assert(table!!.cols?.size == 26) assert(table!!.cols?.get(0)?.size == 5763) assert(table!!.headers!!.isNotEmpty()) val header = table.headers?.find { it.experiment?.field == "Quantity" && it.experiment?.name == "14650" } val quants = table.cols?.get(header!!.idx) val mean = BigDecimal(computeMean(quants)!!) assert(mean == BigDecimal(10156.141745518113)) } @Test fun readMQTable() { val resPath = "./src/test/resources/results/maxquant/Grepper-13695-710/" val filePath = resPath + "proteinGroups.txt" val commonRes = colParser!!.parse(filePath, resPath, ResultType.MaxQuant).second val table = readTableData.getTable(filePath, commonRes.headers) assert(table!!.cols?.size == 219) assert(table!!.headers!!.isNotEmpty()) assert(table!!.headers!!.size == 219) assert(table!!.headers!![0].name == "Protein.IDs") val header = table.headers?.find { it.experiment?.field == "LFQ.intensity" && it.experiment?.name == "WT-13697" } val quants = table.cols?.get(header!!.idx) val mean = computeMean(quants)?.toInt() assert(mean == 789722858) } @Test fun succesfulGetDoubleMatrix() { val resPath = "./src/test/resources/results/maxquant/Grepper-13695-710/" val filePath = resPath + "proteinGroups.txt" val commonRes = colParser!!.parse(filePath, resPath, ResultType.MaxQuant).second val table = readTableData.getTable(filePath, commonRes.headers) val (selHeaders, ints) = readTableData.getDoubleMatrix(table, "LFQ.intensity", null) assert(ints?.size == 16) assert(selHeaders.size == 16) assert(ints[0]?.size == 5535) val mean = computeMean(ints[0])?.toInt() assert(mean == 762055713) } @Test fun noEntriesExceptionGetDoubleMatrix() { val resPath = "./src/test/resources/results/maxquant/Grepper-13695-710/" val filePath = resPath + "proteinGroups.txt" val commonRes = colParser!!.parse(filePath, resPath, ResultType.MaxQuant).second val table = readTableData.getTable(filePath, commonRes.headers) val exception: Exception = assertThrows { readTableData.getDoubleMatrix(table, "blibla", null) } val expectedMessage = "No entries for [blibla] found." val actualMessage = exception.message assert(actualMessage!!.contains(expectedMessage)) } @Test fun notNumericalExceptionGetDoubleMatrix() { val resPath = "./src/test/resources/results/maxquant/Grepper-13695-710/" val filePath = resPath + "proteinGroups.txt" val commonRes = colParser!!.parse(filePath, resPath, ResultType.MaxQuant).second val table = readTableData.getTable(filePath, commonRes.headers) val exception: Exception = assertThrows { readTableData.getDoubleMatrix(table, "Identification.type", null) } val expectedMessage = "Entries for [Identification.type] are not numerical." val actualMessage = exception.message assert(actualMessage!!.contains(expectedMessage)) } }
0
Kotlin
0
0
ffafda01cd91348c4fb5c71ece36abeb850133ae
4,188
paf-analysis-backend
MIT License
webflows/src/test/java/com/schibsted/account/webflows/token/IdTokenValidatorTest.kt
schibsted
385,551,335
false
{"Kotlin": 237572, "Java": 3591}
package com.schibsted.account.webflows.token import com.nimbusds.jose.Payload import com.nimbusds.jose.jwk.JWK import com.nimbusds.jose.jwk.JWKSet import com.nimbusds.jose.jwk.gen.RSAKeyGenerator import com.nimbusds.jwt.JWTClaimsSet import com.schibsted.account.testutil.assertLeft import com.schibsted.account.testutil.assertRight import com.schibsted.account.testutil.createJws import com.schibsted.account.webflows.jose.AsyncJwks import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import java.util.Date private class TestJwks(private val jwks: JWKSet?) : AsyncJwks { override fun fetch(callback: (JWKSet?) -> Unit) { callback(jwks) } } class IdTokenValidatorTest { private val jwk: JWK private val jwks: JWKSet init { jwk = RSAKeyGenerator(2048) .keyID(ID_TOKEN_KEY_ID) .generate() jwks = JWKSet(jwk) } private fun defaultIdTokenClaims(): JWTClaimsSet.Builder { return JWTClaimsSet.Builder() .issuer(ISSUER) .audience(CLIENT_ID) .expirationTime(Date(System.currentTimeMillis() + 5000)) .subject(USER_UUID) .claim("legacy_user_id", USER_ID) .claim("nonce", NONCE) } private fun createIdToken(claims: JWTClaimsSet): String { return createJws(jwk.toRSAKey(), ID_TOKEN_KEY_ID, Payload(claims.toJSONObject())) } private fun idTokenClaims(claims: JWTClaimsSet): IdTokenClaims { return IdTokenClaims( claims.issuer, claims.subject, claims.getStringClaim("legacy_user_id"), claims.audience, (claims.expirationTime.time / 1000), claims.getStringClaim("nonce"), claims.getStringListClaim("amr"), ) } private fun assertErrorMessage( expectedSubstring: String, actualMessage: String, ) { assertTrue( "'$expectedSubstring' not in '$actualMessage'", actualMessage.contains(expectedSubstring), ) } @Test fun testAcceptsValidWithoutAMR() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, null) val claims = defaultIdTokenClaims().build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertRight { assertEquals(idTokenClaims(claims), it) } } } @Test fun testAcceptsValidWithExpectedAMR() { val expectedAmrValue = "testValue" val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, expectedAmrValue) val claims = defaultIdTokenClaims() .claim("amr", listOf(expectedAmrValue, "otherValue")) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertRight { assertEquals(idTokenClaims(claims), it) } } } @Test fun testAcceptsEidAMRWithoutCountryPrefix() { val expectedAmrValue = "eid-se" val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, expectedAmrValue) val claims = defaultIdTokenClaims() .claim("amr", listOf("eid", "otherValue")) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertRight { assertEquals(idTokenClaims(claims), it) } } } @Test fun testAcceptsEidDKAMRWithoutCountryPrefix() { val expectedAmrValue = "eid-dk" val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, expectedAmrValue) val claims = defaultIdTokenClaims() .claim("amr", listOf("eid", "otherValue")) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertRight { assertEquals(idTokenClaims(claims), it) } } } @Test fun testRejectsWrongEidAMRWithoutCountryPrefix() { val expectedAmrValue = "eid-wrong" val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, expectedAmrValue) val claims = defaultIdTokenClaims() .claim("amr", listOf("eid", "otherValue")) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage( "Missing expected AMR value: $expectedAmrValue", it.message, ) } } } @Test fun testRejectMissingExpectedAMRInIdTokenWithoutAMR() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, "testValue") for (amr in listOf(null, emptyList(), listOf("otherValue1", "otherValue2"))) { val claims = defaultIdTokenClaims() .claim("amr", amr) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage("Missing expected AMR value", it.message) } } } } @Test fun testRejectsMismatchingNonce() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, null) for (nonce in listOf(null, "otherNonce")) { val claims = defaultIdTokenClaims() .claim("nonce", nonce) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage("nonce", it.message) } } } } @Test fun testRejectsMismatchingIssuer() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, null) val claims = defaultIdTokenClaims() .issuer("https://other.example.com") .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage("Invalid issuer", it.message) } } } @Test fun testAcceptsIssuerWithTrailingSlash() { val issuerWithSlash = "$ISSUER/" val testData = listOf( ISSUER to ISSUER, ISSUER to issuerWithSlash, issuerWithSlash to ISSUER, issuerWithSlash to issuerWithSlash, ) for ((idTokenIssuer, expectedIssuer) in testData) { val context = IdTokenValidationContext(expectedIssuer, CLIENT_ID, NONCE, null) val claims = defaultIdTokenClaims() .issuer(idTokenIssuer) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertRight { assertEquals(idTokenClaims(claims), it) } } } } @Test fun testRejectsAudienceClaimWithoutExpectedClientId() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, null) val claims = defaultIdTokenClaims() .audience("otherClient") .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage("audience", it.message) } } } @Test fun testRejectsExpiredIdToken() { val context = IdTokenValidationContext(ISSUER, CLIENT_ID, NONCE, null) val hourAgo = System.currentTimeMillis() - (60 * 60) * 1000 val claims = defaultIdTokenClaims() .expirationTime(Date(hourAgo)) .build() val idToken = createIdToken(claims) IdTokenValidator.validate(idToken, TestJwks(jwks), context) { result -> result.assertLeft { assertErrorMessage("Expired JWT", it.message) } } } companion object { const val ID_TOKEN_KEY_ID = "testKey" const val ISSUER = "https://issuer.example.com" const val CLIENT_ID = "client1" const val USER_UUID = "userUuid" const val USER_ID = "12345" const val NONCE = "nonce1234" } }
3
Kotlin
3
2
85193ec1bbd42e2cffefd81ea3541c9e5e683e28
8,704
account-sdk-android-web
MIT License
waypoint-core/src/main/java/com/squaredcandy/waypoint/core/feature/EmptyWaypointFeature.kt
squaredcandy
638,860,321
false
null
package com.squaredcandy.waypoint.core.feature import androidx.compose.runtime.Composable import com.squaredcandy.waypoint.core.content.EmptyWaypointContent import com.squaredcandy.waypoint.core.content.WaypointContent /** * An empty waypoint feature for convenience. */ object EmptyWaypointFeature : MainWaypointFeature { override fun getContent(): WaypointContent = EmptyWaypointContent }
0
Kotlin
0
0
68d7945de37b18b49acde23a555199f205671c08
399
waypoint
Apache License 2.0
app/src/main/java/pl/mobilespot/futuremirror/presentation/dashboard/DashboardViewModel.kt
susnil
765,378,250
false
{"Kotlin": 67763}
package pl.mobilespot.futuremirror.presentation.dashboard import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import pl.mobilespot.futuremirror.namedays.DayMonth import pl.mobilespot.futuremirror.namedays.NameDaysRepository import timber.log.Timber import java.time.LocalDate import javax.inject.Inject @HiltViewModel class DashboardViewModel @Inject constructor( private val nameDaysRepository: NameDaysRepository, private val savedStateHandle: SavedStateHandle ) : ViewModel() { companion object { const val UI_STATE = "dashboard_ui_state" } val uiState = savedStateHandle.getStateFlow(UI_STATE, DashboardState.raw) init { val stateUi: DashboardState? = savedStateHandle[UI_STATE] Timber.d("Init ViewModel, StateUi: $stateUi") updateNameDay() } private fun updateNameDay() { val localDate = LocalDate.now() val dayMonth = DayMonth(uiState.value.selectedDay ?: localDate.dayOfMonth, localDate.monthValue) val nameDays = nameDaysRepository.getNamesForDay(dayMonth) savedStateHandle[UI_STATE] = uiState.value.copy(namesDay = nameDays) Timber.d("Name days $nameDays") } fun selectDay(day: Int) { savedStateHandle[UI_STATE] = uiState.value.copy(selectedDay = day) Timber.d("select day: $day") updateNameDay() } fun unselect() { savedStateHandle[UI_STATE] = uiState.value.copy(selectedDay = null) Timber.d("Unselect day") updateNameDay() } }
0
Kotlin
0
1
369ae6f6d38ff63df9ac2158d70b253ce527ac5c
1,609
FutureMirror
Apache License 2.0
android/app/src/main/java/com/kaelesty/audionautica/di/ViewModelsModule.kt
Kaelesty
698,507,418
false
{"Kotlin": 168575, "Python": 32952, "JavaScript": 23934, "CSS": 10199, "HTML": 231}
package com.kaelesty.audionautica.di import androidx.lifecycle.ViewModel import com.kaelesty.audionautica.presentation.player.PlayerViewModel import com.kaelesty.audionautica.presentation.playlists.PlaylistsViewModel import com.kaelesty.audionautica.presentation.playlists.upload.PlaylistUploadViewModel import com.kaelesty.audionautica.presentation.viewmodels.AccessViewModel import com.kaelesty.audionautica.presentation.viewmodels.MusicViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import dagger.multibindings.StringKey @Module interface ViewModelsModule { @IntoMap @StringKey("AccessViewModel") @Binds fun bindAccessViewModel(impl: AccessViewModel): ViewModel @IntoMap @StringKey("MusicViewModel") @Binds fun bindsMusicViewModel(impl: MusicViewModel): ViewModel @IntoMap @StringKey("PlayerViewModel") @Binds fun bindsPlayerViewModel(impl: PlayerViewModel): ViewModel @IntoMap @StringKey("PlaylistsViewModel") @Binds fun bindsPlaylistsViewModel(impl: PlaylistsViewModel): ViewModel @IntoMap @StringKey("PlaylistUploadViewModel") @Binds fun bindsPlaylistUploadViewModel(impl: PlaylistUploadViewModel): ViewModel }
0
Kotlin
1
0
db5f74b34840a9ac03c67521aa7820d1cd55232a
1,184
project-audionautica
The Unlicense
libnavigation-core/src/test/java/com/mapbox/navigation/core/arrival/ArrivalOptionsTest.kt
zainriaz
341,444,057
true
{"Kotlin": 2515109, "Java": 89431, "Python": 11057, "Makefile": 5883, "JavaScript": 2362, "Shell": 1686}
package com.mapbox.navigation.core.arrival import com.mapbox.navigation.testing.BuilderTest import org.junit.Test import kotlin.reflect.KClass class ArrivalOptionsTest : BuilderTest<ArrivalOptions, ArrivalOptions.Builder>() { override fun getImplementationClass(): KClass<ArrivalOptions> = ArrivalOptions::class override fun getFilledUpBuilder(): ArrivalOptions.Builder { return ArrivalOptions.Builder() .arrivalInMeters(123.0) .arrivalInSeconds(345.0) } @Test override fun trigger() { // only used to trigger JUnit4 to run this class if all test cases come from the parent } }
0
null
0
0
5de9c3c9484466b641ab8907ce9ed316598bad56
646
mapbox-navigation-android
MIT License
src/2020/Day7_1.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.collections.ArrayList data class Bag(val color: String, val contents: HashMap<Bag,Int> = HashMap<Bag,Int>()) { fun findBagOrNew(color: String): Bag { val x = contents.keys.filter { color == it.color } val i = x.indexOfFirst { color == it.color } return if (i >= 0) x[i] else Bag(color) } fun look(lookingFor: String, top: Bag, matches: HashSet<Bag>): Unit { if (color == "TOP") { contents.forEach { bag, count -> bag.look(lookingFor, bag, matches)} } else { contents.forEach { bag, count -> if (bag.color == lookingFor) matches.add(top) if (bag.contents.isNotEmpty()) bag.look(lookingFor, top, matches) } } } } val bags = Bag("TOP", HashMap<Bag,Int>()) File("input/2020/day7").forEachLine { val (color,inner) = it.split(" bags contain ") val bag = bags.findBagOrNew(color) bags.contents.put(bag, 1) inner.trim().split(",") .filter { it != "no other bags." } .forEach { val descriptors = it.trim().split(" ") val count = descriptors[0].trim().toInt() val color = descriptors.subList(1, descriptors.lastIndex).joinToString(" ").trim() var innerBag = bags.findBagOrNew(color) if (!bags.contents.keys.contains(innerBag)) bags.contents.put(innerBag, 1) bag.contents.put(innerBag, count) } } val lookingFor = "shiny gold" val matches = HashSet<Bag>() bags.look(lookingFor,bags,matches) println(matches.size)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,585
adventofcode
MIT License
app/src/p_demo/java/com/dgk/klibrary/demo/TestActivity.kt
KevinDGK
130,669,390
false
null
package com.dgk.klibrary.demo import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.dgk.R import com.dgk.common.util.getFormatDate import com.dgk.common.util.log.KLogi import com.dgk.common.util.log.UploadLogIntentService import com.dgk.klibrary.main.app.CONFIG_SERVER_URL import kotlinx.android.synthetic.main.demo_activity_test.* class TestActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.demo_activity_test) setSupportActionBar(toolbar) btn_upload_log.setOnClickListener { KLogi(this@TestActivity, "点击日志上传按钮") val today = getFormatDate(pattern = "yyyyMMdd") UploadLogIntentService.launch(this@TestActivity, today, "$CONFIG_SERVER_URL/uploadFile") } } }
1
Kotlin
1
1
28101a0ae5a8449ac166ba48e3221d0819ac4bef
871
KLibrary
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/FolderAdd.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.FolderAdd: ImageVector get() { if (_folderAdd != null) { return _folderAdd!! } _folderAdd = Builder(name = "FolderAdd", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { group { path(fill = SolidColor(Color(0xFF374957)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(0.0f, 7.0002f) verticalLineTo(4.0002f) curveTo(0.0f, 3.2046f, 0.3161f, 2.4415f, 0.8787f, 1.8789f) curveTo(1.4413f, 1.3163f, 2.2043f, 1.0002f, 3.0f, 1.0002f) horizontalLineTo(8.236f) lineTo(12.236f, 3.0002f) horizontalLineTo(21.0f) curveTo(21.7956f, 3.0002f, 22.5587f, 3.3163f, 23.1213f, 3.8789f) curveTo(23.6839f, 4.4415f, 24.0f, 5.2046f, 24.0f, 6.0002f) verticalLineTo(7.0002f) horizontalLineTo(0.0f) close() moveTo(24.0f, 9.0002f) verticalLineTo(23.0002f) horizontalLineTo(0.0f) verticalLineTo(9.0002f) horizontalLineTo(24.0f) close() moveTo(16.0f, 15.0002f) horizontalLineTo(13.0f) verticalLineTo(12.0002f) horizontalLineTo(11.0f) verticalLineTo(15.0002f) horizontalLineTo(8.0f) verticalLineTo(17.0002f) horizontalLineTo(11.0f) verticalLineTo(20.0002f) horizontalLineTo(13.0f) verticalLineTo(17.0002f) horizontalLineTo(16.0f) verticalLineTo(15.0002f) close() } } } .build() return _folderAdd!! } private var _folderAdd: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,823
icons
MIT License
app/src/main/java/com/vectorinc/vectormoviesearch/presentation/search_screen/Shimmer.kt
somtorizm
513,634,919
false
{"Kotlin": 221854}
package com.vectorinc.vectormoviesearch.presentation.search_screen import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.unit.dp import com.vectorinc.vectormoviesearch.ui.theme.ShimmerColorShades @Composable fun ShimmerCard( brush: Brush ) { Column( modifier = Modifier .fillMaxWidth() ) { Box() { Card( shape = RoundedCornerShape(15.dp), elevation = 1.dp ) { Box( modifier = Modifier .height(170.dp) .width(150.dp) .background(brush) ) { } } Box( modifier = Modifier .fillMaxWidth() .height(170.dp) ) } } } @Composable fun ShimmerAnimation( ) { /* Create InfiniteTransition which holds child animation like [Transition] animations start running as soon as they enter the composition and do not stop unless they are removed */ val transition = rememberInfiniteTransition() val translateAnim by transition.animateFloat( /* Specify animation positions, initial Values 0F means it starts from 0 position */ initialValue = 0f, targetValue = 800f, animationSpec = infiniteRepeatable( /* Tween Animates between values over specified [durationMillis] */ tween(durationMillis = 1000, easing = FastOutLinearInEasing), RepeatMode.Reverse ) ) /* Create a gradient using the list of colors Use Linear Gradient for animating in any direction according to requirement start=specifies the position to start with in cartesian like system Offset(10f,10f) means x(10,0) , y(0,10) end= Animate the end position to give the shimmer effect using the transition created above */ val brush = Brush.linearGradient( colors = ShimmerColorShades, start = Offset(5f, 5f), end = Offset(translateAnim, translateAnim) ) ShimmerItem(brush = brush) } @Composable fun ShimmerItem( brush: Brush, ) { /* Column composable shaped like a rectangle, set the [background]'s [brush] with the brush receiving from [ShimmerAnimation] which will get animated. Add few more Composable to test */ ShimmerCard(brush = brush) }
0
Kotlin
0
3
f8ee62191309cdaefc3297010133e3800a2bf30a
2,924
MovieAblum
Apache License 2.0
yukihookapi-core/src/main/java/com/highcapable/yukihookapi/hook/xposed/prefs/YukiHookPrefsBridge.kt
fankes
453,432,887
false
null
/* * YukiHookAPI - An efficient Hook API and Xposed Module solution built in Kotlin. * Copyright (C) 2019-2023 HighCapable * https://github.com/fankes/YukiHookAPI * * MIT License * * 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. * * This file is Created by fankes on 2022/2/8. */ @file:Suppress("unused", "MemberVisibilityCanBePrivate", "StaticFieldLeak", "SetWorldReadable", "CommitPrefEdits", "UNCHECKED_CAST") package com.highcapable.yukihookapi.hook.xposed.prefs import android.content.Context import android.content.SharedPreferences import android.util.ArrayMap import androidx.preference.PreferenceFragmentCompat import com.highcapable.yukihookapi.YukiHookAPI import com.highcapable.yukihookapi.hook.log.yLoggerE import com.highcapable.yukihookapi.hook.log.yLoggerW import com.highcapable.yukihookapi.hook.xposed.bridge.YukiXposedModule import com.highcapable.yukihookapi.hook.xposed.bridge.delegate.XSharedPreferencesDelegate import com.highcapable.yukihookapi.hook.xposed.parasitic.AppParasitics import com.highcapable.yukihookapi.hook.xposed.prefs.data.PrefsData import com.highcapable.yukihookapi.hook.xposed.prefs.ui.ModulePreferenceFragment import de.robv.android.xposed.XSharedPreferences import java.io.File /** * [YukiHookAPI] 对 [SharedPreferences]、[XSharedPreferences] 的扩展存储桥实现 * * 在不同环境智能选择存取使用的对象 * * - ❗模块与宿主之前共享数据存储为实验性功能 - 仅在 LSPosed 环境测试通过 - EdXposed 理论也可以使用但不再推荐 * * 对于在模块环境中使用 [PreferenceFragmentCompat] - [YukiHookAPI] 提供了 [ModulePreferenceFragment] 来实现同样的功能 * * 详情请参考 [API 文档 - YukiHookPrefsBridge](https://fankes.github.io/YukiHookAPI/zh-cn/api/public/com/highcapable/yukihookapi/hook/xposed/prefs/YukiHookPrefsBridge) * * For English version, see [API Document - YukiHookPrefsBridge](https://fankes.github.io/YukiHookAPI/en/api/public/com/highcapable/yukihookapi/hook/xposed/prefs/YukiHookPrefsBridge) * @param context 上下文实例 - 默认空 */ class YukiHookPrefsBridge private constructor(private var context: Context? = null) { internal companion object { /** 当前是否为 (Xposed) 宿主环境 */ private val isXposedEnvironment = YukiXposedModule.isXposedEnvironment /** 当前缓存的 [XSharedPreferencesDelegate] 实例数组 */ private val xPrefs = ArrayMap<String, XSharedPreferencesDelegate>() /** 当前缓存的 [SharedPreferences] 实例数组 */ private val sPrefs = ArrayMap<String, SharedPreferences>() /** * 创建 [YukiHookPrefsBridge] 对象 * @param context 实例 - (Xposed) 宿主环境为空 * @return [YukiHookPrefsBridge] */ internal fun from(context: Context? = null) = YukiHookPrefsBridge(context) /** * 设置全局可读可写 * @param context 实例 * @param prefsFileName Sp 文件名 */ internal fun makeWorldReadable(context: Context?, prefsFileName: String) { runCatching { context?.also { File(File(it.applicationInfo.dataDir, "shared_prefs"), prefsFileName).apply { setReadable(true, false) setExecutable(true, false) } } } } } /** 存储名称 */ private var prefsName = "" /** 是否使用新版存储方式 EdXposed、LSPosed */ private var isUsingNewXSharedPreferences = false /** 是否启用原生存储方式 */ private var isUsingNativeStorage = false /** * 获取当前存储名称 - 默认包名 + _preferences * @return [String] */ private val currentPrefsName get() = prefsName.ifBlank { if (isUsingNativeStorage) "${context?.packageName ?: "unknown"}_preferences" else "${YukiXposedModule.modulePackageName.ifBlank { context?.packageName ?: "unknown" }}_preferences" } /** 检查 API 装载状态 */ private fun checkApi() { if (YukiHookAPI.isLoadedFromBaseContext) error("YukiHookPrefsBridge not allowed in Custom Hook API") if (isXposedEnvironment && YukiXposedModule.modulePackageName.isBlank()) error("Xposed modulePackageName load failed, please reset and rebuild it") } /** * 设置全局可读可写 * @param callback 回调方法体 * @return [T] */ private inline fun <T> makeWorldReadable(callback: () -> T): T { val result = callback() if (isXposedEnvironment.not() && isUsingNewXSharedPreferences.not()) runCatching { makeWorldReadable(context, prefsFileName = "${currentPrefsName}.xml") } return result } /** * 获取当前 [XSharedPreferences] 对象 * @return [XSharedPreferences] */ private val currentXsp get() = checkApi().let { runCatching { (xPrefs[currentPrefsName]?.instance ?: XSharedPreferencesDelegate.from(YukiXposedModule.modulePackageName, currentPrefsName) .also { xPrefs[currentPrefsName] = it }.instance).apply { makeWorldReadable() reload() } }.onFailure { yLoggerE(msg = it.message ?: "Operating system not supported", e = it) }.getOrNull() ?: error("Cannot load the XSharedPreferences, maybe is your Hook Framework not support it") } /** * 获取当前 [SharedPreferences] 对象 * @return [SharedPreferences] */ private val currentSp get() = checkApi().let { runCatching { @Suppress("DEPRECATION", "WorldReadableFiles") sPrefs[context.toString() + currentPrefsName] ?: context?.getSharedPreferences(currentPrefsName, Context.MODE_WORLD_READABLE) ?.also { isUsingNewXSharedPreferences = true sPrefs[context.toString() + currentPrefsName] = it } ?: error("YukiHookPrefsBridge missing Context instance") }.getOrElse { sPrefs[context.toString() + currentPrefsName] ?: context?.getSharedPreferences(currentPrefsName, Context.MODE_PRIVATE)?.also { isUsingNewXSharedPreferences = false sPrefs[context.toString() + currentPrefsName] = it } ?: error("YukiHookPrefsBridge missing Context instance") } } /** * 获取 [XSharedPreferences] 是否可读 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [isPreferencesAvailable] * @return [Boolean] */ @Deprecated(message = "请使用新方式来实现此功能", ReplaceWith("isPreferencesAvailable")) val isXSharePrefsReadable get() = isPreferencesAvailable /** * 获取 [YukiHookPrefsBridge] 是否正处于 EdXposed/LSPosed 的最高权限运行 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [isPreferencesAvailable] * @return [Boolean] */ @Deprecated(message = "请使用新方式来实现此功能", ReplaceWith("isPreferencesAvailable")) val isRunInNewXShareMode get() = isPreferencesAvailable /** * 获取当前 [YukiHookPrefsBridge] 的可用状态 * * - 在 (Xposed) 宿主环境中返回 [XSharedPreferences] 可用状态 (可读) * * - 在模块环境中返回当前是否处于 New XSharedPreferences 模式 (可读可写) * @return [Boolean] */ val isPreferencesAvailable get() = if (isXposedEnvironment) (runCatching { currentXsp.let { it.file.exists() && it.file.canRead() } }.getOrNull() ?: false) else runCatching { /** 执行一次装载 */ currentSp.edit() isUsingNewXSharedPreferences }.getOrNull() ?: false /** * 自定义 Sp 存储名称 * @param name 自定义的 Sp 存储名称 * @return [YukiHookPrefsBridge] */ fun name(name: String): YukiHookPrefsBridge { prefsName = name return this } /** * 忽略缓存直接读取键值 * * - ❗此方法及功能已被移除 - 在之后的版本中将直接被删除 * * - ❗键值的直接缓存功能已被移除 - 因为其存在内存溢出 (OOM) 问题 * @return [YukiHookPrefsBridge] */ @Deprecated(message = "此方法及功能已被移除,请删除此方法", ReplaceWith("this")) fun direct() = this /** * 忽略当前环境直接使用 [Context.getSharedPreferences] 存取数据 * @return [YukiHookPrefsBridge] * @throws IllegalStateException 如果 [context] 为空 */ fun native(): YukiHookPrefsBridge { if (isXposedEnvironment && context == null) context = AppParasitics.currentApplication ?: error("The Host App's Context has not yet initialized successfully, the native function cannot be used at this time") isUsingNativeStorage = true return this } /** * 获取 [String] 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - "" * @return [String] */ fun getString(key: String, value: String = "") = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getString(key, value) ?: value else currentSp.getString(key, value) ?: value } /** * 获取 [Set]<[String]> 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - [HashSet]<[String]> * @return [Set]<[String]> */ fun getStringSet(key: String, value: Set<String> = hashSetOf()) = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getStringSet(key, value) ?: value else currentSp.getStringSet(key, value) ?: value } /** * 获取 [Boolean] 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - false * @return [Boolean] */ fun getBoolean(key: String, value: Boolean = false) = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getBoolean(key, value) else currentSp.getBoolean(key, value) } /** * 获取 [Int] 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - 0 * @return [Int] */ fun getInt(key: String, value: Int = 0) = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getInt(key, value) else currentSp.getInt(key, value) } /** * 获取 [Float] 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - 0f * @return [Float] */ fun getFloat(key: String, value: Float = 0f) = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getFloat(key, value) else currentSp.getFloat(key, value) } /** * 获取 [Long] 键值 * * - 智能识别对应环境读取键值数据 * * - 建议使用 [PrefsData] 创建模板并使用 [get] 获取数据 * @param key 键值名称 * @param value 默认数据 - 0L * @return [Long] */ fun getLong(key: String, value: Long = 0L) = makeWorldReadable { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.getLong(key, value) else currentSp.getLong(key, value) } /** * 智能获取指定类型的键值 * @param prefs 键值实例 * @param value 默认值 - 未指定默认为 [prefs] 中的 [PrefsData.value] * @return [T] 只能是 [String]、[Set]<[String]>、[Int]、[Float]、[Long]、[Boolean] */ inline fun <reified T> get(prefs: PrefsData<T>, value: T = prefs.value): T = getPrefsData(prefs.key, value) as T /** * 智能获取指定类型的键值 * * 封装方法以调用内联方法 * @param key 键值 * @param value 默认值 * @return [Any] */ @PublishedApi internal fun getPrefsData(key: String, value: Any?): Any = when (value) { is String -> getString(key, value) is Set<*> -> getStringSet(key, value as? Set<String> ?: error("Key-Value type ${value.javaClass.name} is not allowed")) is Int -> getInt(key, value) is Float -> getFloat(key, value) is Long -> getLong(key, value) is Boolean -> getBoolean(key, value) else -> error("Key-Value type ${value?.javaClass?.name} is not allowed") } /** * 判断当前是否包含 [key] 键值的数据 * * - 智能识别对应环境读取键值数据 * @return [Boolean] 是否包含 */ fun contains(key: String) = if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.contains(key) else currentSp.contains(key) /** * 获取全部存储的键值数据 * * - 智能识别对应环境读取键值数据 * * - ❗每次调用都会获取实时的数据 - 不受缓存控制 - 请勿在高并发场景中使用 * @return [HashMap] 全部类型的键值数组 */ fun all() = hashMapOf<String, Any?>().apply { if (isXposedEnvironment && isUsingNativeStorage.not()) currentXsp.all.forEach { (k, v) -> this[k] = v } else currentSp.all.forEach { (k, v) -> this[k] = v } } /** * 移除全部包含 [key] 的存储数据 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { remove(key) }")) fun remove(key: String) = edit { remove(key) } /** * 移除 [PrefsData.key] 的存储数据 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param prefs 键值实例 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { remove(prefs) }")) inline fun <reified T> remove(prefs: PrefsData<T>) = edit { remove(prefs) } /** * 移除全部存储数据 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { clear() }")) fun clear() = edit { clear() } /** * 存储 [String] 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putString(key, value) }")) fun putString(key: String, value: String) = edit { putString(key, value) } /** * 存储 [Set]<[String]> 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putStringSet(key, value) }")) fun putStringSet(key: String, value: Set<String>) = edit { putStringSet(key, value) } /** * 存储 [Boolean] 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putBoolean(key, value) }")) fun putBoolean(key: String, value: Boolean) = edit { putBoolean(key, value) } /** * 存储 [Int] 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putInt(key, value) }")) fun putInt(key: String, value: Int) = edit { putInt(key, value) } /** * 存储 [Float] 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putFloat(key, value) }")) fun putFloat(key: String, value: Float) = edit { putFloat(key, value) } /** * 存储 [Long] 键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 * @param key 键值名称 * @param value 键值数据 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { putLong(key, value) }")) fun putLong(key: String, value: Long) = edit { putLong(key, value) } /** * 智能存储指定类型的键值 * * - ❗此方法已弃用 - 在之后的版本中将直接被删除 * * - ❗请现在转移到 [edit] 方法 */ @Deprecated(message = "此方法因为性能问题已被作废,请转移到新用法", ReplaceWith("edit { put(prefs, value) }")) inline fun <reified T> put(prefs: PrefsData<T>, value: T) = edit { put(prefs, value) } /** * 创建新的 [Editor] * * - 在模块环境中或启用了 [isUsingNativeStorage] 后使用 * * - ❗在 (Xposed) 宿主环境下只读 - 无法使用 * @return [Editor] */ fun edit() = Editor() /** * 创建新的 [Editor] * * 自动调用 [Editor.apply] 方法 * * - 在模块环境中或启用了 [isUsingNativeStorage] 后使用 * * - ❗在 (Xposed) 宿主环境下只读 - 无法使用 * @param initiate 方法体 */ fun edit(initiate: Editor.() -> Unit) = edit().apply(initiate).apply() /** * 清除 [YukiHookPrefsBridge] 中缓存的键值数据 * * - ❗此方法及功能已被移除 - 在之后的版本中将直接被删除 * * - ❗键值的直接缓存功能已被移除 - 因为其存在内存溢出 (OOM) 问题 * @return [YukiHookPrefsBridge] */ @Deprecated(message = "此方法及功能已被移除,请删除此方法") fun clearCache() { } /** * [YukiHookPrefsBridge] 的存储代理类 * * - ❗请使用 [edit] 方法来获取 [Editor] * * - 在模块环境中或启用了 [isUsingNativeStorage] 后使用 * * - ❗在 (Xposed) 宿主环境下只读 - 无法使用 */ inner class Editor internal constructor() { /** 创建新的存储代理类 */ private var editor = runCatching { currentSp.edit() }.getOrNull() /** * 移除全部包含 [key] 的存储数据 * @param key 键值名称 * @return [Editor] */ fun remove(key: String) = specifiedScope { editor?.remove(key) } /** * 移除 [PrefsData.key] 的存储数据 * @param prefs 键值实例 * @return [Editor] */ inline fun <reified T> remove(prefs: PrefsData<T>) = remove(prefs.key) /** * 移除全部存储数据 * @return [Editor] */ fun clear() = specifiedScope { editor?.clear() } /** * 存储 [String] 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putString(key: String, value: String) = specifiedScope { editor?.putString(key, value) } /** * 存储 [Set]<[String]> 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putStringSet(key: String, value: Set<String>) = specifiedScope { editor?.putStringSet(key, value) } /** * 存储 [Boolean] 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putBoolean(key: String, value: Boolean) = specifiedScope { editor?.putBoolean(key, value) } /** * 存储 [Int] 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putInt(key: String, value: Int) = specifiedScope { editor?.putInt(key, value) } /** * 存储 [Float] 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putFloat(key: String, value: Float) = specifiedScope { editor?.putFloat(key, value) } /** * 存储 [Long] 键值 * * - 建议使用 [PrefsData] 创建模板并使用 [put] 存储数据 * @param key 键值名称 * @param value 键值数据 * @return [Editor] */ fun putLong(key: String, value: Long) = specifiedScope { editor?.putLong(key, value) } /** * 智能存储指定类型的键值 * @param prefs 键值实例 * @param value 要存储的值 - 只能是 [String]、[Set]<[String]>、[Int]、[Float]、[Long]、[Boolean] * @return [Editor] */ inline fun <reified T> put(prefs: PrefsData<T>, value: T) = putPrefsData(prefs.key, value) /** * 智能存储指定类型的键值 * * 封装方法以调用内联方法 * @param key 键值 * @param value 要存储的值 - 只能是 [String]、[Set]<[String]>、[Int]、[Float]、[Long]、[Boolean] * @return [Editor] */ @PublishedApi internal fun putPrefsData(key: String, value: Any?) = when (value) { is String -> putString(key, value) is Set<*> -> putStringSet(key, value as? Set<String> ?: error("Key-Value type ${value.javaClass.name} is not allowed")) is Int -> putInt(key, value) is Float -> putFloat(key, value) is Long -> putLong(key, value) is Boolean -> putBoolean(key, value) else -> error("Key-Value type ${value?.javaClass?.name} is not allowed") } /** * 提交更改 (同步) * @return [Boolean] 是否成功 */ fun commit() = makeWorldReadable { editor?.commit() ?: false } /** 提交更改 (异步) */ fun apply() = makeWorldReadable { editor?.apply() ?: Unit } /** * 仅在模块环境或 [isUsingNativeStorage] 执行 * * 非模块环境使用会打印警告信息 * @param callback 在模块环境执行 * @return [Editor] */ private inline fun specifiedScope(callback: () -> Unit): Editor { if (isXposedEnvironment.not() || isUsingNativeStorage) callback() else yLoggerW(msg = "YukiHookPrefsBridge.Editor not allowed in Xposed Environment") return this } } }
5
null
53
887
e7cca9b5ca874dd3dca8a03c341e8202aa87307d
21,914
YukiHookAPI
MIT License
platform/collaboration-tools/src/com/intellij/collaboration/ui/EditableComponentFactory.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.collaboration.ui import com.intellij.collaboration.ui.util.bindContentIn import com.intellij.ui.components.panels.Wrapper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import javax.swing.JComponent object EditableComponentFactory { fun <VM : Any> create(cs: CoroutineScope, component: JComponent, editingVm: Flow<VM?>, editorComponentSupplier: (CoroutineScope, VM) -> JComponent): JComponent { return Wrapper().apply { bindContentIn(cs, editingVm) { vm -> if (vm != null) editorComponentSupplier(this, vm) else component } } } }
233
null
4912
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
759
intellij-community
Apache License 2.0
app/src/main/java/com/example/bookloverfinalapp/app/ui/general_screens/screen_profile/login_out/FragmentLoginOutDialog.kt
yusuf0405
484,801,816
false
null
package com.example.bookloverfinalapp.app.ui.general_screens.screen_profile.login_out import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import com.example.bookloverfinalapp.app.utils.bindingLifecycleError import com.example.bookloverfinalapp.app.utils.extensions.setOnDownEffectClickListener import com.example.bookloverfinalapp.app.utils.extensions.tuneBottomDialog import com.example.bookloverfinalapp.app.utils.extensions.tuneLyricsDialog import com.example.bookloverfinalapp.databinding.FragmentLoginOutDialogBinding import com.joseph.ui_core.custom.modal_page.ModalPage import com.joseph.ui_core.custom.modal_page.dismissModalPage import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class FragmentLoginOutDialog : DialogFragment() { private var _binding: FragmentLoginOutDialogBinding? = null private val binding get() = _binding ?: bindingLifecycleError() private val viewModel: FragmentLoginOutDialogViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLoginOutDialogBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setOnClickListeners() } private fun setOnClickListeners() = with(binding) { loginOutButton.setOnDownEffectClickListener { viewModel.loginOut() dismissModalPage() } cancelButton.setOnDownEffectClickListener { dismissModalPage() } } companion object { fun newInstance() = FragmentLoginOutDialog().run { ModalPage.Builder() .fragment(this) .build() } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
1
Kotlin
1
2
6e778a25c43f85ffe25bce01788a1b5441c81880
2,076
BookLoverFinalApp
Apache License 1.1
feature/groups/src/main/java/com/azhapps/listapp/groups/ui/GroupsScreen.kt
Azhrei251
539,352,238
false
{"Kotlin": 239334}
package com.azhapps.listapp.groups.ui import android.widget.Toast import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.AlertDialog import androidx.compose.material.Card import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.azhapps.listapp.common.UiState import com.azhapps.listapp.common.model.Group import com.azhapps.listapp.common.ui.DialogButton import com.azhapps.listapp.common.ui.ErrorMarker import com.azhapps.listapp.common.ui.ErrorPage import com.azhapps.listapp.common.ui.LoadingPage import com.azhapps.listapp.common.ui.ThemedScaffold import com.azhapps.listapp.common.ui.TopBar import com.azhapps.listapp.common.ui.theme.ListAppTheme import com.azhapps.listapp.common.ui.theme.Typography import com.azhapps.listapp.groups.GroupsViewModel import com.azhapps.listapp.groups.R import com.azhapps.listapp.groups.model.GroupItemState import com.azhapps.listapp.groups.model.GroupsAction @Composable fun GroupsScreen() { val viewModel = viewModel<GroupsViewModel>() val state = viewModel.collectAsState() ThemedScaffold( topBar = { TopBar( title = stringResource(R.string.groups_title), ) { IconButton(onClick = { viewModel.dispatch(GroupsAction.CreateGroup) }) { Icon( imageVector = Icons.Filled.Add, contentDescription = stringResource(id = R.string.groups_add_new), ) } } } ) { Box(Modifier.padding(it)) { GroupsPage( uiState = state.uiState, groupItemStates = state.groupItemStates, showConfirmDeleteDialog = state.showConfirmDeleteGroupDialog, selectedGroup = state.selectedGroup, actor = viewModel::dispatch, ) } } } @Composable private fun GroupsPage( uiState: UiState, groupItemStates: List<GroupItemState>, showConfirmDeleteDialog: Boolean, selectedGroup: Group?, actor: (GroupsAction) -> Unit, ) { when (uiState) { UiState.Loading -> LoadingPage() is UiState.Error -> ErrorPage( errorMessage = stringResource(id = R.string.groups_selection_error_message), errorTitle = stringResource(id = R.string.groups_selection_error_title), retryAction = { actor(GroupsAction.GetGroups) }, cancelAction = { //TODO }) UiState.Content -> { GroupsContent( groupItemStates = groupItemStates, actor = actor ) if (showConfirmDeleteDialog) { ConfirmDeleteGroupDialog(actor = actor, group = selectedGroup!!) } } } } @Composable private fun ConfirmDeleteGroupDialog( group: Group, actor: (GroupsAction) -> Unit, ) { AlertDialog( onDismissRequest = { actor(GroupsAction.HideConfirmDeleteDialog) }, confirmButton = { DialogButton( action = { actor(GroupsAction.DeleteGroup(group)) }, text = stringResource(id = R.string.groups_bottom_confirm_button) ) }, title = { Text(text = stringResource(id = R.string.groups_bottom_confirm_title)) }, text = { Text(text = stringResource(id = R.string.groups_bottom_confirm_remove_group_text, group.name)) } ) } @Composable private fun GroupsContent( groupItemStates: List<GroupItemState>, actor: (GroupsAction) -> Unit, ) { LazyColumn( modifier = Modifier .fillMaxSize() .background(ListAppTheme.alternateBackgroundColor) .padding(start = 8.dp, end = 8.dp, top = 8.dp), verticalArrangement = Arrangement.spacedBy(ListAppTheme.defaultSpacing), content = { groupItemStates.forEach { item { GroupCard( itemState = it, actor = actor ) } } item { Spacer(modifier = Modifier.height(ListAppTheme.defaultSpacing)) } } ) } @OptIn(ExperimentalFoundationApi::class) @Composable private fun GroupCard( itemState: GroupItemState, actor: (GroupsAction) -> Unit, ) { val context = LocalContext.current Card( modifier = Modifier .fillMaxWidth() .combinedClickable( onClick = { if (itemState.editable) { actor(GroupsAction.EditGroup(itemState.group)) } else { Toast .makeText(context, context.getString(R.string.groups_unowned), Toast.LENGTH_LONG) .show() } }, onLongClick = { if (itemState.editable) { actor(GroupsAction.ShowConfirmDeleteDialog(itemState.group)) } } ), elevation = 2.dp, ) { Column(modifier = Modifier.padding(8.dp)) { Row( modifier = Modifier.padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier .padding(end = ListAppTheme.defaultSpacing) .weight(1F), text = itemState.group.name, style = Typography.h6 ) when (itemState.uiState) { UiState.Content -> { //Do nothing } is UiState.Error -> ErrorMarker() UiState.Loading -> CircularProgressIndicator() } } Text(text = itemState.group.users?.joinToString { it.username } ?: "") } } }
5
Kotlin
0
1
317804ec4047ebe3c68b29ef344d4a2e1f1010ae
7,308
list-app
MIT License
src/main/kotlin/pl/krakow/riichi/chombot/commands/kcc3client/Chombo.kt
riichi
196,456,477
false
null
package pl.krakow.riichi.chombot.commands.kcc3client import kotlinx.serialization.Serializable import java.time.temporal.TemporalAccessor @Serializable data class Chombo( @Serializable(with = DateSerializer::class) val timestamp: TemporalAccessor, val player: String, val comment: String )
6
Kotlin
1
4
59ae05a49e0b3a67cc845adc9ec0e6cbeb911011
308
chombot
MIT License
app/src/main/java/com/example/gdsc_hackathon/adapters/TopicAdapter.kt
CerritusCodersComm
439,586,667
false
{"Kotlin": 315378}
package com.example.gdsc_hackathon.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.gdsc_hackathon.R import com.example.gdsc_hackathon.dataModel.Topic import com.firebase.ui.firestore.FirestoreRecyclerAdapter import com.firebase.ui.firestore.FirestoreRecyclerOptions class TopicAdapter(options: FirestoreRecyclerOptions<Topic>) : FirestoreRecyclerAdapter<Topic, TopicAdapter.TopicHolder>(options) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicHolder { val v: View = LayoutInflater.from(parent.context).inflate( R.layout.topic_item, parent, false ) return TopicHolder(v) } override fun onBindViewHolder(holder: TopicHolder, position: Int, model: Topic) { holder.textViewTopic.text = model.topicName } class TopicHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var textViewTopic : TextView = itemView.findViewById(R.id.text_view_topic) var textViewHours : TextView = itemView.findViewById(R.id.text_view_hours) var textViewDiscussion : TextView = itemView.findViewById(R.id.text_view_discussion) } }
4
Kotlin
12
17
58dec8a91b36283b33811149beeeed027bcf95de
1,301
eduJam
MIT License
src/main/kotlin/com/igorivkin/website/service/ArticleServiceImpl.kt
IgorIvkin
341,263,198
false
null
package com.igorivkin.website.service import com.igorivkin.website.controller.dto.IdValue import com.igorivkin.website.controller.dto.article.ArticleCreateRequest import com.igorivkin.website.controller.dto.article.ArticleGetResponse import com.igorivkin.website.controller.dto.article.ArticleGetSimplifiedResponse import com.igorivkin.website.controller.dto.article.ArticleUpdateRequest import com.igorivkin.website.exception.EntityDoesNotExistException import com.igorivkin.website.persistence.repository.ArticleRepository import com.igorivkin.website.service.mapper.ArticleMapper import org.springframework.data.domain.* import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Service class ArticleServiceImpl( private val articleRepository: ArticleRepository, private val articleMapper: ArticleMapper ) : ArticleService { @Transactional(readOnly = true) override fun findById(id: Long): ArticleGetResponse { val article = articleRepository.findById(id) .orElseThrow { EntityDoesNotExistException.ofArticleId(id) } return articleMapper.toDto(article) } @Transactional(readOnly = true) override fun findByTitle(title: String): List<ArticleGetSimplifiedResponse> { return articleMapper.toSimplifiedDto( articleRepository.findAllByTitleContainingIgnoreCase(title) ) } @Transactional(readOnly = true) override fun findAllByTopicId(topicId: Long, pageable: Pageable): Page<ArticleGetResponse> { val page = articleRepository.findAllByTopicsId(topicId, pageable) return PageImpl( articleMapper.toDto(page.toList()), pageable, page.totalElements ) } @Transactional(readOnly = true) override fun findAllByTopicId(topicId: Long, pageNum: Int, articlesPerPage: Int): Page<ArticleGetResponse> { return findAllByTopicId( topicId = topicId, pageable = PageRequest.of( pageNum, articlesPerPage, Sort.by("id").descending() ) ) } @Transactional(readOnly = true) override fun findAll(pageable: Pageable): Page<ArticleGetResponse> { val page = articleRepository.findAll(pageable) return PageImpl( articleMapper.toDto(page.toList()), pageable, page.totalElements ) } @Transactional(readOnly = true) override fun findAll(pageNum: Int, articlesPerPage: Int): Page<ArticleGetResponse> { return findAll( PageRequest.of( pageNum, articlesPerPage, Sort.by("id").descending() ) ) } @Transactional(readOnly = true) override fun findBySearchQuery(query: String): List<ArticleGetResponse> { val results = articleRepository.findAllBySearchQuery(prepareSearchQuery(query)) return articleMapper.toDto(results) } @Transactional override fun create(request: ArticleCreateRequest): IdValue<Long> { val articleId = articleRepository.save(articleMapper.toModel(request)).id if (articleId != null) { return IdValue(id = articleId) } else { throw IllegalStateException("Cannot create request, ID was not set") } } @Transactional override fun update(id: Long, request: ArticleUpdateRequest): IdValue<Long> { val article = articleRepository.findById(id) .orElseThrow { EntityDoesNotExistException.ofArticleId(id) } articleMapper.update(request, article) val articleId = articleRepository.save(article).id if (articleId != null) { return IdValue(id = articleId) } else { throw IllegalStateException("Cannot update request, cannot retrieve ID") } } private fun prepareSearchQuery(query: String): String { return query.split(" ").joinToString(separator = " & ") { it.lowercase(Locale.getDefault()) } } }
0
Kotlin
0
1
71d78154621ac9c1ce4cddb86d385af898c89ae8
4,100
igor-ivkin-website-kotlin
Apache License 2.0
math-hammer-library/src/main/kotlin/io/hsar/mathhammer/statistics/DiceProbability.kt
HSAR
382,069,316
false
null
package io.hsar.mathhammer.statistics object DiceProbability { /** * Returns the expectation of dice that will MEET OR EXCEED the target. */ fun averageChanceToPass(diceNumber: Int, diceTarget: Int, rerolls: Reroll = Reroll.NONE): Double { return (1..diceNumber) .map { currentRoll -> when { currentRoll == 1 -> 0.0 // rolling 1 always fails currentRoll == diceNumber -> 1.0 // rolling max always succeeds currentRoll >= diceTarget -> 1.0 else -> 0.0 }.let { rollSucceeded -> // If we didn't hit, re-roll if allowed if (rollSucceeded != 1.0) { if (rerolls == Reroll.ONES && currentRoll == 1) { averageChanceToPass(diceNumber, diceTarget, Reroll.NONE) // Rerolls don't continue } else if (rerolls == Reroll.ALL) { averageChanceToPass(diceNumber, diceTarget, Reroll.NONE) // Rerolls don't continue } else { rollSucceeded // No re-roll allowed } } else { rollSucceeded // No re-roll needed } } } .average() } }
0
Kotlin
0
0
ffbe8eff2dc37c12737d67a8fc565af59bbb4e6a
1,388
MathHammer
Apache License 2.0
baselibrary/src/main/java/com/android/baselibrary/base/type/RequestType.kt
luechenying
152,445,901
false
null
package com.android.baselibrary.base.type /** * Des: 通用网络请求的Type */ enum class RequestType { TYPE_SUCCESS, TYPE_LOADING, TYPE_ERROR, TYPE_NET_ERROR, TYPE_EMPTY, }
1
null
1
1
4de70a667762ad0b7ce95d143eb93c3d700880e3
191
KotlinVM
Apache License 2.0
app/src/main/java/com/onandoff/onandoff_android/data/model/MyProfileResponse.kt
CMC-Hackathon-Team1
583,885,566
false
{"Kotlin": 409987}
package com.onandoff.onandoff_android.data.model import com.google.gson.annotations.SerializedName data class MyProfileResponse( @SerializedName("profileId") val profileId: Int, @SerializedName("personaName") val personaName: String?, @SerializedName("profileName") val profileName: String?, @SerializedName("statusMessage") val statusMessage: String?, @SerializedName("profileImgUrl") val profileImgUrl: String?, @SerializedName("createdAt") val createdAt: String? )
0
Kotlin
1
1
8be99848ac489415bbf4f056a9a747c155e3101f
518
OnAndOff-Android
The Unlicense
csw-params/src/test/kotlin/csw/params/core/models/SemesterIdTests.kt
kgillies
554,485,604
false
{"Kotlin": 332901, "Java": 2668}
package csw.params.core.models import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.equals.shouldBeEqual import io.kotest.matchers.shouldBe import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json /* * Tests for SemesterId */ class SemesterIdTest: FunSpec( { test("should create semesterId with valid year and semester | CSW-121") { val semesterId = SemesterId("2010B") semesterId.toString() shouldBeEqual "2010B" semesterId.year shouldBe 2010 semesterId.semester shouldBe Semester.B } test("should throw exception if semester is invalid | CSW-121") { val ex = shouldThrow<IllegalArgumentException> { SemesterId("2010C") } ex.message shouldBe("Failed to parse semester C. Semester ID must be A or B.") } test("should throw exception if year is invalid | CSW-121") { val ex = shouldThrow<IllegalArgumentException> { SemesterId("ABCDA") } ex.message?.contains("could not be converted") shouldBe true } test("should throw exception if SemesterId is not 5 long") { val ex = shouldThrow<IllegalArgumentException> { SemesterId("1000000000A") } ex.message?.startsWith("Semester ID must be length") shouldBe true } test("Should serialize and deserialize semesterId") { val semesterId = SemesterId("2010B") val json = Json.encodeToString(semesterId) //println("json: $json") val objIn = Json.decodeFromString<SemesterId>(json) //println("objIn: $objIn") objIn shouldBe semesterId } } )
0
Kotlin
0
0
84aadf8d6d73e27770b292f00b69a36fdf8e097f
1,706
kotlin-csw
Apache License 2.0
app/src/main/java/com/rerere/iwara4a/ui/screen/index/page/RecommendPage.kt
jiangdashao
349,642,808
false
null
package com.rerere.iwara4a.ui.screen.index.page import androidx.compose.animation.Crossfade import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Error import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.google.accompanist.flowlayout.FlowRow import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.rerere.iwara4a.R import com.rerere.iwara4a.data.model.detail.video.toMediaPreview import com.rerere.iwara4a.ui.component.MediaPreviewCard import com.rerere.iwara4a.ui.component.RandomLoadingAnim import com.rerere.iwara4a.ui.component.basic.Centered import com.rerere.iwara4a.ui.screen.index.IndexViewModel import com.rerere.iwara4a.ui.util.adaptiveGridCell import com.rerere.iwara4a.ui.util.stringResourceByName import com.rerere.iwara4a.util.DataState import com.rerere.iwara4a.util.onError import com.rerere.iwara4a.util.onLoading import com.rerere.iwara4a.util.onSuccess import me.rerere.compose_setting.preference.rememberStringSetPreference @Composable fun RecommendPage( indexViewModel: IndexViewModel ) { val context = LocalContext.current fun refresh(tags: Set<String>) { indexViewModel.recommendVideoList(tags) } val allTags by indexViewModel.allRecommendTags.collectAsState() var tags by rememberStringSetPreference( key = "recommend_tag", default = emptySet() ) val recommendVideoList by indexViewModel.recommendVideoList.collectAsState() val refreshState = rememberSwipeRefreshState(recommendVideoList is DataState.Loading) var showSettingDialog by remember { mutableStateOf(false) } if (showSettingDialog) { AlertDialog( onDismissRequest = { showSettingDialog = false }, title = { Text("推荐标签设置") }, text = { allTags .onSuccess { FlowRow( mainAxisSpacing = 2.dp ) { it.forEach { FilterChip( selected = tags.contains(it), onClick = { tags = if (tags.contains(it)) { tags.toMutableSet().apply { remove(it) } } else { tags.toMutableSet().apply { add(it) } } }, label = { Text( text = stringResourceByName("tag_$it") ) } ) } } }.onLoading { Centered(Modifier.fillMaxWidth()) { CircularProgressIndicator() } }.onError { Centered( Modifier .clickable { indexViewModel.loadTags() } .fillMaxWidth() .padding(16.dp) ) { Text( text = "获取标签失败, 点击重试 ($it)" ) } } }, confirmButton = { TextButton( onClick = { showSettingDialog = false refresh(tags) } ) { Text(stringResource(R.string.confirm_button)) } }, dismissButton = { TextButton( onClick = { showSettingDialog = false } ) { Text(stringResource(R.string.cancel_button)) } } ) } LaunchedEffect(tags) { if (recommendVideoList is DataState.Empty) { refresh(tags) } } Scaffold( floatingActionButton = { FloatingActionButton( onClick = { showSettingDialog = true } ) { Icon(Icons.Outlined.Settings, null) } }, floatingActionButtonPosition = FabPosition.Center ) { innerPadding -> if (tags.isEmpty()) { Centered(Modifier.fillMaxSize()) { Text("请先选择你喜欢的标签") } } else { SwipeRefresh( modifier = Modifier .fillMaxSize() .padding(innerPadding), state = refreshState, onRefresh = { indexViewModel.recommendVideoList(tags) } ) { Crossfade(recommendVideoList) { recommendVideoList -> when (recommendVideoList) { is DataState.Success -> { LazyVerticalGrid( columns = adaptiveGridCell(), ) { items(recommendVideoList.readSafely() ?: emptyList()) { MediaPreviewCard( mediaPreview = it.toMediaPreview() ) } } } is DataState.Loading -> { RandomLoadingAnim() } is DataState.Error -> { Centered(Modifier.fillMaxSize()) { Icon(Icons.Outlined.Error, null) } } is DataState.Empty -> {} } } } } } }
8
Kotlin
39
636
5ec0ad6068d5f48bfb81d269f7e34e1f4b511ca5
7,076
iwara4a
Apache License 2.0
app/src/main/kotlin/vitalii/pankiv/dev/android/features/messages/presentation/MessagesRouter.kt
pankivV
679,640,982
false
null
package vitalii.pankiv.dev.android.features.messages.presentation interface MessagesRouter { fun showMessagesScreen() fun showMessageDetailsScreen(id: Long) }
0
Kotlin
0
0
3dbb32a879647a315e461f4c34b618f5df670a07
167
code-sample
Apache License 2.0
Project/src-ParserV1/edu.citadel.cprl/src/edu/citadel/cprl/Scope.kt
SoftMoore
525,070,814
false
{"Kotlin": 345664, "Assembly": 85379, "Batchfile": 6123, "Shell": 5812, "Java": 675}
package edu.citadel.cprl /** * This class encapsulates a scope in CPRL. */ class Scope(val scopeLevel : ScopeLevel) : HashMap<String, IdType>()
0
Kotlin
1
1
c2a02785f2a1e415a65d52e952046255bf009a6a
147
CPRL-Kt-2nd
The Unlicense
domain/teamplay-business-domain/src/main/kotlin/com/teamplay/domain/business/user/validator/CheckDuplicateUserNickname.kt
YAPP-16th
235,351,938
false
{"Kotlin": 79474, "Java": 5820, "Shell": 224}
package com.teamplay.domain.business.user.validator import com.teamplay.core.function.ValidatorWithError import com.teamplay.domain.business.user.error.NicknameAlreadyRegisteredError import com.teamplay.domain.database.jpa.user.repository.UserRepository class CheckDuplicateUserNickname( private val repository: UserRepository ): ValidatorWithError<String>(NicknameAlreadyRegisteredError()) { override fun apply(nickname: String): Boolean { return !repository.existsByNickname(nickname) } }
2
Kotlin
0
1
a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2
513
Team_Android_2_Backend
MIT License
app/src/main/java/com/hashim/instagram/ui/signup/SignupActivity.kt
vibhusharma101
263,597,893
true
{"Kotlin": 206711}
package com.hashim.instagram.ui.signup import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.lifecycle.Observer import com.hashim.instagram.R import com.hashim.instagram.di.component.ActivityComponent import com.hashim.instagram.ui.base.BaseActivity import com.hashim.instagram.ui.main.MainActivity import com.hashim.instagram.utils.common.Event import com.hashim.instagram.utils.common.Status import kotlinx.android.synthetic.main.activity_signup.* class SignupActivity : BaseActivity<SignupViewModel>(){ override fun provideLayoutId(): Int = R.layout.activity_signup override fun injectDependencies(activityComponent: ActivityComponent) { activityComponent.inject(this) } override fun setupView(savedInstanceState: Bundle?) { et_password.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { viewModel.onPasswordChange(s.toString()) } }) et_email.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { viewModel.onEmailChange(s.toString()) } }) et_name.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { viewModel.onNameChange(s.toString()) } }) bt_login.setOnClickListener { viewModel.doSignup() } } override fun setupObservers() { super.setupObservers() viewModel.fullNameField.observe(this, Observer { if(et_name.text.toString() != it){ viewModel.fullNameField.postValue(it) } }) viewModel.nameValidation.observe(this, Observer { when(it.status) { Status.ERROR -> layout_name.error = it.data?.run { getString(it.data) } else -> layout_name.isErrorEnabled = false } }) viewModel.emailField.observe(this, Observer { if(et_email.text.toString() != it){ viewModel.emailField.postValue(it) } }) viewModel.emailValidation.observe(this, Observer { when(it.status) { Status.ERROR -> layout_email.error = it.data?.run { getString(it.data) } else -> layout_email.isErrorEnabled = false } }) viewModel.passwordField.observe(this, Observer { if(et_password.text.toString() != it){ viewModel.passwordField.postValue(it) } }) viewModel.passwordValidation.observe(this, Observer { when(it.status) { Status.ERROR -> layout_password.error = it.data?.run { getString(it.data) } else -> layout_password.isErrorEnabled = false } }) viewModel.launchMain.observe(this, Observer<Event<Map<String,String>>> { it.getIfNotHandled()?.run { startActivity(Intent(applicationContext,MainActivity::class.java)) } }) viewModel.siginningUp.observe(this, Observer { pb_loading.visibility = if(it) View.VISIBLE else View.GONE }) } }
0
null
0
1
3bbb5afe2900326638fec800546ec3b3ddab0284
4,029
Instagram
MIT License
app/src/main/java/com/gram/pictory/ui/login/LoginViewModel.kt
notmyfault02
178,123,874
false
null
package com.gram.pictory.ui.login import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.MutableLiveData import android.widget.Toast import com.google.gson.JsonObject import com.gram.pictory.connect.Connecter import com.gram.pictory.database.Auth import com.gram.pictory.database.AuthDatabase import com.gram.pictory.model.LoginModel import com.gram.pictory.util.SingleLiveEvent import com.gram.pictory.util.saveToken import org.jetbrains.anko.doAsync import retrofit2.Call import retrofit2.Callback import retrofit2.Response class LoginViewModel(val app: Application) : AndroidViewModel(app) { val loginId = MutableLiveData<String>() val loginPw = MutableLiveData<String>() val goMainEvent = SingleLiveEvent<Any>() val goRegisterEvent = SingleLiveEvent<Any>() fun doLogin() { if (loginId.isValueBlank()) { Toast.makeText(app.baseContext, "아이디를 입력해주세요", Toast.LENGTH_SHORT).show() } else if(loginPw.isValueBlank()) { Toast.makeText(app.baseContext, "비밀번호를 입력해주세요", Toast.LENGTH_SHORT).show() } else { val auth = Auth(loginId.value!!, loginPw.value!!) val json = JsonObject().apply { addProperty("id", loginId.value) addProperty("pw", loginPw.value) } Connecter.api.login(json).enqueue(object : Callback<LoginModel> { override fun onResponse(call: Call<LoginModel>, response: Response<LoginModel>) { doAsync { AuthDatabase.getInstance(app.baseContext)!! .getAuthDao().insert(auth) } saveToken(app.baseContext, response.body()!!.token) toMain() } override fun onFailure(call: Call<LoginModel>?, t: Throwable?) { Toast.makeText(app.baseContext, "로그인 실패", Toast.LENGTH_SHORT).show() } }) } } fun toSignUpBtn() = goRegisterEvent.call() fun toMain() = goMainEvent.call() fun MutableLiveData<String>.isValueBlank() = this.value.isNullOrBlank() }
0
Kotlin
0
1
503ee703d906ee61c90ac737f3cfad86d662c20d
2,214
Pictory_Master
MIT License
src/main/kotlin/ru/kontur/cdp4k/rpc/RpcSession.kt
kinfra
758,916,083
false
{"Kotlin": 93843}
package ru.kontur.cdp4k.rpc import com.fasterxml.jackson.databind.node.ObjectNode import ru.kontur.cdp4k.connection.ConnectionClosedException /** * Client side of CDP session. */ interface RpcSession { val connection: RpcConnection /** * Execute an RPC request. * * @throws RpcErrorException if server signals an error * @throws ConnectionClosedException if this session is disconnected * @throws IllegalStateException if this session is closed */ suspend fun executeRequest(methodName: String, params: ObjectNode): ObjectNode fun subscribe(methodName: String, callback: (ObjectNode) -> Unit): EventSubscription interface EventSubscription : AutoCloseable }
0
Kotlin
0
0
0b7a7a3072a918e49588df4b7843e7c6dc7c350a
717
cdp4k
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/ui/compose/DisposableLifecycleCallbacks.kt
horizontalsystems
142,825,178
false
null
package com.wikicious.app.ui.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner // see https://developer.android.com/jetpack/compose/side-effects#disposableeffect @Composable fun DisposableLifecycleCallbacks( lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, onStart: (() -> Unit) = {}, onResume: () -> Unit = {}, onPause: () -> Unit = {}, onStop: () -> Unit = {}, ) { // Safely update the current lambdas when a new one is provided val currentOnStart by rememberUpdatedState(onStart) val currentOnResume by rememberUpdatedState(onResume) val currentOnPause by rememberUpdatedState(onPause) val currentOnStop by rememberUpdatedState(onStop) // If `lifecycleOwner` changes, dispose and reset the effect DisposableEffect(lifecycleOwner) { // Create an observer that triggers our remembered callbacks val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_START -> currentOnStart() Lifecycle.Event.ON_STOP -> currentOnStop() Lifecycle.Event.ON_RESUME -> currentOnResume() Lifecycle.Event.ON_PAUSE -> currentOnPause() else -> Unit } } // Add the observer to the lifecycle lifecycleOwner.lifecycle.addObserver(observer) // When the effect leaves the Composition, remove the observer onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } }
153
null
346
805
399fd8dc84c249dd1094fee0a7a043ec5e4ffa90
1,851
unstoppable-wallet-android
MIT License
app/src/main/java/com/example/camera/page/LoadingPage.kt
Redari-Es
687,263,456
false
{"Kotlin": 87619}
package com.example.camera.page import androidx.compose.animation.Animatable import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.foundation.layout.* import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.sp import com.example.camera.util.LogUtil //@Preview(showBackground=true) @Composable fun LoadingPage(getState:Boolean) :String{ var state by remember { mutableStateOf(getState) } LogUtil.d("Loading", "state") var ok by remember { mutableStateOf(false) } val color01 = Color(0x3c, 0x91, 0xfa) val color02 = Color(0xcf, 0x2f, 0xfa) val color1 = remember { Animatable(Color(0x00, 0x00, 0x00, 0)) } val color2 = remember { Animatable(Color(0x00, 0x00, 0x00, 0)) } LogUtil.d("color", "init color") var change by remember {mutableStateOf(false)} change=state if(change){ LaunchedEffect(state) { color1.animateTo(color01) color2.animateTo(color02) LogUtil.d("blender1", "state") change=false state = false } if(!state){ LaunchedEffect(ok) { color1.animateTo(color02) color2.animateTo(color01) LogUtil.d("blender2", "ok") ok=false } } change=false } AnimatedVisibility( visible = state, enter = fadeIn( animationSpec = tween( durationMillis = 3000, delayMillis = 200, easing = LinearOutSlowInEasing ), ).apply { LogUtil.d("blender","Enter") ok=true change=ok LogUtil.d("Status","Next is Exit") }, exit = fadeOut( animationSpec = tween( durationMillis = 3000, delayMillis = 200, easing = LinearOutSlowInEasing ), ).apply{ ok=false LogUtil.d("blender","Exit") LogUtil.d("Status","Next is None") } ) { Box(modifier = Modifier.fillMaxSize()) { // Column( modifier = Modifier .fillMaxWidth() .align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text("怪物", color = color1.value, fontSize = 80.sp, fontWeight = FontWeight.Bold) Text( "卡美啦", color = color2.value, fontSize = 100.sp, fontWeight = FontWeight.Bold ) } } } return "MyCameraX" }
2
Kotlin
0
1
dc912fb5f982efcaff890f0d5ec9e8938478d407
3,569
Camera
MIT License
wui/src/main/kotlin/pages/exercise/editor/tsl/TSLTestComp.kt
kspar
160,047,508
false
null
package pages.exercise.editor.tsl import Icons import components.form.SelectComp import debug import kotlinx.coroutines.await import libheaders.MCollapsibleInstance import libheaders.Materialize import libheaders.open import pages.exercise.editor.tsl.tests.TSLFunctionCallTest import pages.exercise.editor.tsl.tests.TSLProgramExecutionTest import rip.kspar.ezspa.* import template import tsl.common.model.* class TSLTestComp( private val initialModel: Test?, private val onUpdate: () -> Unit, parent: Component ) : Component(parent) { companion object { private const val DEFAULT_TITLE = "Uus test" } private var activeTitle = when { initialModel == null -> DEFAULT_TITLE initialModel.name == null -> getTestTypeFromModel(initialModel).defaultTestTitle else -> initialModel.name } private val testType = SelectComp( "Testi tüüp", TestType.values().map { SelectComp.Option(it.optionName, it.name, initialModel?.let { model -> getTestTypeFromModel(model) } == it) }, hasEmptyOption = true, onOptionChange = ::changeTestType, parent = this ) private val contentDst = IdGenerator.nextId() private var content: TSLTestComponent? = null private lateinit var collapsible: MCollapsibleInstance var isOpen = false private set override val children: List<Component> get() = listOfNotNull(testType, content) override fun create() = doInPromise { content = initialModel?.let { createContentComp(getTestTypeFromModel(it), it) } } override fun render() = template( """ <ul class="ez-collapsible collapsible"> <li> <div class="collapsible-header"> <ez-tsl-test-header-left> <ez-collapsible-icon>{{{titleIcon}}}</ez-collapsible-icon> <ez-collapsible-title>{{title}}</ez-collapsible-title> </ez-tsl-test-header-left> <ez-tsl-test-header-right> <ez-icon-action ez-tsl-test-menu title="{{menuLabel}}" class="waves-effect dropdown-trigger icon-med" tabindex="0" data-target="ez-tsl-test-{{testDst}}">{{{menuIcon}}}</ez-icon-action> </ez-tsl-test-header-right> </div> <div class="collapsible-body"> <ez-dst id="{{testTypeDst}}"></ez-dst> <ez-dst id="{{testContentDst}}"></ez-dst> </div> </li> </ul> <!-- Menu structure --> <ul id="ez-tsl-test-{{testDst}}" class="dropdown-content"> {{#actions}} <li><span ez-action="{{id}}">{{{iconHtml}}}{{text}}</span></li> {{/actions}} </ul> """.trimIndent(), "title" to activeTitle, "testTypeDst" to testType.dstId, "testContentDst" to contentDst, "testDst" to dstId, "actions" to TestAction.values().map { mapOf( "id" to it.name, "iconHtml" to it.icon, "text" to it.title, ) }, "titleIcon" to Icons.robot, "menuLabel" to "Muuda...", "menuIcon" to Icons.dotsVertical, ) override fun postRender() { getElemById(dstId).getElemBySelector("[ez-tsl-test-menu]").onVanillaClick(false) { // Stop click from propagating to collapsible header it.stopPropagation() } TestAction.values().forEach { action -> getElemById(dstId).getElemBySelector("[ez-action=\"${action.name}\"]").onVanillaClick(false) { it.stopPropagation() debug { "Action ${action.name} on test $activeTitle" } action.action() } } collapsible = Materialize.Collapsible.init( getElemById(dstId).getElemsByClass("ez-collapsible").single(), objOf( "onOpenStart" to { isOpen = true }, "onCloseStart" to { isOpen = false }, ) ) Materialize.Dropdown.init( getElemById(dstId).getElemBySelector("[ez-tsl-test-menu]"), objOf("constrainWidth" to false, "coverTrigger" to false) ) } fun getTestModel(): Test? { return content?.getTSLModel() } fun open() = collapsible.open() private suspend fun changeTestType(newTypeId: String?) { debug { "Test type changed to: $newTypeId" } val newType = newTypeId?.let { TestType.valueOf(it) } // Change title if previous one was default if (TestType.defaultTitles.contains(activeTitle)) { changeTitle(newType?.defaultTestTitle ?: DEFAULT_TITLE) } content = if (newType != null) { content?.destroy() createContentComp(newType, null).also { it.createAndBuild().await() } } else { content?.destroy() null } // Test type changed onUpdate() } private fun changeTitle(newTitle: String) { activeTitle = newTitle getElemById(dstId).getElemBySelector("ez-collapsible-title").textContent = newTitle } private fun getTestTypeFromModel(test: Test) = when (test) { is FunctionCallsFunctionTest -> TODO() is FunctionCallsPrintTest -> TODO() is FunctionContainsKeywordTest -> TODO() is FunctionContainsLoopTest -> TODO() is FunctionContainsReturnTest -> TODO() is FunctionContainsTryExceptTest -> TODO() is FunctionDefinesFunctionTest -> TODO() is FunctionExecutionTest -> TestType.FUNCTION_EXECUTION is FunctionImportsModuleTest -> TODO() is FunctionIsPureTest -> TODO() is FunctionIsRecursiveTest -> TODO() is ProgramExecutionTest -> TestType.PROGRAM_EXECUTION is ProgramCallsFunctionTest -> TODO() is ProgramCallsPrintTest -> TODO() is ProgramContainsKeywordTest -> TODO() is ProgramContainsLoopTest -> TODO() is ProgramContainsTryExceptTest -> TODO() is ProgramDefinesFunctionTest -> TODO() is ProgramImportsModuleTest -> TODO() } private suspend fun createContentComp(type: TestType, model: Test?): TSLTestComponent = // it might be better to show/hide content comps to preserve inputs when (type) { TestType.PROGRAM_EXECUTION -> TSLProgramExecutionTest(model?.let { it as ProgramExecutionTest }, onUpdate, this, contentDst) TestType.FUNCTION_EXECUTION -> TSLFunctionCallTest(model?.let { it as FunctionExecutionTest }, onUpdate, this, contentDst) } enum class TestType(val optionName: String, val defaultTestTitle: String) { PROGRAM_EXECUTION("Programmi väljund", "Programmi väljundi test"), FUNCTION_EXECUTION("Funktsiooni tagastus", "Funktsiooni tagastuse test"), ; companion object { val defaultTitles = TestType.values().map { it.defaultTestTitle } + DEFAULT_TITLE } } enum class TestAction(val title: String, val icon: String, val action: () -> Unit) { RENAME("Muuda pealkirja", Icons.edit, {}), MOVE("Liiguta", Icons.reorder, {}), DELETE("Kustuta", Icons.delete, {}), } } abstract class TSLTestComponent( parent: Component?, dstId: String = IdGenerator.nextId() ) : Component(parent, dstId) { abstract fun getTSLModel(): Test }
1
Kotlin
2
4
54d31d4d1d2a393ecefa02f6ec5e7c998b0adf7c
7,655
easy
MIT License
oneinchkit/src/main/java/io/definenulls/oneinchkit/OneInchKit.kt
toEther
677,364,903
false
null
package io.definenulls.oneinchkit import com.google.gson.annotations.SerializedName import io.definenulls.ethereumkit.core.EthereumKit import io.definenulls.ethereumkit.core.toHexString import io.definenulls.ethereumkit.models.Address import io.definenulls.ethereumkit.models.Chain import io.definenulls.ethereumkit.models.GasPrice import io.definenulls.oneinchkit.contracts.OneInchContractMethodFactories import io.definenulls.oneinchkit.decorations.OneInchMethodDecorator import io.definenulls.oneinchkit.decorations.OneInchTransactionDecorator import java.math.BigInteger import java.util.* class OneInchKit( private val evmKit: EthereumKit, private val service: OneInchService ) { val routerAddress: Address = when (evmKit.chain) { Chain.Ethereum, Chain.BinanceSmartChain, Chain.Komerco, Chain.Optimism, Chain.ArbitrumOne, Chain.Gnosis, Chain.Fantom, Chain.Avalanche -> Address("0x1111111254eeb25477b68fb85ed929f73a960582") else -> throw IllegalArgumentException("Invalid Chain: ${evmKit.chain.id}") } fun getApproveCallDataAsync(tokenAddress: Address, amount: BigInteger) = service.getApproveCallDataAsync(tokenAddress, amount) fun getQuoteAsync( fromToken: Address, toToken: Address, amount: BigInteger, protocols: List<String>? = null, gasPrice: GasPrice? = null, complexityLevel: Int? = null, connectorTokens: List<String>? = null, gasLimit: Long? = null, mainRouteParts: Int? = null, parts: Int? = null ) = service.getQuoteAsync( fromToken, toToken, amount, protocols, gasPrice, complexityLevel, connectorTokens, gasLimit, mainRouteParts, parts ) fun getSwapAsync( fromToken: Address, toToken: Address, amount: BigInteger, slippagePercentage: Float, protocols: List<String>? = null, recipient: Address? = null, gasPrice: GasPrice? = null, burnChi: Boolean = false, complexityLevel: Int? = null, connectorTokens: List<String>? = null, allowPartialFill: Boolean = false, gasLimit: Long? = null, parts: Int? = null, mainRouteParts: Int? = null ) = service.getSwapAsync( fromToken, toToken, amount, evmKit.receiveAddress, slippagePercentage, protocols, recipient, gasPrice, burnChi, complexityLevel, connectorTokens, allowPartialFill, gasLimit, parts, mainRouteParts ) companion object { fun getInstance(evmKit: EthereumKit): OneInchKit { val service = OneInchService(evmKit.chain) return OneInchKit(evmKit, service) } fun addDecorators(evmKit: EthereumKit) { evmKit.addMethodDecorator(OneInchMethodDecorator(OneInchContractMethodFactories)) evmKit.addTransactionDecorator(OneInchTransactionDecorator(evmKit.receiveAddress)) } } } data class Token( val symbol: String, val name: String, val decimals: Int, val address: String, val logoURI: String ) data class Quote( val fromToken: Token, val toToken: Token, val fromTokenAmount: BigInteger, val toTokenAmount: BigInteger, @SerializedName("protocols") val route: List<Any>, val estimatedGas: Long ) { override fun toString(): String { return "Quote {fromToken: ${fromToken.name}, toToken: ${toToken.name}, fromTokenAmount: $fromTokenAmount, toTokenAmount: $toTokenAmount}" } } data class SwapTransaction( val from: Address, val to: Address, val data: ByteArray, val value: BigInteger, val gasPrice: Long?, val maxFeePerGas: Long?, val maxPriorityFeePerGas: Long?, @SerializedName("gas") val gasLimit: Long ) { override fun toString(): String { return "SwapTransaction {\nfrom: ${from.hex}, \nto: ${to.hex}, \ndata: ${data.toHexString()}, \nvalue: $value, \ngasPrice: $gasPrice, \ngasLimit: $gasLimit\n}" } } data class Swap( val fromToken: Token, val toToken: Token, val fromTokenAmount: BigInteger, val toTokenAmount: BigInteger, @SerializedName("protocols") val route: List<Any>, @SerializedName("tx") val transaction: SwapTransaction ) { override fun toString(): String { return "Swap {\nfromToken: ${fromToken.name}, \ntoToken: ${toToken.name}, \nfromTokenAmount: $fromTokenAmount, \ntoTokenAmount: $toTokenAmount, \ntx: $transaction\n}" } } data class ApproveCallData( val data: ByteArray, val gasPrice: Long, val to: Address, val value: BigInteger ) { override fun equals(other: Any?): Boolean { return when { this === other -> true other is ApproveCallData -> to == other.to && value == other.value && data.contentEquals(other.data) else -> false } } override fun hashCode(): Int { return Objects.hash(to, value, data) } override fun toString(): String { return "ApproveCallData {\nto: ${to.hex}, \nvalue: $value, \ndata: ${data.toHexString()}\n}" } }
0
Kotlin
0
0
8a5c1090e305af60b8b0e5e04e8d7853f3cad3ce
5,290
ethereum-kit-android
MIT License
api/src/main/kotlin/io/codegeet/sandbox/Configuration.kt
codegeet
704,806,290
false
{"Kotlin": 17709, "Shell": 2861, "Dockerfile": 2688}
package io.codegeet.sandbox import com.fasterxml.jackson.module.kotlin.KotlinModule import com.github.dockerjava.api.DockerClient import com.github.dockerjava.core.DefaultDockerClientConfig import com.github.dockerjava.core.DockerClientImpl import com.github.dockerjava.httpclient5.ApacheDockerHttpClient import io.codegeet.sandbox.auth.Token import io.codegeet.sandbox.auth.TokenRepository import io.codegeet.sandbox.container.ContainerConfiguration import org.springframework.boot.ApplicationRunner import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.net.URI import java.time.Duration @Configuration class Configuration { @Bean fun jackson2ObjectMapperBuilderCustomizer(): Jackson2ObjectMapperBuilderCustomizer { return Jackson2ObjectMapperBuilderCustomizer { builder -> builder.modulesToInstall(KotlinModule.Builder().build()) } } @Bean fun databaseInitializer(tokenRepository: TokenRepository) = ApplicationRunner { tokenRepository.save(Token("<KEY>")) } // todo Configure Docker Client similar to https://github.com/bmuschko/gradle-docker-plugin/blob/e5abdc28e483905bacd49ae49738482dbd567a60/src/main/java/com/bmuschko/gradle/docker/internal/services/DockerClientService.java#L75 @Bean fun dockerClient(): DockerClient { val config = DefaultDockerClientConfig.createDefaultConfigBuilder().build() val dockerHttpClient = ApacheDockerHttpClient.Builder() .dockerHost(config.dockerHost) .sslConfig(config.sslConfig) .maxConnections(50) .connectionTimeout(Duration.ofSeconds(15)) .responseTimeout(Duration.ofSeconds(30)) .build() val dockerClient = DockerClientImpl.getInstance(config, dockerHttpClient) try { dockerClient.pingCmd().exec() } catch (e: Exception) { throw RuntimeException("Docker client initialization failed. Docker host: '${config.dockerHost}'.", e) } return dockerClient } @Bean fun apiConfiguration(): ContainerConfiguration { return ContainerConfiguration() } }
4
Kotlin
0
1
43c550c3a6e5f2ec3e9c673f6656c8553e885e9e
2,305
codegeet
MIT License
src/main/kotlin/com/uchuhimo/konf/source/Provider.kt
slomkowski
183,307,337
true
{"Kotlin": 559761, "Java": 10367}
/* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uchuhimo.konf.source import com.uchuhimo.konf.source.hocon.HoconProvider import com.uchuhimo.konf.source.json.JsonProvider import com.uchuhimo.konf.source.properties.PropertiesProvider import com.uchuhimo.konf.source.toml.TomlProvider import com.uchuhimo.konf.source.xml.XmlProvider import com.uchuhimo.konf.source.yaml.YamlProvider import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.TransportCommand import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import java.io.File import java.io.FileInputStream import java.io.InputStream import java.io.Reader import java.net.URL import java.nio.file.Paths /** * Provides source from various input format. */ interface Provider { /** * Returns a new source from specified reader. * * @param reader specified reader for reading character streams * @return a new source from specified reader */ fun fromReader(reader: Reader): Source /** * Returns a new source from specified input stream. * * @param inputStream specified input stream of bytes * @return a new source from specified input stream */ fun fromInputStream(inputStream: InputStream): Source /** * Returns a new source from specified file. * * @param file specified file * @return a new source from specified file */ fun fromFile(file: File): Source { return file.inputStream().buffered().use { inputStream -> fromInputStream(inputStream).apply { addContext("file", file.toString()) } } } /** * Returns a new source from specified file path. * * @param file specified file path * @return a new source from specified file path */ fun fromFile(file: String): Source = fromFile(File(file)) /** * Returns a new source from specified string. * * @param content specified string * @return a new source from specified string */ fun fromString(content: String): Source = fromReader(content.reader()).apply { addContext("content", "\"\n$content\n\"") } /** * Returns a new source from specified byte array. * * @param content specified byte array * @return a new source from specified byte array */ fun fromBytes(content: ByteArray): Source = fromInputStream(content.inputStream()) /** * Returns a new source from specified portion of byte array. * * @param content specified byte array * @param offset the start offset of the portion of the array to read * @param length the length of the portion of the array to read * @return a new source from specified portion of byte array */ fun fromBytes(content: ByteArray, offset: Int, length: Int): Source = fromInputStream(content.inputStream(offset, length)) /** * Returns a new source from specified url. * * @param url specified url * @return a new source from specified url */ fun fromUrl(url: URL): Source { // from com.fasterxml.jackson.core.JsonFactory._optimizedStreamFromURL in version 2.8.9 if (url.protocol == "file") { val host = url.host if (host == null || host.isEmpty()) { val path = url.path if (path.indexOf('%') < 0) { return fromInputStream(FileInputStream(url.path)).apply { addContext("url", url.toString()) } } } } return fromInputStream(url.openStream()).apply { addContext("url", url.toString()) } } /** * Returns a new source from specified url string. * * @param url specified url string * @return a new source from specified url string */ fun fromUrl(url: String): Source = fromUrl(URL(url)) /** * Returns a new source from specified resource. * * @param resource path of specified resource * @return a new source from specified resource */ fun fromResource(resource: String): Source { val loader = Thread.currentThread().contextClassLoader val e = loader.getResources(resource) if (!e.hasMoreElements()) { throw SourceNotFoundException("resource not found on classpath: $resource") } val sources = mutableListOf<Source>() while (e.hasMoreElements()) { val url = e.nextElement() val source = fromUrl(url) sources.add(source) } return sources.reduce(Source::withFallback).apply { addContext("resource", resource) } } /** * Returns a new source from a specified git repository. * * @param repo git repository * @param file file in the git repository * @param dir local directory of the git repository * @param branch the initial branch * @param action additional action when cloning/pulling * @return a new source from a specified git repository */ fun fromGit( repo: String, file: String, dir: String? = null, branch: String = Constants.HEAD, action: TransportCommand<*, *>.() -> Unit = {} ): Source { return (dir?.let(::File) ?: createTempDir(prefix = "local_git_repo")).let { directory -> if (directory.list { _, name -> name == ".git" }.isEmpty()) { Git.cloneRepository().apply { setURI(repo) setDirectory(directory) setBranch(branch) this.action() }.call().close() } else { Git.open(directory).use { git -> val uri = URIish(repo) val remoteName = git.remoteList().call().firstOrNull { it.urIs.contains(uri) }?.name ?: throw InvalidRemoteRepoException(repo, directory.path) git.pull().apply { remote = remoteName remoteBranchName = branch this.action() }.call() } } fromFile(Paths.get(directory.path, file).toFile()).apply { addContext("repo", repo) addContext("file", file) addContext("dir", directory.path) addContext("branch", branch) } } } /** * Returns a provider providing sources that applying the given [transform] function. * * @param transform the given transformation function * @return a provider providing sources that applying the given [transform] function */ fun map(transform: (Source) -> Source): Provider { return object : Provider { override fun fromReader(reader: Reader): Source = [email protected](reader).let(transform) override fun fromInputStream(inputStream: InputStream): Source = [email protected](inputStream).let(transform) override fun fromFile(file: File): Source = [email protected](file).let(transform) override fun fromFile(file: String): Source = [email protected](file).let(transform) override fun fromString(content: String): Source = [email protected](content).let(transform) override fun fromBytes(content: ByteArray): Source = [email protected](content).let(transform) override fun fromBytes(content: ByteArray, offset: Int, length: Int): Source = [email protected](content, offset, length).let(transform) override fun fromUrl(url: URL): Source = [email protected](url).let(transform) override fun fromUrl(url: String): Source = [email protected](url).let(transform) override fun fromResource(resource: String): Source = [email protected](resource).let(transform) } } companion object { private val extensionToProvider = mutableMapOf( "conf" to HoconProvider, "json" to JsonProvider, "properties" to PropertiesProvider, "toml" to TomlProvider, "xml" to XmlProvider, "yml" to YamlProvider, "yaml" to YamlProvider ) /** * Register extension with the corresponding provider. * * @param extension the file extension * @param provider the corresponding provider */ fun registerExtension(extension: String, provider: Provider) { extensionToProvider[extension] = provider } /** * Unregister the given extension. * * @param extension the file extension */ fun unregisterExtension(extension: String): Provider? = extensionToProvider.remove(extension) /** * Returns corresponding provider based on extension. * * Returns null if the specific extension is unregistered. * * @param extension the file extension * @return the corresponding provider based on extension */ fun of(extension: String): Provider? = extensionToProvider[extension] } }
0
Kotlin
0
0
7246d880e56e2efe2671e80f7e14be7d310e6e81
10,102
konf
Apache License 2.0
domain/src/main/java/com/example/kdotdi/domain/mapper/CvPositionsMapper.kt
kdotdi
287,327,045
false
null
package com.example.kdotdi.domain.mapper import com.example.kdotdi.data.model.CvPositionsDTO import com.example.kdotdi.domain.entity.CvPositions fun CvPositionsDTO.toEntity() = CvPositions( positions = positions?.map { it.toEntity() } ) fun CvPositions.toDTO() = CvPositionsDTO( positions = positions?.map { it.toDTO() } )
0
Kotlin
0
0
33ed7ac4d51929e0769576cf94a3128b666598aa
357
my-cv-maintainer
MIT License
freetype-async/src/test/kotlin/ktx/freetype/async/freetypeAsyncTest.kt
serandel
239,540,763
true
{"Kotlin": 784252, "GLSL": 68}
package ktx.freetype.async import com.badlogic.gdx.Gdx import com.badlogic.gdx.assets.loaders.resolvers.ClasspathFileHandleResolver import com.badlogic.gdx.backends.lwjgl.LwjglFiles import com.badlogic.gdx.backends.lwjgl.LwjglNativesLoader import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader import com.nhaarman.mockitokotlin2.mock import ktx.async.`coroutine test` import ktx.async.`destroy coroutines context` import ktx.async.assets.AssetStorage import ktx.freetype.freeTypeFontParameters import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test /** * Tests FreeType font loading utilities. Uses Hack font for testing. See https://github.com/source-foundry/Hack for * font details. */ class FreeTypeAsyncTest { private val ttfFile = "ktx/freetype/async/hack.ttf" private val otfFile = "ktx/freetype/async/hack.otf" @Test fun `should register FreeType font loaders`() = `coroutine test`(concurrencyLevel = 1) { val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() assertTrue(assetStorage.getLoader<FreeTypeFontGenerator>() is FreeTypeFontGeneratorLoader) assertTrue(assetStorage.getLoader<BitmapFont>(".ttf") is FreetypeFontLoader) assertTrue(assetStorage.getLoader<BitmapFont>(".otf") is FreetypeFontLoader) } @Test fun `should register FreeType font loaders with custom extensions`() = `coroutine test`(concurrencyLevel = 1) { val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders(fileExtensions = arrayOf(".custom")) assertTrue(assetStorage.getLoader<FreeTypeFontGenerator>() is FreeTypeFontGeneratorLoader) assertTrue(assetStorage.getLoader<BitmapFont>(".custom") is FreetypeFontLoader) // Should not register loader for unlisted extensions: assertFalse(assetStorage.getLoader<BitmapFont>(".ttf") is FreetypeFontLoader) assertFalse(assetStorage.getLoader<BitmapFont>(".otf") is FreetypeFontLoader) } @Test fun `should register FreeType font loaders with default loader override`() = `coroutine test`(concurrencyLevel = 1) { val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders(replaceDefaultBitmapFontLoader = true) assertTrue(assetStorage.getLoader<FreeTypeFontGenerator>() is FreeTypeFontGeneratorLoader) assertTrue(assetStorage.getLoader<BitmapFont>() is FreetypeFontLoader) } @Test fun `should load OTF file into BitmapFont`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.loadFreeTypeFont(otfFile) val font = assetStorage.get<BitmapFont>(otfFile) assertTrue(font is BitmapFont) assertSame(asset, font) } } @Test fun `should load OTF file into BitmapFont with custom params`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.loadFreeTypeFont(otfFile) { size = 12 borderWidth = 1f } val font = assetStorage.get<BitmapFont>(otfFile) assertTrue(font is BitmapFont) assertSame(asset, font) } } @Test fun `should load TTF file into BitmapFont`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.loadFreeTypeFont(ttfFile) val font = assetStorage.get<BitmapFont>(ttfFile) assertTrue(font is BitmapFont) assertSame(asset, font) } } @Test fun `should load TTF file into BitmapFont with custom params`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.loadFreeTypeFont(ttfFile) { size = 12 borderWidth = 1f } val font = assetStorage.get<BitmapFont>(ttfFile) assertTrue(font is BitmapFont) assertSame(asset, font) } } @Test fun `should use FreeType loader to load OTF file into BitmapFont`() = `coroutine test`(concurrencyLevel = 1) { async -> // Note that this method uses "raw" AssetStorage API without font loading utilities. val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.load<BitmapFont>(otfFile, parameters = freeTypeFontParameters(otfFile)) val font = assetStorage.get<BitmapFont>(otfFile) assertTrue(font is BitmapFont) assertSame(font, asset) } } @Test fun `should use FreeType loader to load TTF file into BitmapFont`() = `coroutine test`(concurrencyLevel = 1) { async -> // Note that this method uses "raw" AssetStorage API without font loading utilities. val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val asset = assetStorage.load<BitmapFont>(ttfFile, parameters = freeTypeFontParameters(ttfFile)) val font = assetStorage.get<BitmapFont>(ttfFile) assertTrue(font is BitmapFont) assertSame(font, asset) } } @Test fun `should load OTF file into FreeTypeFontGenerator`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val fontGenerator = assetStorage.load<FreeTypeFontGenerator>(otfFile) assertNotNull(fontGenerator) assertSame(fontGenerator, assetStorage.get<FreeTypeFontGenerator>(otfFile)) } } @Test fun `should load TTF file into FreeTypeFontGenerator`() = `coroutine test`(concurrencyLevel = 1) { async -> val assetStorage = assetStorage() assetStorage.registerFreeTypeFontLoaders() async { val fontGenerator = assetStorage.load<FreeTypeFontGenerator>(ttfFile) assertNotNull(fontGenerator) assertSame(fontGenerator, assetStorage.get<FreeTypeFontGenerator>(ttfFile)) } } @Before fun `setup LibGDX`() { LwjglNativesLoader.load() Gdx.gl = mock() Gdx.gl20 = Gdx.gl Gdx.graphics = mock() Gdx.files = LwjglFiles() } @After fun `cleanup LibGDX`() { Gdx.gl = null Gdx.gl20 = null Gdx.files = null Gdx.graphics = null `destroy coroutines context`() } private fun assetStorage() = AssetStorage(fileResolver = ClasspathFileHandleResolver()) }
0
Kotlin
0
0
cc6051ac6500f5b349095bcbf567b8d9d5446cc4
6,691
ktx
Creative Commons Zero v1.0 Universal
netswitchy/src/main/java/com/cyberland/netswitchy/proxy/IProxyStateChanged.kt
Era-CyberLabs
576,196,269
false
{"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472}
package com.bcm.netswitchy.proxy interface IProxyStateChanged { fun onProxyListChanged() {} fun onProxyConnectStarted() {} fun onProxyConnecting(proxyName: String, isOfficial: Boolean) {} fun onProxyConnectFinished() {} }
1
null
1
1
65a11e5f009394897ddc08f4252969458454d052
239
cyberland-android
Apache License 2.0
j2k/testData/fileOrElement/tryWithResource/Simple.kt
pawegio
33,691,693
true
{"Markdown": 32, "XML": 662, "Ant Build System": 34, "Ignore List": 8, "Kotlin": 17223, "Java": 4248, "Protocol Buffer": 4, "Text": 3580, "JavaScript": 61, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 116, "Groovy": 20, "Maven POM": 47, "Gradle": 68, "Java Properties": 9, "CSS": 3, "JFlex": 2, "Shell": 7, "Batchfile": 7}
import java.io.* public class C { throws(javaClass<IOException>()) fun foo() { ByteArrayInputStream(ByteArray(10)).use { stream -> println(stream.read()) } } }
0
Java
0
0
405038b2d8a759dd81f56cb39e9d41222b722ab7
180
kotlin
Apache License 2.0
architectury-1.18.2/common/src/main/kotlin/dev/fastmc/allocfix/IPatchedChunkRendererRegion.kt
FastMinecraft
574,390,605
false
{"Java": 402152, "Kotlin": 36348}
package dev.fastmc.allocfix import net.minecraft.client.render.block.BlockModelRenderer import net.minecraft.util.math.BlockPos import java.util.BitSet interface IPatchedChunkRendererRegion { fun getAmbientOcclusionCalculator(renderer: BlockModelRenderer): BlockModelRenderer.AmbientOcclusionCalculator val bitSet: BitSet val boxDimension: FloatArray val brightness: FloatArray val lights: IntArray val mutablePos1: BlockPos.Mutable }
1
null
1
1
0fc181373a2b25c081816604273a52cd0ab3a368
460
fastmc-allocfix
MIT License
worldline-connect-sdk/src/main/java/com/worldline/connect/sdk/client/android/network/NetworkResponse.kt
Worldline-Global-Collect
748,165,932
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Text": 1, "Markdown": 3, "Proguard": 1, "YAML": 1, "XML": 2, "Java": 85, "Kotlin": 40, "JSON": 12}
/* * Copyright (c) 2022 Worldline Global Collect B.V */ package com.worldline.connect.sdk.client.android.network sealed class NetworkResponse<T>( val data: T? = null, val apiErrorResponse: ApiErrorResponse? = null ) { class Success<T>(data: T) : NetworkResponse<T>(data) class ApiError<T>(apiErrorResponse: ApiErrorResponse?, data: T? = null) : NetworkResponse<T>(data, apiErrorResponse) } object UnknownNetworkResponseException: Exception("Unknown NetworkResponse")
0
Java
0
0
a9a24d6dc27a598a895ed7ce290b2758b4a28e6e
489
connect-sdk-client-android
Apache License 2.0
core/src/main/java/com/ifmvo/togetherad/core/helper/AdHelperNative.kt
ZhouSilverBullet
268,483,019
true
{"Kotlin": 84526}
package com.ifmvo.togetherad.core.helper import android.app.Activity import android.support.annotation.NonNull import android.support.annotation.Nullable import android.view.ViewGroup import com.ifmvo.togetherad.core.TogetherAd import com.ifmvo.togetherad.core.config.AdProviderLoader import com.ifmvo.togetherad.core.custom.flow.BaseNativeTemplate import com.ifmvo.togetherad.core.listener.NativeListener import com.ifmvo.togetherad.core.listener.NativeViewListener import com.ifmvo.togetherad.core.utils.AdRandomUtil /** * 原生自渲染广告 * * Created by Matthew Chen on 2020-04-20. */ object AdHelperNative : BaseHelper() { private const val defaultMaxCount = 4 //为了照顾 Java 调用的同学 fun getList(@NonNull activity: Activity, @NonNull alias: String, maxCount: Int = defaultMaxCount, listener: NativeListener? = null) { getList(activity, alias, null, maxCount, listener) } fun getList(@NonNull activity: Activity, @NonNull alias: String, radioMap: Map<String, Int>? = null, maxCount: Int = defaultMaxCount, listener: NativeListener? = null) { val currentMaxCount = if (maxCount <= 0) defaultMaxCount else maxCount val currentRadioMap = if (radioMap?.isEmpty() != false) TogetherAd.getPublicProviderRadio() else radioMap val adProviderType = AdRandomUtil.getRandomAdProvider(currentRadioMap) if (adProviderType?.isEmpty() != false) { listener?.onAdFailedAll() return } val adProvider = AdProviderLoader.loadAdProvider(adProviderType) if (adProvider == null) { val newRadioMap = AdHelperSplash.filterType(radioMap = currentRadioMap, adProviderType = adProviderType) getList(activity = activity, alias = alias, radioMap = newRadioMap, maxCount = maxCount, listener = listener) return } adProvider.getNativeAdList(activity = activity, adProviderType = adProviderType, alias = alias, maxCount = currentMaxCount, listener = object : NativeListener { override fun onAdStartRequest(providerType: String) { listener?.onAdStartRequest(providerType) } override fun onAdLoaded(providerType: String, adList: List<Any>) { listener?.onAdLoaded(providerType, adList) } override fun onAdFailed(providerType: String, failedMsg: String?) { listener?.onAdFailed(providerType, failedMsg) val newRadioMap = AdHelperSplash.filterType(radioMap = currentRadioMap, adProviderType = adProviderType) getList(activity = activity, alias = alias, radioMap = newRadioMap, maxCount = maxCount, listener = listener) } override fun onAdFailedAll() { listener?.onAdFailedAll() } }) } fun show(@NonNull adObject: Any, @NonNull container: ViewGroup, @NonNull nativeTemplate: BaseNativeTemplate, @Nullable listener: NativeViewListener? = null) { TogetherAd.mProviders.entries.forEach { entry -> val adProvider = AdProviderLoader.loadAdProvider(entry.key) if (adProvider?.isBelongTheProvider(adObject) == true) { val nativeView = nativeTemplate.getNativeView(entry.key) nativeView?.showNative(entry.key, adObject, container, listener) return@forEach } } } }
0
null
0
2
c8d0385d4b4abc8f331348382a33d946f931e519
3,396
TogetherAd
MIT License
app/src/main/java/me/syahdilla/putra/sholeh/storyappdicoding/ui/customview/EditableTextView.kt
adi-itgg
607,399,179
false
null
package me.syahdilla.putra.sholeh.storyappdicoding.ui.customview import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import android.text.InputType import android.text.method.PasswordTransformationMethod import android.util.AttributeSet import android.view.Gravity import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.AppCompatEditText import androidx.core.content.ContextCompat import androidx.core.content.withStyledAttributes import androidx.core.view.updatePadding import androidx.core.widget.addTextChangedListener import androidx.transition.Slide import androidx.transition.TransitionManager import me.syahdilla.putra.sholeh.storyappdicoding.R enum class EditableType { NORMAL, NAME, EMAIL, PASSWORD } class EditableTextView: AppCompatEditText, View.OnTouchListener { constructor(context: Context) : super(context) { initialize() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initializeStyleable(attrs) initialize() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initializeStyleable(attrs) initialize() } private lateinit var clearButtonImage: Drawable private val passwordTransformationMethod by lazy { PasswordTransformationMethod() } private var _textType = EditableType.NORMAL var onNameInvalidView: View? = null var onEmailInvalidView: View? = null var onPasswordInvalidView: View? = null private var _isInputValid = false val isInputValid get() = _isInputValid val getText get() = text?.toString() ?: "" private val isInputValidAsView get() = if (isInputValid || getText.isEmpty()) View.INVISIBLE else View.VISIBLE private fun View.validateView() { animateViewsChanged(this) visibility = isInputValidAsView } private fun initialize() { clearButtonImage = R.drawable.editable_ic_close.getDrawable setOnTouchListener(this) addTextChangedListener( onTextChanged = { s, _, _, _ -> if (s.toString().isNotEmpty()) showClearButton() else hideClearButton() when(_textType) { EditableType.NORMAL -> {} EditableType.NAME -> { _isInputValid = length() > 3 onNameInvalidView?.validateView() } EditableType.EMAIL -> { val text = s.toString() _isInputValid = text.split("@").run { if (size <= 1) return@run false if (!this[1].contains(".")) return@run false val sp = this[1].split(".") if (sp.size <= 1) return@run false if (sp[0].length < 2 || sp[1].length < 2) return@run false true } onEmailInvalidView?.validateView() } EditableType.PASSWORD -> { _isInputValid = length() > 7 onPasswordInvalidView?.validateView() } } } ) background = R.drawable.editable_textview_background.getDrawable when(_textType) { EditableType.NORMAL -> _isInputValid = true EditableType.NAME -> { maxLines = 1 hint = context.getString(R.string.hint_name) } EditableType.EMAIL -> { maxLines = 1 hint = context.getString(R.string.hint_email) } EditableType.PASSWORD -> { maxLines = 1 transformationMethod = passwordTransformationMethod hint = context.getString(R.string.hint_password) } } setButtonDrawables() } private fun initializeStyleable(attrs: AttributeSet) { context.withStyledAttributes(attrs, R.styleable.EditableTextView) { _textType = EditableType.values()[getInt(R.styleable.EditableTextView_textType, 0)] } } private fun showClearButton() { if (_textType == EditableType.PASSWORD) return setButtonDrawables() setButtonDrawables(endOfTheText = clearButtonImage) } private fun hideClearButton() { setButtonDrawables() } private fun setButtonDrawables( startOfTheText: Drawable? = when(_textType) { EditableType.EMAIL -> R.drawable.editable_ic_email EditableType.PASSWORD -> R.drawable.editable_ic_password else -> null }?.getDrawable, topOfTheText:Drawable? = null, endOfTheText:Drawable? = if (_textType == EditableType.PASSWORD) (if (transformationMethod == null) R.drawable.editable_ic_eye else R.drawable.editable_ic_eye_off).getDrawable else null, bottomOfTheText: Drawable? = null ){ setCompoundDrawablesWithIntrinsicBounds( startOfTheText, topOfTheText, endOfTheText, bottomOfTheText ) } private fun animateViewsChanged( view: View ) = Slide(if (view.visibility == View.VISIBLE) Gravity.END else Gravity.START).apply { duration = 400 addTarget(view) TransitionManager.beginDelayedTransition(parent as ViewGroup, this) } override fun onTouch(v: View?, event: MotionEvent): Boolean { if (compoundDrawables[2] == null) return false var isRightButtonClicked = false val instrinsicWidth = clearButtonImage.intrinsicWidth if (layoutDirection == View.LAYOUT_DIRECTION_RTL) { val clearButtonEnd = (instrinsicWidth + paddingStart).toFloat() if (event.x < clearButtonEnd) isRightButtonClicked = true } else { val clearButtonStart = (width - paddingEnd - instrinsicWidth).toFloat() if (event.x > clearButtonStart) isRightButtonClicked = true } return if (isRightButtonClicked) when (event.action) { MotionEvent.ACTION_DOWN -> { showClearButton() true } MotionEvent.ACTION_UP -> { if (_textType == EditableType.PASSWORD) { transformationMethod = if (transformationMethod == null) passwordTransformationMethod else null setSelection(length()) } if (_textType != EditableType.PASSWORD && text != null) text?.clear() hideClearButton() true } else -> false } else false } private var isFirstInitialize = true override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (isFirstInitialize) { isFirstInitialize = false val dp = resources.getDimensionPixelSize(R.dimen.editable_default_padding) updatePadding(left = dp, right = dp) compoundDrawablePadding = dp } } private var isFirstInitializeOnDraw = true override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) if (isFirstInitializeOnDraw) return isFirstInitializeOnDraw = true when(_textType) { EditableType.NORMAL -> _isInputValid = true EditableType.NAME -> inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PERSON_NAME EditableType.EMAIL -> inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS EditableType.PASSWORD -> inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD } } private val Int.getDrawable get() = ContextCompat.getDrawable(context, this) as Drawable }
0
Kotlin
0
0
80ab31ed8387d71ea9493ca371f770209b2e7ec0
8,442
StoryAppDicoding
MIT License
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyConstructorSpec.kt
BoxResin
166,523,079
true
{"Kotlin": 1090643, "Groovy": 3620, "Shell": 1710, "HTML": 698}
package io.gitlab.arturbosch.detekt.rules.empty import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.lint import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.it /** * @author <NAME> */ class EmptyConstructorSpec : Spek({ it("should not report empty constructors for 'expect'ed annotation classes - #1362") { val code = """ expect annotation class NeedsConstructor() @NeedsConstructor fun annotatedFunction() = Unit """.trimIndent() val findings = EmptyDefaultConstructor(Config.empty).lint(code) assertThat(findings).isEmpty() } })
0
Kotlin
0
0
7b5b3ec14d570ae7fb334a07a25b7436d2f7b987
660
detekt
Apache License 2.0
completion-plugin/src/org/jb/cce/highlighter/Highlighter.kt
AlexeyKalina
175,355,979
true
{"Gradle": 9, "XML": 4, "Shell": 7, "Text": 28, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 179, "JavaScript": 3, "CSS": 3, "INI": 1, "Java": 40, "Python": 7}
package org.jb.cce.highlighter import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jb.cce.ReportColors.Companion.getColor import org.jb.cce.Session import java.awt.Font class Highlighter(private val project: Project) { companion object { private val listenerKey = Key<HighlightersClickListener>("org.jb.cce.highlighter.listener") } private lateinit var listener : HighlightersClickListener fun highlight(sessions: List<Session>) { val editor = (FileEditorManager.getInstance(project).selectedEditors[0] as TextEditor).editor listener = editor.getUserData(listenerKey) ?: HighlightersClickListener(editor, project) editor.addEditorMouseListener(listener) ApplicationManager.getApplication().invokeLater { editor.markupModel.removeAllHighlighters() listener.clear() for (session in sessions) { addHighlight(editor, session, session.offset, session.offset + session.expectedText.length) } editor.putUserData(listenerKey, listener) } } private fun addHighlight(editor: Editor, session: Session, begin: Int, end: Int) { val color = getColor(session, HighlightColors, session.lookups.lastIndex) editor.markupModel.addRangeHighlighter(begin, end, HighlighterLayer.LAST, TextAttributes(null, color, null, EffectType.BOXED, Font.PLAIN), HighlighterTargetArea.EXACT_RANGE) listener.addSession(session, begin, end) } }
0
Kotlin
0
0
54d40d0a45ed8ef3100d2fbf1d8c3c09b58197d6
1,987
code-completion-evaluation
Apache License 2.0
core/src/main/java/com/ridhoafni/core/domain/usecase/MovieDbInteractor.kt
ridhoafnidev
352,913,233
false
null
package com.ridhoafni.core.domain.usecase import com.ridhoafni.core.data.Resource import com.ridhoafni.core.data.local.entity.MovieDetails import com.ridhoafni.core.data.remote.response.ApiResponse import com.ridhoafni.core.data.remote.response.DataMovie import com.ridhoafni.core.data.remote.response.Genre import com.ridhoafni.core.domain.model.Movie import com.ridhoafni.core.domain.repository.IMovieDbRepository import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import javax.inject.Inject class MovieDbInteractor @Inject constructor(private val movieDbRepository: IMovieDbRepository) : MovieDbUseCase { override fun getDiscoverMovies(): Flow<ApiResponse<List<DataMovie>>> = movieDbRepository.getDiscoverMovies() override fun getGenres(): Flow<List<Genre>> = movieDbRepository.getGenres() override fun getMoviesByGenres(genreId: String): Flow<ApiResponse<List<DataMovie>>> = movieDbRepository.getMoviesByGenres(genreId) override fun getMovie(movieId: Long): Flow<Resource<MovieDetails>> = movieDbRepository.getMovie(movieId) }
0
Kotlin
0
1
1d22e7b85ce47a4bc034b8cf5e0760b18e44b4f9
1,145
codeinmoviedb
Apache License 2.0
packages/Manager/src/test/kotlin/nz/govt/eop/plan_limits/DetailedWaterUsageTest.kt
Greater-Wellington-Regional-Council
528,176,417
false
{"Kotlin": 248210, "TypeScript": 206033, "Batchfile": 66171, "Shell": 54151, "PLpgSQL": 42581, "ASL": 6123, "SCSS": 4684, "JavaScript": 4383, "Dockerfile": 2524, "HTML": 1578, "CSS": 860}
package nz.govt.eop.plan_limits import java.time.LocalDate import org.hamcrest.Matchers.containsString import org.junit.jupiter.api.Test import org.mockito.Mockito.`when` import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* @ActiveProfiles("test") @SpringBootTest @AutoConfigureMockMvc class DetailedWaterUsageTest(@Autowired val mvc: MockMvc) { @MockBean private lateinit var queries: Queries @Test fun `accepts request for 52 weeks of water usage data`() { // mock db query `when`(queries.waterUsage(9, LocalDate.of(2022, 1, 1), LocalDate.of(2022, 12, 31), null)) .thenReturn("[]") mvc.perform( get("/plan-limits/water-usage?councilId=9&from=2022-01-01&to=2022-12-31") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) } @Test fun `fails for 366 days over a non-leap year`() { `when`(queries.waterUsage(9, LocalDate.of(2022, 1, 1), LocalDate.of(2023, 1, 1), null)) .thenReturn("[]") mvc.perform( get("/plan-limits/water-usage?councilId=9&from=2022-01-01&to=2023-01-01") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest) .andExpect(content().string(containsString("The duration between"))) } @Test fun `succeeds for 366 on leap year`() { `when`(queries.waterUsage(9, LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31), null)) .thenReturn("[]") mvc.perform( get("/plan-limits/water-usage?councilId=9&from=2024-01-01&to=2024-12-31") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) } }
13
Kotlin
3
5
292ce1c7eb3039957f0774e018832625c7a336d5
2,157
Environmental-Outcomes-Platform
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/greedy/TaskAssignment.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.greedy /** * k is a number of workers * tasks is an array of task duration * * find the fastest time to complete all tasks, if worker can proceed only 2 tasks */ fun main() { val tasks = mutableListOf(2, 4, 6, 1, 5, 3) // [[3, 2], [0, 4], [5, 1]] print(taskAssignment(tasks, tasks.size / 2)) } // O(nlog(n)) time | O(n) space private fun taskAssignment(tasks: MutableList<Int>, k: Int): List<List<Int>> { val paired = mutableListOf<List<Int>>() val taskDurationToIndices = taskDurationToIndices(tasks) tasks.sort() for (i in 0 until k) { val loTaskDuration = tasks[i] val loTaskIndices = taskDurationToIndices[loTaskDuration]!! val loIdx = loTaskIndices.removeAt(loTaskIndices.size - 1) val hiTaskDuration = tasks[tasks.size - 1 - i] val hiTaskIndices = taskDurationToIndices[hiTaskDuration]!! val hiIdx = hiTaskIndices.removeAt(hiTaskIndices.size - 1) paired.add(listOf(loIdx, hiIdx)) } return paired } private fun taskDurationToIndices(tasks: MutableList<Int>): MutableMap<Int, MutableList<Int>> { val taskDurationToIndices = mutableMapOf<Int, MutableList<Int>>() for (i in 0 until tasks.size) { val taskDuration = tasks[i] if (taskDuration in taskDurationToIndices) { taskDurationToIndices[taskDuration]!!.add(i) } else { taskDurationToIndices[taskDuration] = mutableListOf(i) } } return taskDurationToIndices }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,539
algs4-leprosorium
MIT License
builders-marketplace-transport-multiplatform/src/commonMain/kotlin/builders/marketplace/transport/multiplatform/models/advert/options/AdditionalDetailDto.kt
otuskotlin
330,110,908
false
null
package builders.marketplace.transport.multiplatform.models.advert.options import builders.marketplace.transport.multiplatform.models.common.MarketplaceMessage import kotlinx.serialization.Serializable @Serializable data class AdditionalDetailDto( val name: String? = null, val description: String? = null ) : MarketplaceMessage()
1
Kotlin
0
0
634d29aa6673f8fedbe25a6ee75598e631cded14
340
otuskotlin-202012-bauserviceads-bd
MIT License
src/commonMain/kotlin/com/github/onotoliy/opposite/data/core/HasName.kt
onotoliy
186,129,590
false
null
package com.github.onotoliy.opposite.data.core interface HasName { val name: String }
0
Kotlin
0
0
b302e812f7e35819b0e2c6c270babe8e8c7a0dae
91
opposite-treasure-data
Apache License 2.0
common/src/commonMain/kotlin/com/nordeck/app/worldle/common/model/Country.kt
ameriod
494,662,375
false
{"Kotlin": 50860, "Swift": 17503, "Shell": 89}
package com.nordeck.app.worldle.common.model import com.nordeck.app.worldle.common.GeoMath import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Country( @SerialName("code") val code: String, @SerialName("latitude") val latitude: Double, @SerialName("longitude") val longitude: Double, @SerialName("name") val name: String ) { fun getDirectionTo(dest: Country): Direction { return if (this == dest) { Direction.CORRECT } else { val bearing = GeoMath.bearing( lat1 = latitude, lng1 = longitude, lat2 = dest.latitude, lng2 = dest.longitude ) // Make sure we only use real "Direction" Direction.values().filter { it.isDirection } .firstOrNull { it.isInRange(bearing) } ?: run { // This should never happen, but if it does, do not crash. Direction.ERROR } } } fun getDistanceTo(dest: Country): Int = GeoMath.distance( lat1 = latitude, lng1 = longitude, lat2 = dest.latitude, lng2 = dest.longitude ).toInt() } fun List<Country>.getByCode(code: String): Country? = firstOrNull { country -> code.equals(country.code, true) }
0
Kotlin
0
0
c9b99d045a1910e8d00e559af536b4714c4b3e02
1,379
Worldle-Mobile
MIT License
engine/src/main/kotlin/com/cuupa/classificator/engine/services/kb/KnowledgeFileParser.kt
Cuupa
236,094,744
false
{"JavaScript": 348091, "CSS": 195119, "Kotlin": 182293, "Java": 23235, "HTML": 11583, "Batchfile": 111}
package com.cuupa.classificator.engine.services.kb import com.cuupa.classificator.domain.SemanticResultData import com.cuupa.classificator.domain.Sender import com.cuupa.classificator.domain.Topic import com.cuupa.classificator.engine.RegexConstants import com.cuupa.classificator.engine.StringConstants import com.cuupa.classificator.engine.extensions.Extension.substringBetween import com.cuupa.classificator.engine.services.Tokens import com.cuupa.classificator.engine.services.token.InvalidTokenException import com.cuupa.classificator.engine.services.token.MetaDataToken import com.cuupa.classificator.engine.services.token.TokenTextPointer import java.util.stream.IntStream object KnowledgeFileParser { fun parseMetaFile(kbFile: String): MetaDataToken { validateToken(kbFile) return parseMetaData(kbFile) } fun parseSenderFile(kbFile: String): Sender { validateToken(kbFile) return parseSender(kbFile) } private fun parseSender(kbFile: String) = (fillToken(kbFile, Sender()) as Sender).apply { name = kbFile.split(RegexConstants.equalPattern)[0].trim() } private fun fillToken(kbFile: String, data: SemanticResultData): SemanticResultData { val charArray = kbFile.toCharArray() for (index in charArray.indices) { if (charArray[index] == '(') { data.addToken(Tokens[TokenTextPointer(charArray, index)]) } if (charArray[index] == '}') { break } } return data } fun parseRegexFile(filename: String, content: String) = Pair(filename.split(RegexConstants.dotPattern)[0], content) private fun parseMetaData(kbFile: String): MetaDataToken { return MetaDataToken().apply { val charArray = kbFile.toCharArray() for (index in charArray.indices) { when { charArray[index] == '$' -> name = findExtractName(charArray, index) charArray[index] == '(' && name.isNotEmpty() -> addToken(Tokens[TokenTextPointer(charArray, index)]) } } } } fun parseDatabaseMetadata(metaInfContent: String): KnowledgeBaseMetadata { return KnowledgeBaseMetadata().apply { version = metaInfContent.substringBetween("version=", "\n") } } fun parseTopicFile(kbFile: String): Topic { val topicName = kbFile.split(RegexConstants.equalPattern)[0].trim() return (fillToken(kbFile, Topic()) as Topic).apply { name = topicName } } private fun findExtractName(charArray: CharArray, index: Int): String { val extractName = StringBuilder() for (i in index until charArray.size) { if (charArray[i] == '=') { for (j in i - 1 downTo 1) { if (charArray[j] == '$') { return extractName.toString().trim { it <= ' ' } } extractName.insert(0, charArray[j]) } } } return extractName.toString().trim() } private fun validateToken(kbFile: String) { val charArray = kbFile.toCharArray() var curlyOpenBrackets = 0 var curlyCloseBrackets = 0 var normalOpenBrackets = 0 var normalCloseBrackets = 0 var quotationMarks = 0 for (c in charArray) { when (c) { '{' -> curlyOpenBrackets++ '}' -> curlyCloseBrackets++ '(' -> normalOpenBrackets++ ')' -> normalCloseBrackets++ '"' -> quotationMarks++ } } val indexOf = kbFile.indexOf(StringConstants.equal) if (indexOf == -1) { throw InvalidTokenException("invalid file definition") } var equalAndBracketValid = false IntStream.of(indexOf, charArray.size - 2).forEach { index -> var searchIndex = index + 1 while (!equalAndBracketValid && charArray[searchIndex].isWhitespace()) { searchIndex++ } if (!equalAndBracketValid && charArray[searchIndex] == '{') { equalAndBracketValid = true } } if (curlyCloseBrackets != curlyOpenBrackets || normalCloseBrackets != normalOpenBrackets) { throw InvalidTokenException("invalid bracket count") } if (quotationMarks % 2 != 0) { throw InvalidTokenException("Invalid usage of quotation marks") } if (!equalAndBracketValid) { throw InvalidTokenException("invalid file definition") } } }
94
JavaScript
0
0
ba3f2b743873a9eebd8919f5461ec53bb5cbc249
4,695
classificator
MIT License
outbox/local/src/commonMain/kotlin/raven/LocalOutboxConfiguration.kt
aSoft-Ltd
849,606,763
false
{"Kotlin": 80259, "HTML": 24145}
package raven fun <P> Map<String, String>.toOutbox(isSent: P.(receiver: String) -> Boolean): Outbox<P> { val capacity = this["capacity"]?.toIntOrNull() ?: LocalOutbox.DEFAULT_CAPACITY return LocalOutbox(capacity = capacity, isSent = isSent) }
0
Kotlin
0
0
aacd62464c6d381d5e9a13483c1ea1fb23aabf34
251
raven
MIT License
src/main/kotlin/dev/austinzhu/algods/containers/sequence/SinglyLinkedList.kt
AustinZhu
287,033,539
false
null
package dev.austinzhu.algods.containers.sequence import dev.austinzhu.algods.containers.Searchable import dev.austinzhu.algods.containers.util.Operation import kotlin.random.Random open class SinglyLinkedList<E> : AbstractLinked<E, SinglyLinkedList<E>.Node>() { inner class Node(value: E, next: Node? = null) : AbstractLinked<E, Node>.Node(value, next) private var isSorted = false companion object { @JvmStatic fun init(size: Int, bound: Int): SinglyLinkedList<Int> { val capacity = Random.nextInt(size) val list = SinglyLinkedList<Int>() for (i in 0 until capacity) { list.push(Random.nextInt(bound)) } return list } } private fun getNode(i: Int, from: Node? = head): Node { val idx = absIdx(i) if (idx >= size) throw IndexOutOfBoundsException() var cur = from for (j in 0 until idx) { cur = cur!!.next } return cur!! } override fun add(idx: Int, value: E) { val cur = getNode(idx) val newNode = Node(value, cur.next) cur.next = newNode size++ } @Operation override fun delete(idx: Int): E { if (head == null) throw IndexOutOfBoundsException("Nothing to delete") val del: E if (idx == 0) { del = head!!.value head = head!!.next } else { val pred = getNode(idx - 1) del = pred.next!!.value pred.next = pred.next!!.next } size-- return del } @Operation override fun push(elem: E) { val newNode = Node(elem) if (head == null) { head = newNode } else { getNode(size - 1).next = newNode } size++ } override fun <V : Comparable<V>> Searchable<Int, V>.max(): Int { check(this is SinglyLinkedList<V>) if (head == null) throw IndexOutOfBoundsException("Null Head") var cur = head var max = head!!.value var maxIdx = 0 var idx = 0 while (cur != null) { if (cur.value > max) { max = cur.value maxIdx = idx } cur = cur.next idx++ } return maxIdx } override fun <V : Comparable<V>> Searchable<Int, V>.max(begin: Int, end: Int): Int { return 0 } override fun <V : Comparable<V>> Searchable<Int, V>.min(): Int { check(this is SinglyLinkedList<V>) if (head == null) throw IndexOutOfBoundsException("Null Head") var cur = head var min = head!!.value var minIdx = 0 var idx = 0 while (cur != null) { if (cur.value < min) { min = cur.value minIdx = idx } cur = cur.next idx++ } return minIdx } override fun <V : Comparable<V>> Searchable<Int, V>.min(begin: Int, end: Int): Int { return 0 } @Operation override fun reverse() { var cur = head var next: Node? var prev: Node? = null while (cur != null) { next = cur.next cur.next = prev prev = cur cur = next } head = prev } fun reverse(start: Int, end: Int) { val head: Node = getNode(start - 1) var cur: Node? var next: Node? var prev: Node? if (start > 0) { cur = head.next prev = getNode(end - 1) } else { cur = head prev = null } for (i in start until end) { next = cur?.next cur?.next = prev prev = cur cur = next } if (start > 0) { head.next = prev } else { this.head = prev!! } } override fun swap(i: Int, j: Int) { if (head == null || i >= size || j >= size) throw IndexOutOfBoundsException("Nothing to swap") val fst = minOf(i, j) val snd = maxOf(i, j) val prevFst = getNode(fst - 1) val nodeFst = prevFst.next val nextFst = prevFst.next?.next val prevSnd = getNode(snd - fst, prevFst) val nodeSnd = prevSnd.next val nextSnd = prevSnd.next?.next prevSnd.next = nodeFst nodeFst?.next = nextSnd prevFst.next = nodeSnd nodeSnd?.next = nextFst } fun toArray() = toArray(0, size) @Suppress("UNCHECKED_CAST") fun toArray(start: Int, end: Int): Array<E?> { if (end < start) throw IllegalArgumentException() if (head == null) { return arrayOfNulls<Any>(0) as Array<E?> } val array: Array<E?> = arrayOfNulls<Any>(end - start) as Array<E?> var iterator: Node = head!! for (i in 0 until start) { if (!iterator.hasNext()) { throw IndexOutOfBoundsException() } iterator = iterator.next!! } for (i in start until end) { if (!iterator.hasNext()) { throw IndexOutOfBoundsException() } array[i] = iterator.value iterator = iterator.next!! } return array } }
0
Kotlin
0
0
e0188bad8a6519e571bdc3ee21c41764c1271f10
5,346
AlgoDS
MIT License
src/main/kotlin/net/ndrei/teslapoweredthingies/integrations/crafttweaker/BaseRegistryTweaker.kt
MinecraftModDevelopmentMods
77,729,751
false
{"Kotlin": 552829}
@file:Suppress("MemberVisibilityCanPrivate") package net.ndrei.teslapoweredthingies.integrations.crafttweaker import crafttweaker.CraftTweakerAPI import net.minecraft.util.ResourceLocation import net.minecraftforge.common.MinecraftForge import net.ndrei.teslapoweredthingies.api.IPoweredRecipe import net.ndrei.teslapoweredthingies.api.IPoweredRegistry import stanhebben.zenscript.annotations.ZenMethod @Suppress("unused") abstract class BaseRegistryTweaker<R: IPoweredRecipe<R>>(protected val registry: IPoweredRegistry<R>) { private val actionsCache = mutableListOf<BaseRegistryAction<R>>() private var registrationCompleted = false init { @Suppress("LeakingThis") MinecraftForge.EVENT_BUS.register(this) this.registrationCompleted = registry.isRegistrationCompleted } protected fun addDelayedAction(action: BaseRegistryAction<R>) { if (!this.registrationCompleted) { this.actionsCache.add(action) } else { action.apply() } } protected fun runRegistrations() { this.registrationCompleted = true this.actionsCache.forEach { it.apply() } this.actionsCache.clear() } private class Add<T: IPoweredRecipe<T>>(tweaker: BaseRegistryTweaker<T>, getter: () -> T) : BaseRegistryAddAction<T>(tweaker.registry, getter) private class Clear<T: IPoweredRecipe<T>>(tweaker: BaseRegistryTweaker<T>) : BaseRegistryClearAction<T>(tweaker.registry) private class Remove<T: IPoweredRecipe<T>>(tweaker: BaseRegistryTweaker<T>, key: ResourceLocation) : BaseRegistryRemoveAction<T>(tweaker.registry, key) private class LogKeys<T: IPoweredRecipe<T>>(tweaker: BaseRegistryTweaker<T>) : BaseRegistryAction<T>(tweaker.registry, "Logging keys of") { override fun apply(registry: IPoweredRegistry<T>) { CraftTweakerAPI.logCommand(this.describe()) registry.registry!!.keys.forEach { CraftTweakerAPI.logCommand(it.toString()) } CraftTweakerAPI.logCommand("<${this.describe()}> finished.") } } fun add(recipe: R) { this.addDelayedAction(Add(this, { recipe })) } fun add(getter: () -> R) { this.addDelayedAction(Add(this, getter ))} @ZenMethod fun clear() { this.addDelayedAction(Clear(this)) } @ZenMethod fun removeRecipe(key: String) { this.removeRecipe(ResourceLocation(key)) } fun removeRecipe(key: ResourceLocation) { this.addDelayedAction(Remove(this, key)) } fun replaceRecipe(key: String, recipe: R) { this.removeRecipe(key); this.add(recipe) } fun replaceRecipe(key: ResourceLocation, recipe: R) { this.removeRecipe(key); this.add(recipe) } fun replaceRecipe(key: String, getter: () -> R) { this.removeRecipe(key); this.add(getter) } fun replaceRecipe(key: ResourceLocation, getter: () -> R) { this.removeRecipe(key); this.add(getter) } @ZenMethod fun logKeys() { this.addDelayedAction(LogKeys(this)) } }
21
Kotlin
4
2
22fdcf629e195a73dd85cf0ac0c5dda551085e71
3,018
Tesla-Powered-Thingies
MIT License
Soluciones/17-ProductosBD-DDD-Koin/src/main/kotlin/di/ProductosModule.kt
joseluisgs
773,712,877
false
{"Kotlin": 626362, "HTML": 34890}
package dev.joseluisgs.di import dev.joseluisgs.productos.cache.ProductosCache import dev.joseluisgs.productos.reposiitories.ProductosRepository import dev.joseluisgs.productos.repositories.ProductosRepositoryImpl import dev.joseluisgs.productos.services.ProductosService import dev.joseluisgs.productos.services.ProductosServicesImpl import dev.joseluisgs.productos.storage.ProductosStorage import dev.joseluisgs.productos.storage.ProductosStorageImpl import dev.joseluisgs.productos.validators.ProductoValidator import org.koin.dsl.module val productosModule = module { // Productos single<ProductosRepository> { ProductosRepositoryImpl(dbManager = get()) } single { ProductoValidator() } single { ProductosCache(size = getProperty("cache.size", "5").toInt()) } single<ProductosStorage> { ProductosStorageImpl() } single<ProductosService> { ProductosServicesImpl( productosRepository = get(), productoValidator = get(), productosCache = get(), productosStorage = get() ) } }
0
Kotlin
2
9
abac30b310f9b9c6cd19e625244f8146a49b8c69
1,071
Programacion-08-2023-2024
PostgreSQL License
app/src/main/java/com/yj/addwords/MyWordListRecyclerViewInterface.kt
lllllLeo
308,499,662
false
{"Kotlin": 280357}
package com.yj.addwords import android.view.View import android.widget.ImageView // 커스텀 인터페이스 interface MyWordListRecyclerViewInterface { // fun onRemoveClicked(v : View, position: Int) fun onViewClicked(v: View, adapterPosition: Int) fun onPopupMenuWordBookClicked(v: View, myWordBtnViewOption: ImageView, adapterPosition: Int) }
0
Kotlin
0
0
a8ef994173405ac10b5b27754ec82bec89a2daa7
344
kokako
Freetype Project License
app/src/main/java/com/app/helper/MenuItem.kt
yash786agg
244,130,702
false
null
package com.app.helper import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.app.jetpackcompose.R sealed class MenuItem(@StringRes val label: Int, @DrawableRes val icon: Int) { object Share: MenuItem(R.string.share,R.drawable.ic_share_black_24dp) object More: MenuItem(R.string.more,R.drawable.ic_more_black_24dp) }
0
Kotlin
0
0
5c2a1f019f84da07490fdc635845306bb00b11d3
358
JetPack-Compose
Apache License 2.0
app/src/main/java/com/akm/letscook/view/categorymeals/CategoryMealsFragment.kt
khawasi
364,934,722
false
null
package com.akm.letscook.view.categorymeals import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.akm.letscook.NavigationGraphDirections import com.akm.letscook.databinding.FragmentCategoryMealsBinding import com.akm.letscook.model.domain.Meal import com.akm.letscook.util.Resource import com.akm.letscook.view.MainActivity import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collect @AndroidEntryPoint class CategoryMealsFragment : Fragment() { private val viewModel: CategoryMealsViewModel by viewModels() private val fragmentArgs: CategoryMealsFragmentArgs by navArgs() private var _binding: FragmentCategoryMealsBinding? = null private var _uiStateJob: Job? = null private var shortAnimationDuration: Int = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentCategoryMealsBinding.inflate(inflater, container, false) _binding!!.categoryMealsRecyclerView.visibility = View.GONE shortAnimationDuration = resources.getInteger(android.R.integer.config_shortAnimTime) (activity as MainActivity).supportActionBar?.title = "" return _binding!!.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setCategoryMeals() } override fun onResume() { (activity as MainActivity).supportActionBar?.title = fragmentArgs.categoryName super.onResume() } override fun onDestroyView() { _binding = null _uiStateJob?.cancel() super.onDestroyView() } private fun setCategoryMeals() { val adapter = CategoryMealsListAdapter { meal -> lifecycleScope.launchWhenCreated { goToDetail(meal) } } _binding?.let { it.categoryMealsRecyclerView.apply { this.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) this.adapter = adapter } } _uiStateJob = lifecycleScope.launchWhenStarted { viewModel.meals.collect { resource -> when (resource.status) { Resource.Status.LOADING -> { Log.v("CMEALS", "LOADING") } Resource.Status.SUCCESS -> { Log.v("CMEALS", "SUCCESS") val meals = resource.data!! adapter.submitList(meals) showCategoryMeals() hideProgressBar() } Resource.Status.ERROR -> { _binding?.let { Snackbar.make(it.root, resource.message!!, Snackbar.LENGTH_LONG).show() } Log.v("CMEALS", "ERROR") hideProgressBar() } } } } } private fun goToDetail(meal: Meal) { this.findNavController().navigate( NavigationGraphDirections.actionGlobalDetailFragment( meal.id, meal.lastAccessed ) ) } private fun showCategoryMeals() { _binding?.let { it.categoryMealsRecyclerView.apply { // Set the content view to 0% opacity but visible, so that it is visible // (but fully transparent) during the animation. alpha = 0f visibility = View.VISIBLE // Animate the content view to 100% opacity, and clear any animation // listener set on the view. animate() .alpha(1f) .setListener(null) .duration = shortAnimationDuration.toLong() } } } private fun hideProgressBar() { _binding?.let { it.categoryMealsShimmerLayout.animate() .alpha(0f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { it.categoryMealsShimmerLayout.visibility = View.GONE } }) .duration = shortAnimationDuration.toLong() } } }
0
Kotlin
1
0
3ea232fb62367b635fbf33533edbb9ab18c77837
5,032
LetsCook
Apache License 2.0
shuttle/icons/domain/src/main/kotlin/shuttle/icons/domain/IconPacksRepository.kt
4face-studi0
462,194,990
false
null
package shuttle.icons.domain import android.graphics.Bitmap import android.graphics.drawable.Drawable import shuttle.apps.domain.model.AppId interface IconPacksRepository { suspend fun getDrawableIcon(iconPackId: AppId, appId: AppId, defaultDrawable: Drawable): Drawable suspend fun getBitmapIcon(iconPackId: AppId, appId: AppId, defaultBitmap: Bitmap): Bitmap }
11
Kotlin
0
10
d06d81fda1b92288183a8aea1c2bd30077652959
375
Shuttle
Apache License 2.0
shuttle/icons/domain/src/main/kotlin/shuttle/icons/domain/IconPacksRepository.kt
4face-studi0
462,194,990
false
null
package shuttle.icons.domain import android.graphics.Bitmap import android.graphics.drawable.Drawable import shuttle.apps.domain.model.AppId interface IconPacksRepository { suspend fun getDrawableIcon(iconPackId: AppId, appId: AppId, defaultDrawable: Drawable): Drawable suspend fun getBitmapIcon(iconPackId: AppId, appId: AppId, defaultBitmap: Bitmap): Bitmap }
11
Kotlin
0
10
d06d81fda1b92288183a8aea1c2bd30077652959
375
Shuttle
Apache License 2.0
idea/testData/debugger/positionManager/functionLiteral.kt
JakeWharton
99,388,807
false
null
class A { fun foo() { { fun innerFoo() { "" // A\$foo\$1\$1 } innerFoo() }() } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
159
kotlin
Apache License 2.0