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/src/main/kotlin/net/insprill/advancementsapi/CustomAdvancement.kt
Insprill
529,109,454
false
null
package net.insprill.advancementsapi import com.google.common.base.Preconditions import com.google.gson.JsonArray import com.google.gson.JsonObject import net.insprill.advancementsapi.nms.NmsHandler import org.bukkit.Bukkit import org.bukkit.NamespacedKey import org.bukkit.advancement.Advancement class CustomAdvancement() { lateinit var key: NamespacedKey var parent: NamespacedKey? = null var display: AdvancementDisplay? = null var criteria: MutableList<AdvancementCriteria> = ArrayList() lateinit var requirements: List<List<String>> lateinit var reward: AdvancementReward private constructor( key: NamespacedKey, parent: NamespacedKey?, display: AdvancementDisplay?, criteria: MutableList<AdvancementCriteria>, requirements: List<List<String>>, reward: AdvancementReward ) : this() { this.key = key this.parent = parent this.display = display this.criteria = criteria this.requirements = requirements this.reward = reward } fun display(init: AdvancementDisplay.() -> Unit) { display = AdvancementDisplay() display!!.init() } fun criteria(init: AdvancementCriteria.() -> Unit) { val criteria = AdvancementCriteria() criteria.init() this.criteria.add(criteria) } fun reward(init: AdvancementReward.() -> Unit) { reward = AdvancementReward() reward.init() } fun build(): Advancement { return NmsHandler.nmsImpl.createCraftAdvancement( CustomAdvancement( key, parent, display, criteria, requirements, reward ) ) } @Suppress("DEPRECATION") // Unsafe fun register() { Preconditions.checkArgument(Bukkit.getAdvancement(key) == null, "Advancement already registered. Check #isRegistered before calling again") Bukkit.getUnsafe().loadAdvancement(key, toJson()) } fun isRegistered(): Boolean { return Bukkit.getAdvancement(key) != null } @Suppress("DEPRECATION") // Unsafe fun unregister() { Preconditions.checkArgument(Bukkit.getAdvancement(key) != null, "Advancement not registered. Check #isRegistered before calling again") Bukkit.getUnsafe().removeAdvancement(key) } /** * [Format](https://minecraft.fandom.com/wiki/Advancement/JSON_format#File_format) */ fun toJson(): String { val json = JsonObject() if (this.parent != null) { json.addProperty("parent", this.parent.toString()) } if (this.display != null) { val advDisplay = this.display!! val display = JsonObject() val icon = JsonObject() icon.addProperty("item", NmsHandler.nmsImpl.getItemKey(advDisplay.icon)) icon.addProperty("nbt", NmsHandler.nmsImpl.getItemNbt(advDisplay.icon)) display.add("icon", icon) display.addProperty("title", advDisplay.title) display.addProperty("frame", advDisplay.displayType.name.lowercase()) display.addProperty("background", advDisplay.background) display.addProperty("description", advDisplay.description) display.addProperty("show_toast", advDisplay.showToast) display.addProperty("announce_to_chat", advDisplay.announceToChat) display.addProperty("hidden", advDisplay.hidden) json.add("display", display) } val criteria = JsonObject() this.criteria.forEach { val c = JsonObject() c.addProperty("trigger", it.trigger) c.add("conditions", it.serializeConditions()) criteria.add(it.key, c) } json.add("criteria", criteria) val requirements = JsonArray() this.requirements.forEach { val arr = JsonArray() it.forEach { arr.add(it) } requirements.add(arr) } json.add("requirements", requirements) val rewards = JsonObject() val recipes = JsonArray() reward.recipes.forEach { recipes.add(it) } rewards.add("recipes", recipes) val loot = JsonArray() reward.loot.forEach { loot.add(it) } rewards.add("loot", recipes) rewards.addProperty("experience", reward.experience) rewards.addProperty("function", reward.function) json.add("rewards", rewards) return json.toString() } companion object { fun customAdvancement(init: CustomAdvancement.() -> Unit): Advancement { val builder = CustomAdvancement() builder.init() return builder.build() } } }
0
Kotlin
0
0
149818e00dce947673b00fbf734506b624fba7e1
4,735
advancements-api
Apache License 2.0
data/data/src/main/java/com/aetherinsight/goldentomatoes/data/data/source/FavoriteMoviesSource.kt
OdisBy
828,176,452
false
{"Kotlin": 192143}
package com.aetherinsight.goldentomatoes.data.data.source import com.aetherinsight.goldentomatoes.data.data.model.MovieGlobal interface FavoriteMoviesSource { interface Local : FavoriteMoviesSource { suspend fun getFavoriteMovies(): List<MovieGlobal> suspend fun addFavoriteMovie(movie: MovieGlobal) suspend fun removeFavoriteMovie(movieId: Long) suspend fun getMoviesById(movieId: Long): MovieGlobal? suspend fun setScheduledStatus(movieId: Long, newState: Boolean) } }
2
Kotlin
0
1
c684e00b066445bd700ac3b5b27c858221d89fea
521
Golden-Movies
MIT License
cinescout/profile/presentation/src/main/kotlin/cinescout/profile/presentation/sample/ProfileStateSample.kt
fardavide
280,630,732
false
null
package cinescout.profile.presentation.sample import cinescout.profile.presentation.state.ProfileState internal object ProfileStateSample { val AccountConnected = ProfileState( account = ProfileState.Account.Connected( uiModel = ProfileAccountUiModelSample.Account ), appVersion = 123 ) val AccountError = ProfileState( account = ProfileState.Account.Error, appVersion = 123 ) val AccountNotConnected = ProfileState( account = ProfileState.Account.NotConnected, appVersion = 123 ) }
10
Kotlin
2
6
7a875cd67a3df0ab98af520485122652bd5de560
580
CineScout
Apache License 2.0
src/main/kotlin/com/piashcse/models/bands/AddBrand.kt
piashcse
410,331,425
false
{"Kotlin": 172948, "FreeMarker": 59, "Procfile": 55}
package com.piashcse.models.bands import org.valiktor.functions.isNotEmpty import org.valiktor.functions.isNotNull import org.valiktor.validate data class AddBrand(val brandName: String) { fun validation() { validate(this) { validate(AddBrand::brandName).isNotNull().isNotEmpty() } } }
5
Kotlin
18
96
7093a687fb0fa35e4714847b13663603aeeb6db5
323
ktor-E-Commerce
curl License
modules/client/src/commonMain/kotlin/client/http/RequestHandler.kt
nirmato
816,013,962
false
{"Kotlin": 128746, "Shell": 1054, "JavaScript": 203}
package org.nirmato.ollama.client.http import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.FlowCollector import kotlinx.coroutines.flow.flow import kotlinx.coroutines.isActive import io.ktor.client.call.body import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.statement.HttpResponse import io.ktor.util.reflect.TypeInfo import io.ktor.util.reflect.typeInfo import io.ktor.utils.io.ByteReadChannel import io.ktor.utils.io.cancel import io.ktor.utils.io.core.Closeable import io.ktor.utils.io.readUTF8Line import org.nirmato.ollama.client.JsonLenient private const val STREAM_PREFIX = "data:" private const val STREAM_END_TOKEN = "$STREAM_PREFIX [DONE]" /** * Perform HTTP requests. */ public interface HttpClientHandler : Closeable { /** * Perform an HTTP request. */ public suspend fun <T : Any> handle(info: TypeInfo, builder: HttpRequestBuilder.() -> Unit): T /** * Perform an HTTP request and transform the result. */ public suspend fun <T : Any> handle(builder: HttpRequestBuilder.() -> Unit, block: suspend (response: HttpResponse) -> T) } /** * Perform an HTTP request. */ public suspend inline fun <reified T> HttpClientHandler.handle(noinline builder: HttpRequestBuilder.() -> Unit): T { return handle(typeInfo<T>(), builder) } /** * Perform an HTTP request and transform the result. */ internal inline fun <reified T : Any> HttpClientHandler.handleFlow(noinline builder: HttpRequestBuilder.() -> Unit): Flow<T> { return flow { handle(builder) { response -> streamEventsFrom(response) } } } /** * Get data as [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). */ @Suppress("LoopWithTooManyJumpStatements") internal suspend inline fun <reified T> FlowCollector<T>.streamEventsFrom(response: HttpResponse) { val channel = response.body<ByteReadChannel>() try { while (currentCoroutineContext().isActive && !channel.isClosedForRead) { val line = channel.readUTF8Line() ?: continue val value: T = when { line.startsWith(STREAM_PREFIX) -> JsonLenient.decodeFromString(line.removePrefix(STREAM_PREFIX)) line.startsWith(STREAM_END_TOKEN) -> break else -> continue } emit(value) } } finally { channel.cancel() } }
1
Kotlin
1
1
fcf2cdee3cbc231b2e99ca5dac69266eb75d10ac
2,511
nirmato-ollama
Apache License 2.0
src/main/kotlin/io/github/kryszak/gwatlin/api/gamemechanics/model/facts/TraitedFact.kt
Kryszak
214,791,260
false
{"Kotlin": 443350, "Shell": 654}
package io.github.kryszak.gwatlin.api.gamemechanics.model.facts import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonTransformingSerializer import kotlinx.serialization.json.jsonObject /** * Data model for traited fact skill property. * * _Important!_ When serializing, serialize with [TraitedFactUnwrapSerializer] * to comply with GW2 API. * */ @Serializable data class TraitedFact( @SerialName("requires_trait") val requiresTrait: Int, val overrides: Int? = null, val fact: Fact, ) { /** * Use this to serialize [TraitedFact] to comply with GW2 API. */ class TraitedFactUnwrapSerializer : JsonTransformingSerializer<TraitedFact>(serializer()) { override fun transformSerialize(element: JsonElement): JsonElement { val (traitedFact, fact) = split(element) val entries = requireNotNull(traitedFact).toMutableMap() requireNotNull(fact) .entries .single() .value .jsonObject .entries .forEach { (k, v) -> entries[k] = v } return JsonObject(entries) } override fun transformDeserialize(element: JsonElement): JsonElement { val (traitedFact, fact) = split(element) val entries = requireNotNull(traitedFact).toMutableMap() entries["fact"] = JsonObject(requireNotNull(fact)) return JsonObject(entries) } private fun split(element: JsonElement) = element.jsonObject.entries .groupBy { (k, _) -> k == "requires_trait" || k == "overrides" } .mapValues { (_, v) -> v.associate { it.toPair() } } .let { it[true] to it[false] } } }
1
Kotlin
1
6
e2a2047e9644a7d27183a98cd28a96844b338232
1,897
gwatlin
MIT License
src/main/kotlin/com/github/thahnen/UniformDependenciesPluginExtension.kt
thahnen
366,445,283
false
null
package com.github.thahnen import org.gradle.api.provider.Property /** * UniformDependenciesPluginExtension: * ================================== * * Extension to this plugin but not for configuration, only for storing data as project.ext / project.extra is not * available when working with the configurations resolution strategy for dependencies * * @author thahnen */ @Suppress("UnnecessaryAbstractClass") abstract class UniformDependenciesPluginExtension { /** stores the path to the properties file holding all information on dependencies provided to this plugin */ abstract val path: Property<String> /** stores the strictness value: STRICT -> always throw exception / LOOSELY -> throw exception on direct * dependencies / LOOSE -> no exception only warning */ abstract val strictness: Property<Strictness> /** stores all dependencies seperated by ";" because I am too stupid to use the List<Property> data type -.- */ abstract val dependencies: Property<String> }
0
Kotlin
0
1
94bd656da91d460b0eaaa32dae1194c56b73aa25
1,020
UniformDependenciesPlugin
MIT License
core/src/commonMain/kotlin/work/socialhub/kmisskey/api/response/blocks/BlocksListResponse.kt
uakihir0
756,689,268
false
{"Kotlin": 251848, "Shell": 2146, "Makefile": 318}
package work.socialhub.kmisskey.api.response.blocks import kotlinx.serialization.Serializable import work.socialhub.kmisskey.entity.Block import kotlin.js.JsExport @JsExport @Serializable class BlocksListResponse : Block()
0
Kotlin
1
3
bbe3fe37d54e24bf1b3ff8b680f25bbc4e190578
225
kmisskey
MIT License
mobilesdk/src/main/java/com/swedbankpay/mobilesdk/ConfigurationCompat.kt
SwedbankPay
209,749,704
false
null
package com.swedbankpay.mobilesdk import android.content.Context import androidx.annotation.WorkerThread import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Java compatibility wrapper for [Configuration]. * * For each callback defined in [Configuration], this class * contains a corresponding callback but without the suspend modifier. * The suspending methods of [Configuration] invoke the corresponding * regular methods using the * [IO Dispatcher](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html). * This means your callbacks run in a background thread, so be careful with synchronization. */ @Suppress("unused") abstract class ConfigurationCompat : Configuration() { /** * Called by [PaymentFragment] when it needs to start a consumer identification * session. Your implementation must ultimately make the call to Swedbank Pay API * and return a [ViewConsumerIdentificationInfo] describing the result. * * @param context an application context * @param consumer the [Consumer] object set as the PaymentFragment argument * @param userData the user data object set as the PaymentFragment argument * @return ViewConsumerIdentificationInfo describing the consumer identification session */ @WorkerThread abstract fun postConsumersCompat( context: Context, consumer: Consumer?, userData: Any? ): ViewConsumerIdentificationInfo /** * Called by [PaymentFragment] to determine whether it should fail or allow * retry after it failed to start a consumer identification session. * * @param exception the exception that caused the failure * @return `true` if retry should be allowed, `false` otherwise */ @WorkerThread open fun shouldRetryAfterPostConsumersExceptionCompat(exception: Exception): Boolean { return exception !is IllegalStateException } /** * Called by [PaymentFragment] when it needs to create a payment order. * Your implementation must ultimately make the call to Swedbank Pay API * and return a [ViewPaymentOrderInfo] describing the result. * * @param context an application context * @param paymentOrder the [PaymentOrder] object set as the PaymentFragment argument * @param userData the user data object set as the PaymentFragment argument * @param consumerProfileRef if a checkin was performed first, the `consumerProfileRef` from checkin * @return ViewPaymentOrderInfo describing the payment order */ @WorkerThread abstract fun postPaymentordersCompat( context: Context, paymentOrder: PaymentOrder?, userData: Any?, consumerProfileRef: String? ): ViewPaymentOrderInfo /** * Called by [PaymentFragment] to determine whether it should fail or allow * retry after it failed to create the payment order. * * @param exception the exception that caused the failure * @return `true` if retry should be allowed, `false` otherwise */ @WorkerThread open fun shouldRetryAfterPostPaymentordersExceptionCompat(exception: Exception): Boolean { return exception !is IllegalStateException } /** * Called by [PaymentFragment] when it needs to update a payment order. * * If you do not update payment orders after they have been created, * you do not need to override this method. * * @param context an application context * @param paymentOrder the [PaymentOrder] object set as the PaymentFragment argument * @param userData the user data object set as the PaymentFragment argument * @param viewPaymentOrderInfo the current [ViewPaymentOrderInfo] as returned from a call to this or [postPaymentorders] * @param updateInfo the updateInfo value from the [PaymentViewModel.updatePaymentOrder] call * @return ViewPaymentOrderInfo describing the payment order with the changed instrument */ @WorkerThread open fun updatePaymentOrderCompat( context: Context, paymentOrder: PaymentOrder?, userData: Any?, viewPaymentOrderInfo: ViewPaymentOrderInfo, updateInfo: Any? ): ViewPaymentOrderInfo = viewPaymentOrderInfo final override suspend fun postConsumers( context: Context, consumer: Consumer?, userData: Any? ) = requestCompat { postConsumersCompat(context, consumer, userData) } final override suspend fun shouldRetryAfterPostConsumersException( exception: Exception ) = requestCompat { shouldRetryAfterPostConsumersExceptionCompat(exception) } final override suspend fun postPaymentorders( context: Context, paymentOrder: PaymentOrder?, userData: Any?, consumerProfileRef: String? ) = requestCompat { postPaymentordersCompat(context, paymentOrder, userData, consumerProfileRef) } final override suspend fun shouldRetryAfterPostPaymentordersException( exception: Exception ) = requestCompat { shouldRetryAfterPostPaymentordersExceptionCompat(exception) } final override suspend fun updatePaymentOrder( context: Context, paymentOrder: PaymentOrder?, userData: Any?, viewPaymentOrderInfo: ViewPaymentOrderInfo, updateInfo: Any? ) = requestCompat { updatePaymentOrderCompat( context, paymentOrder, userData, viewPaymentOrderInfo, updateInfo ) } private suspend fun <T> requestCompat(f: suspend CoroutineScope.() -> T): T { return withContext(Dispatchers.IO, f) } }
13
Kotlin
2
5
9c5b21f3e622741b9b4f5ae1b256242ba26d2efb
5,809
swedbank-pay-sdk-android
Apache License 2.0
app/src/main/java/com/yabancikelimedefteri/presentation/word/WordItem.kt
AhmetOcak
621,942,001
false
{"Kotlin": 215007}
package com.yabancikelimedefteri.presentation.word import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.scaleOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.CompareArrows import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.yabancikelimedefteri.core.ui.component.CardFeatures import com.yabancikelimedefteri.core.ui.component.DeleteWarning import com.yabancikelimedefteri.domain.utils.setImportanceLevel import kotlinx.coroutines.delay import kotlinx.coroutines.launch @Composable fun WordCard( foreignWord: String, meaning: String, onDeleteClick: (Int) -> Unit, wordId: Int, isWordListTypeThin: Boolean, importanceLevel: Int, onEditClick: (Int) -> Unit ) { val scope = rememberCoroutineScope() var visible by remember { mutableStateOf(true) } var showDeleteWarning by remember { mutableStateOf(false) } if (showDeleteWarning) { DeleteWarning( onDismissRequest = { showDeleteWarning = false }, onConfirm = remember { { scope.launch { showDeleteWarning = false visible = false delay(1000) onDeleteClick(wordId) } } } ) } AnimatedVisibility( visible = visible, exit = scaleOut() ) { ElevatedCard( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(vertical = 8.dp) ) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceAround ) { Row( modifier = Modifier .fillMaxWidth() .padding(start = 16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .width(48.dp) .height(8.dp) .clip(RoundedCornerShape(50)) .background(importanceLevel.setImportanceLevel()) .clickable(onClick = {}) ) CardFeatures( onDeleteClick = remember { { showDeleteWarning = true } }, onEditClick = remember { { onEditClick(wordId) } } ) } WordItemContent( isWordListTypeThin = isWordListTypeThin, foreignWord = foreignWord, meaning = meaning ) } } } } @Composable private fun WordItemContent(isWordListTypeThin: Boolean, foreignWord: String, meaning: String) { if (isWordListTypeThin) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier.weight(1f), text = foreignWord, textAlign = TextAlign.End ) Icon( modifier = Modifier.padding(horizontal = 8.dp), imageVector = Icons.AutoMirrored.Default.CompareArrows, contentDescription = null ) Column(modifier = Modifier.weight(1f)) { meaning.split(",").map { it.trim() }.forEach { s -> Text( text = s, textAlign = TextAlign.Start ) } } } } else { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = foreignWord, textAlign = TextAlign.Center ) Icon( modifier = Modifier .rotate(90f) .then(Modifier.padding(vertical = 4.dp)), imageVector = Icons.AutoMirrored.Default.CompareArrows, contentDescription = null ) Text( text = meaning, textAlign = TextAlign.Center ) } } }
2
Kotlin
0
2
70b79147500e11ce47657091910d2457df3862b3
6,001
YabanciKelimeDefterim
MIT License
app/src/main/java/com/example/internetcookbook/models/CupboardOidModel.kt
michealdunne14
272,404,745
false
{"Kotlin": 231001}
package com.example.internetcookbook.models import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class CupboardOidModel ( @SerializedName("cupboardoid") val cupboardoid: String = "", @SerializedName("foodPurchasedCounter") var foodPurchasedCounter: Number = 0 ): Parcelable
0
Kotlin
0
2
bf8bcb28ea43b984762c525ecf7c76f0ddeedf7f
374
InternetCookBookFYP
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsuserpreferences/jpa/repository/PreferenceRepository.kt
ministryofjustice
333,073,953
false
null
package uk.gov.justice.digital.hmpps.hmppsuserpreferences.jpa.repository import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.hmppsuserpreferences.jpa.entity.Preference @Repository interface PreferenceRepository : CrudRepository<Preference, Long> { fun findByHmppsUserIdAndName(userId: String, preferenceName: String): List<Preference> }
2
Kotlin
1
3
99911c218e60188570d4e9811a274f795982f63c
432
hmpps-user-preferences
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/datasync/TaskSchedulePropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.datasync import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.datasync.CfnTask @Generated public fun buildTaskScheduleProperty(initializer: @AwsCdkDsl CfnTask.TaskScheduleProperty.Builder.() -> Unit): CfnTask.TaskScheduleProperty = CfnTask.TaskScheduleProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
451a1e42282de74a9a119a5716bd95b913662e7c
435
aws-cdk-kt
Apache License 2.0
domene/src/main/kotlin/no/nav/tiltakspenger/saksbehandling/domene/behandling/BehandlingTilstand.kt
navikt
487,246,438
false
{"Kotlin": 681488, "Shell": 1309, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.saksbehandling.domene.behandling enum class BehandlingTilstand { OPPRETTET, VILKÅRSVURDERT, TIL_BESLUTTER, IVERKSATT }
7
Kotlin
0
1
e125e2953c16c4bb2c99e6d36075c553b51ed794
153
tiltakspenger-vedtak
MIT License
core/data/src/main/java/com/msg/data/repository/club/ClubRepository.kt
GSM-MSG
700,744,250
false
{"Kotlin": 835112, "CMake": 3664, "C++": 519}
package com.msg.data.repository.club import com.msg.model.remote.enumdatatype.HighSchool import com.msg.model.remote.response.club.ClubDetailResponse import com.msg.model.remote.response.club.ClubListResponse import com.msg.model.remote.response.club.StudentBelongClubResponse import kotlinx.coroutines.flow.Flow import java.util.UUID interface ClubRepository { fun getClubList(highSchool: HighSchool): Flow<List<ClubListResponse>> fun getClubDetail(id: Long): Flow<ClubDetailResponse> fun getStudentBelongClubDetail(id: Long, studentId: UUID): Flow<StudentBelongClubResponse> fun getMyClubDetail(): Flow<ClubDetailResponse> }
4
Kotlin
0
17
feedc33fe2574f5b8d04b71b2bda51209a929a5d
644
Bitgoeul-Android
MIT License
app/src/main/java/com/example/zap/ResultActivity.kt
gilanglahat22
645,295,034
false
null
package com.example.zap import android.content.Context import android.content.Intent import android.media.AudioManager import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import android.media.SoundPool import android.widget.Toast class ResultActivity : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) mediaPlayer = MediaPlayer.create(this, R.raw.results_sound_effect) mediaPlayer.setVolume(0.5f, 0.5f) // Set the volume (0.0f - 1.0f) //Make the View FullScreen window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN val sharedPref = getSharedPreferences("myPref", Context.MODE_PRIVATE) val greet_name = findViewById<TextView>(R.id.greet_name) val tv_score = findViewById<TextView>(R.id.tv_score) val btn_finish = findViewById<Button>(R.id.btn_finish) val userName = sharedPref.getString(Constants.USERNAME, "User") val editor = sharedPref.edit() greet_name.text = userName val highestScoreGeneral = sharedPref.getInt(Constants.GENERAL_HIGHEST_SCORE, 0) val highestScoreHistory = sharedPref.getInt(Constants.HISTORY_HIGHEST_SCORE, 0) val highestScoreMovies = sharedPref.getInt(Constants.MOVIES_HIGHEST_SCORE, 0) val highestScoreComics = sharedPref.getInt(Constants.COMICS_HIGHEST_SCORE, 0) val totalQuestions = intent.getIntExtra(Constants.QUESTIONS_TOTAL, 0) val correctOptions = intent.getIntExtra(Constants.CORRECT_ANSWERS, 0) val categoryName = intent.getStringExtra(Constants.CATEGORY) if (categoryName == "General") { if (correctOptions > highestScoreGeneral) { editor.apply { putInt(Constants.GENERAL_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "History") { if (correctOptions > highestScoreHistory) { editor.apply { putInt(Constants.HISTORY_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "Movies") { if (correctOptions > highestScoreMovies) { editor.apply { putInt(Constants.MOVIES_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "Comics") { if (correctOptions > highestScoreComics) { editor.apply { putInt(Constants.COMICS_HIGHEST_SCORE, correctOptions) apply() } } } tv_score.text = "Akurasi skor kamu adalah $correctOptions/$totalQuestions" btn_finish.setOnClickListener { startActivity(Intent(this, DashboardActivity::class.java)) } } override fun onStart() { super.onStart() mediaPlayer.start() // Start playing the music } override fun onPause() { super.onPause() mediaPlayer.pause() // Pause the music } override fun onStop() { super.onStop() mediaPlayer.stop() // Stop the music mediaPlayer.release() // Release the MediaPlayer resources } }
0
Kotlin
0
0
0258c1b6c1268cdc05fbdc56e3ee8e8bf67a5ce1
3,565
Javanesse_culture
MIT License
app/src/main/java/com/example/zap/ResultActivity.kt
gilanglahat22
645,295,034
false
null
package com.example.zap import android.content.Context import android.content.Intent import android.media.AudioManager import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import android.media.SoundPool import android.widget.Toast class ResultActivity : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) mediaPlayer = MediaPlayer.create(this, R.raw.results_sound_effect) mediaPlayer.setVolume(0.5f, 0.5f) // Set the volume (0.0f - 1.0f) //Make the View FullScreen window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN val sharedPref = getSharedPreferences("myPref", Context.MODE_PRIVATE) val greet_name = findViewById<TextView>(R.id.greet_name) val tv_score = findViewById<TextView>(R.id.tv_score) val btn_finish = findViewById<Button>(R.id.btn_finish) val userName = sharedPref.getString(Constants.USERNAME, "User") val editor = sharedPref.edit() greet_name.text = userName val highestScoreGeneral = sharedPref.getInt(Constants.GENERAL_HIGHEST_SCORE, 0) val highestScoreHistory = sharedPref.getInt(Constants.HISTORY_HIGHEST_SCORE, 0) val highestScoreMovies = sharedPref.getInt(Constants.MOVIES_HIGHEST_SCORE, 0) val highestScoreComics = sharedPref.getInt(Constants.COMICS_HIGHEST_SCORE, 0) val totalQuestions = intent.getIntExtra(Constants.QUESTIONS_TOTAL, 0) val correctOptions = intent.getIntExtra(Constants.CORRECT_ANSWERS, 0) val categoryName = intent.getStringExtra(Constants.CATEGORY) if (categoryName == "General") { if (correctOptions > highestScoreGeneral) { editor.apply { putInt(Constants.GENERAL_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "History") { if (correctOptions > highestScoreHistory) { editor.apply { putInt(Constants.HISTORY_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "Movies") { if (correctOptions > highestScoreMovies) { editor.apply { putInt(Constants.MOVIES_HIGHEST_SCORE, correctOptions) apply() } } } if (categoryName == "Comics") { if (correctOptions > highestScoreComics) { editor.apply { putInt(Constants.COMICS_HIGHEST_SCORE, correctOptions) apply() } } } tv_score.text = "Akurasi skor kamu adalah $correctOptions/$totalQuestions" btn_finish.setOnClickListener { startActivity(Intent(this, DashboardActivity::class.java)) } } override fun onStart() { super.onStart() mediaPlayer.start() // Start playing the music } override fun onPause() { super.onPause() mediaPlayer.pause() // Pause the music } override fun onStop() { super.onStop() mediaPlayer.stop() // Stop the music mediaPlayer.release() // Release the MediaPlayer resources } }
0
Kotlin
0
0
0258c1b6c1268cdc05fbdc56e3ee8e8bf67a5ce1
3,565
Javanesse_culture
MIT License
app/src/main/java/com/example/firstproject/ResultActivity.kt
wesleylenz
619,271,122
false
null
package com.example.firstproject import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.view.MenuItem import android.widget.TextView import androidx.core.content.ContextCompat class ResultActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) supportActionBar?.setHomeButtonEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) val TVresult2 = findViewById<TextView>(R.id.TVresult2) val TVclassificacao = findViewById<TextView>(R.id.TVclassificacao) val result = intent.getFloatExtra("EXTRA_RESULT", 0.1f) val resultformatado = String.format("%.2f", result) TVresult2.text = resultformatado var classificacao = "" if (result < 18.5f) { TVclassificacao.setTextColor(ContextCompat.getColor(this, R.color.abaixo)) classificacao= "Abaixo do peso" } else if (result in 18.5f..24.9f) { TVclassificacao.setTextColor(ContextCompat.getColor(this, R.color.normal)) classificacao= "Normal" } else if (result in 25.0f..29.9f) { TVclassificacao.setTextColor(ContextCompat.getColor(this, R.color.sobrepeso)) classificacao= "Sobrepeso" } else if (result in 30.0f..39.9f) { TVclassificacao.setTextColor(ContextCompat.getColor(this, R.color.obesidade)) classificacao= "Obesidade" } else if (result >= 40.0f) { TVclassificacao.setTextColor(ContextCompat.getColor(this, R.color.obesidadeG)) classificacao= "Obesidade grave" } TVclassificacao.text = getString(R.string.messages_classificacao, classificacao) } override fun onOptionsItemSelected(item: MenuItem): Boolean { finish() return super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
5a5ed2a8879492d7f5b851c226a28bc15e7cb163
2,024
CalculadoraIMC
The Unlicense
src/main/kotlin/ru/yoomoney/gradle/plugins/moira/trigger/collect/CollectorWithFileName.kt
yoomoney
399,815,895
false
null
package ru.yoomoney.gradle.plugins.moira.trigger.collect import java.io.File /** * Collects item from file and provides the absolute name of this file. */ class CollectorWithFileName<C>(private val collector: FilesCollector<C>) : FilesCollector<ItemWithFileName<C>> { override fun isSupported(file: File): Boolean = collector.isSupported(file) override fun collect(file: File): ItemWithFileName<C> = ItemWithFileName(file.absolutePath, collector.collect(file)) }
0
Kotlin
0
1
46f36a0de6722a836d9d7803fe203bb2c2f41bac
477
moira-trigger-plugin
MIT License
src/jvmMain/kotlin/lgbt/lizzy/launch/util/AppData.kt
LizAinslie
559,139,049
false
null
package lgbt.lizzy.launch.util import java.io.File actual class AppData actual constructor( actual val folderName: String ) { init { _instance = this } actual fun getAppData(): FileDescriptor = when (OS.current()) { OS.WINDOWS -> windows() OS.MAC -> mac() OS.LINUX -> linux() } actual fun windows(): FileDescriptor { val appDataFolder = File(System.getenv("UserProfile"), "AppData${File.pathSeparator}$folderName") if (!appDataFolder.exists()) appDataFolder.mkdirs() return appDataFolder } actual fun linux(): FileDescriptor { val appDataFolder = File(System.getenv("HOME"), ".config${File.pathSeparator}$folderName") if (!appDataFolder.exists()) appDataFolder.mkdirs() return appDataFolder } actual fun mac(): FileDescriptor { val appDataFolder = File(System.getenv("HOME"), "Library${File.pathSeparator}Application Support${File.pathSeparator}$folderName") if (!appDataFolder.exists()) appDataFolder.mkdirs() return appDataFolder } actual companion object { actual var _instance: AppData? = null actual fun getInstance(): AppData = _instance!! } }
0
Kotlin
0
1
834d5c1ae53f659a4a6cbbffb9a2b5c8d9a518a7
1,264
LaunchTool
MIT License
src/test/kotlin/vvu/study/kotlin/demo/controllers/DeviceControllerTest.kt
vietvuhoang
440,435,716
false
{"Kotlin": 31085}
package vvu.study.kotlin.demo.controllers import com.ninjasquad.springmockk.MockkBean import io.kotest.common.runBlocking import io.mockk.coEvery import io.mockk.coVerify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.http.MediaType import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody import reactor.core.publisher.Mono import vvu.study.kotlin.demo.dtos.Device import vvu.study.kotlin.demo.dtos.utils.DeviceUtils import vvu.study.kotlin.demo.services.devices.DeviceService @ExtendWith(SpringExtension::class) @WebFluxTest(controllers = [DeviceController::class]) internal class DeviceControllerTest { @MockkBean lateinit var deviceService: DeviceService lateinit var webClient: WebTestClient @Autowired lateinit var controller: DeviceController @BeforeEach fun setup() { webClient = WebTestClient.bindToController(controller).build() } @Test fun createADevice(): Unit = runBlocking { val device = DeviceUtils.createADevice() coEvery { deviceService.create(device) } returns device.id webClient.post() .uri("/devices").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(Mono.just(device), Device::class.java) .exchange().expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.id").isNotEmpty .jsonPath("$.id").isEqualTo(device.id) coVerify(exactly = 1) { deviceService.create(device) } } @Test fun findOne(): Unit = runBlocking { val device = DeviceUtils.createADevice() coEvery { deviceService.get(device.id) } returns device webClient.get().uri("/devices/{id}", device.id) .accept(MediaType.APPLICATION_JSON) .exchange().expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody<Device>().isEqualTo(device) coVerify(exactly = 1) { deviceService.get(device.id) } } }
0
Kotlin
0
0
c255f42dd048970dc7ed3b4d2e6e09f290f6da50
2,534
kotlin-demo-app
Apache License 2.0
slack/adapter/src/commonMain/kotlin/com/gchristov/thecodinglove/slack/adapter/http/model/ApiSlackDeleteMessage.kt
gchristov
533,472,792
false
{"Kotlin": 499294, "CSS": 174432, "HTML": 61045, "Dockerfile": 4477, "JavaScript": 742, "Shell": 613}
package com.gchristov.thecodinglove.slack.adapter.http.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class ApiSlackDeleteMessageResponse( @SerialName("ok") val ok: Boolean, @SerialName("error") val error: String?, ) @Serializable internal data class ApiSlackDeleteMessage( @SerialName("channel") val channelId: String, @SerialName("ts") val messageTs: String, )
1
Kotlin
1
4
130e0157f613ad04816561dc5738d7e1e42ece21
450
thecodinglove-kotlinjs
Apache License 2.0
slack/adapter/src/commonMain/kotlin/com/gchristov/thecodinglove/slack/adapter/http/model/ApiSlackDeleteMessage.kt
gchristov
533,472,792
false
{"Kotlin": 499294, "CSS": 174432, "HTML": 61045, "Dockerfile": 4477, "JavaScript": 742, "Shell": 613}
package com.gchristov.thecodinglove.slack.adapter.http.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class ApiSlackDeleteMessageResponse( @SerialName("ok") val ok: Boolean, @SerialName("error") val error: String?, ) @Serializable internal data class ApiSlackDeleteMessage( @SerialName("channel") val channelId: String, @SerialName("ts") val messageTs: String, )
1
Kotlin
1
4
130e0157f613ad04816561dc5738d7e1e42ece21
450
thecodinglove-kotlinjs
Apache License 2.0
src/r3/atomic-swap/corda/evm-interop-common/src/main/kotlin/com/r3/corda/interop/evm/common/trie/NibbleArray.kt
hyperledger-labs
648,500,313
false
null
/* * Copyright 2023, R3 LLC * * 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.r3.corda.interop.evm.common.trie /** * Represents an array of nibbles (values between 0-15 inclusive) */ class NibbleArray(private val values: ByteArray) { companion object { val empty: NibbleArray = NibbleArray(ByteArray(0)) fun fromBytes(bytes: ByteArray): NibbleArray { val result = ByteArray(bytes.size shl 1) bytes.forEachIndexed { byteIndex, byte -> val nibbleIndex = byteIndex shl 1 result[nibbleIndex] = (byte shr 4) and 0x0F result[nibbleIndex + 1] = byte and 0x0F } return NibbleArray(result) } } fun toBytes(): ByteArray { require(isEvenSized) { "Cannot convert odd-sized nibble array to bytes" } val result = ByteArray(values.size shr 1) values.forEachIndexed { nibbleIndex, nibble -> val resultIndex = nibbleIndex shr 1 result[resultIndex] = if (nibbleIndex.isEven) nibble shl 4 else result[resultIndex] or nibble } return result } fun prepend(prefix: NibbleArray): NibbleArray { val prepended = ByteArray(prefix.size + values.size) prefix.values.copyInto(prepended, 0) values.copyInto(prepended, prefix.size) return NibbleArray(prepended) } fun dropFirst(numberOfNibbles: Int): NibbleArray = NibbleArray(values.copyOfRange(numberOfNibbles, values.size)) fun remainingAfter(index: Int): NibbleArray = dropFirst(index + 1) fun takeFirst(numberOfNibbles: Int): NibbleArray = NibbleArray(values.copyOfRange(0, numberOfNibbles)) val size: Int get() = values.size val isEvenSized: Boolean get() = size.isEven val head: Byte get() = values.firstOrNull() ?: throw IllegalStateException("head called on empty nibble array") val tail: NibbleArray get() = dropFirst(1) fun isEmpty(): Boolean = values.isEmpty() fun startsWith(other: NibbleArray): Boolean { if (other.size > size) { return false } for (i in other.values.indices) { if (values[i] != other[i]) { return false } } return true } fun prefixMatchingLength(other: NibbleArray): Int { var ptr = 0 while (ptr < size && ptr < other.size) { if (values[ptr] != other.values[ptr]) break ptr++ } return ptr } operator fun get(index: Int): Byte = values[index] override fun equals(other: Any?) = this === other || (other is NibbleArray && values.contentEquals(other.values)) override fun hashCode(): Int = values.contentHashCode() } /** * Represents the result of comparing the prefixes of a key and a path. */ sealed class PathPrefixMatch { companion object { /** * Compare a key and a path, and return a [PathPrefixMatch] representing the agreement between their prefixes. */ fun match(key: NibbleArray, path: NibbleArray): PathPrefixMatch { if (key == path) return Equals val matchesUpTo = path.prefixMatchingLength(key) return when (matchesUpTo) { 0 -> NoMatch( path[0].toInt(), path.remainingAfter(0), key[0].toInt(), key.remainingAfter(0) ) key.size -> KeyPrefixesPath(path.dropFirst(matchesUpTo)) path.size -> PathPrefixesKey(key.dropFirst(matchesUpTo)) else -> PartialMatch( path.takeFirst(matchesUpTo), path.dropFirst(matchesUpTo), key.dropFirst(matchesUpTo) ) } } } /** * The path and the key are entirely equal. */ object Equals: PathPrefixMatch() /** * The path and the key are entirely unequal. */ data class NoMatch( val pathHead: Int, val pathTail: NibbleArray, val keyHead: Int, val keyTail: NibbleArray ) : PathPrefixMatch() /** * The entire key (e.g. 1, 2, 3) is a prefix to the path (e.g. 1, 2, 3, 4) */ data class KeyPrefixesPath(val pathRemainder: NibbleArray): PathPrefixMatch() { val pathRemainderHead: Int get() = pathRemainder.head.toInt() val pathRemainderTail: NibbleArray get() = pathRemainder.tail } /** * The entire path (e.g. 1, 2, 3) is a prefix to the entire key (e.g. 1, 2, 3, 4) */ data class PathPrefixesKey(val keyRemainder: NibbleArray): PathPrefixMatch() { val keyRemainderHead: Int get() = keyRemainder.head.toInt() val keyRemainderTail: NibbleArray get() = keyRemainder.tail } /** * The key and the path have a shared prefix (e.g. 1, 2) not equal to the entire key (e.g. 1, 2, 3) * or the entire path (e.g. 1, 2, 4) */ data class PartialMatch( val sharedPrefix: NibbleArray, val pathRemainder: NibbleArray, val keyRemainder: NibbleArray): PathPrefixMatch() { val pathRemainderHead: Int get() = pathRemainder.head.toInt() val pathRemainderTail: NibbleArray get() = pathRemainder.tail val keyRemainderHead: Int get() = keyRemainder.head.toInt() val keyRemainderTail: NibbleArray get() = keyRemainder.tail } } // Logic operations for Bytes private infix fun Byte.shl(shift: Int) = (toInt() shl shift).toByte() private infix fun Byte.shr(shift: Int) = (toInt() shr shift).toByte() private infix fun Byte.and(other: Byte) = (toInt() and other.toInt()).toByte() private infix fun Byte.or(other: Byte) = (toInt() or other.toInt()).toByte() // Test if an Int is even private val Int.isEven: Boolean get() = (this and 1) == 0 // Not available in this version of Kotlin private fun ByteArray.copyInto(other: ByteArray, startIndex: Int) { var ptr = startIndex forEach { other[ptr++] = it } }
4
Kotlin
7
9
469a06064e1795977ab8aed00973ab1c98481172
6,618
harmonia
Apache License 2.0
src/main/java/com/softwareforgood/pridefestival/ui/events/EventsFragment.kt
softwareforgood
145,141,473
false
null
package com.softwareforgood.pridefestival.ui.events import android.view.LayoutInflater import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import com.jakewharton.rxbinding2.support.v7.widget.SearchViewQueryTextEvent import com.softwareforgood.pridefestival.databinding.ViewEventsBinding import com.softwareforgood.pridefestival.ui.misc.SearchFragment import io.reactivex.Observable class EventsFragment : SearchFragment<ViewEventsBinding>() { override val title = "Schedule" override val toolbar: Toolbar get() = binding.toolbar.root override fun searchEvents(searchEvents: Observable<SearchViewQueryTextEvent>) { binding.root.presenter.search(searchEvents) } override fun inflate(inflater: LayoutInflater, container: ViewGroup?): ViewEventsBinding { return ViewEventsBinding.inflate(layoutInflater, container, false) } }
13
Kotlin
1
0
894181ca9e77438ab77f4707d1bb056b9506da59
885
pride-android
MIT License
Programming-With-IntelliJ-IDEA/Programming-With-IntelliJ-IDEA/src/main/kotlin/konsepObjectOrientedProgramming/OOP.kt
eby8zevin
248,026,114
false
{"Kotlin": 107743}
package konsepObjectOrientedProgramming fun main() { println("Blueprint: Mobil") // class println("Komponen: Roda, Pintu, Nomor Kendaraan, & Lampu") // atribut println("Kemampuan: Melaju & Mundur") // behaviour println("The result of the realization of a blueprint is called an object") }
0
Kotlin
0
0
bde791efe687f35dffb6ae6e352e10abeab8bc4e
309
started-Kotlin
MIT License
Business/JetpackBusiness/src/main/java/com/yc/jetpack/study/binding/PlainOldActivity.kt
yangchong211
105,117,953
false
null
package com.yc.jetpack.study.binding import android.content.Context import android.content.Intent import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.widget.ImageViewCompat import androidx.lifecycle.ViewModelProviders import com.yc.jetpack.R class PlainOldActivity : AppCompatActivity() { private val viewModel by lazy { ViewModelProviders.of(this).get(SimpleViewModel::class.java) } companion object{ fun startActivity(context: Context) { context.startActivity(Intent(context, PlainOldActivity::class.java)) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_binding_plain) updateName() updateLikes() findViewById<TextView>(R.id.like_button).setOnClickListener { viewModel.onLike() updateLikes() } } private fun updateName() { findViewById<TextView>(R.id.plain_name).text = viewModel.name findViewById<TextView>(R.id.plain_lastname).text = viewModel.lastName } private fun updateLikes() { findViewById<TextView>(R.id.likes).text = viewModel.likes.toString() findViewById<ProgressBar>(R.id.progressBar).progress = (viewModel.likes * 100 / 5).coerceAtMost(100) val image = findViewById<ImageView>(R.id.imageView) val color = getAssociatedColor(viewModel.popularity, this) ImageViewCompat.setImageTintList(image, ColorStateList.valueOf(color)) image.setImageDrawable(getDrawablePopularity(viewModel.popularity, this)) } private fun getAssociatedColor(popularity: Popularity, context: Context): Int { return when (popularity) { Popularity.NORMAL -> context.theme.obtainStyledAttributes( intArrayOf(android.R.attr.colorForeground) ).getColor(0, 0x000000) Popularity.POPULAR -> ContextCompat.getColor(context, R.color.priority_green) Popularity.STAR -> ContextCompat.getColor(context, R.color.redTab) } } private fun getDrawablePopularity(popularity: Popularity, context: Context): Drawable? { return when (popularity) { Popularity.NORMAL -> { ContextCompat.getDrawable(context, R.drawable.ic_android) } Popularity.POPULAR -> { ContextCompat.getDrawable(context, R.drawable.ic_home) } Popularity.STAR -> { ContextCompat.getDrawable(context, R.drawable.common_ic_account) } } } }
15
null
743
3,157
83c22ffbd61186aa86d29a325755e5f796d1e117
2,910
YCAppTool
Apache License 2.0
src/main/java/net/ddns/rkdawenterprises/brief4ijidea/Keymap_action_data.kt
rkdawenterprises
512,818,011
false
{"Text": 2, "Gradle Kotlin DSL": 2, "Markdown": 2, "Java Properties": 2, "YAML": 5, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "TOML": 1, "INI": 2, "Kotlin": 45, "Java": 26, "SVG": 3, "XML": 8}
/* * Copyright (c) 2019-2022 RKDAW Enterprises and <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("ClassName") package net.ddns.rkdawenterprises.brief4ijidea import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.util.SmartList import javax.swing.Icon data class Keymap_action_data ( var version: Int = 1, var text: String? = null, var description: String? = null, var action_ID: String? = null, var icon: Icon? = null, var shortcuts: List<KeyboardShortcut> = SmartList() )
2
Java
0
0
5ea26506590a320353693385d359199e7ee920eb
1,062
brief4ijidea
Apache License 2.0
MultiModuleApp2/module2/src/main/java/com/github/yamamotoj/module2/package48/Foo04822.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.module2.package48 class Foo04822 { fun method0() { Foo04821().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
347
android_multi_module_experiment
Apache License 2.0
imitate/src/main/java/com/engineer/imitate/activity/FakeJikeActivity.kt
Saujyun
181,672,600
true
{"Java Properties": 2, "YAML": 1, "Gradle": 11, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 6, "XML": 352, "JSON": 14, "Groovy": 2, "INI": 1, "Proguard": 4, "Java": 290, "HTML": 10, "Kotlin": 62, "JavaScript": 1, "PlantUML": 1}
package com.engineer.imitate.activity import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.engineer.imitate.R import com.engineer.imitate.util.ViewUtils import com.engineer.imitate.widget.ShadowStack import kotlinx.android.synthetic.main.activity_fake_jike.* import org.jetbrains.annotations.NotNull class FakeJikeActivity : AppCompatActivity() { override fun onCreate(@NotNull savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fake_jike) val shadowStack = ShadowStack<View>(this) shadowStack.setTargetView(image) shadowStack.setContainer(container) val shadowStack1 = ShadowStack<View>(this) shadowStack1.setTargetView(text) shadowStack1.setContainer(container) val shadowStack2 = ShadowStack<View>(this) shadowStack2.setTargetView(layout) shadowStack2.setContainer(container) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ViewUtils.getBitmapFormView(image, this) { bitmap -> temp.setImageBitmap(bitmap) } } temp1.setImageBitmap(ViewUtils.getBitmapFromView(image)) } }
0
Java
0
0
024bf733802a28cb65b0b7859aab607a54d4354a
1,360
AndroidAnimationExercise
Apache License 2.0
fetch2/src/main/java/com/tonyodev/fetch2/database/TagDao.kt
jordyamc
479,109,068
false
{"Java Properties": 3, "YAML": 2, "Gradle": 11, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 4, "Ignore List": 9, "Proguard": 8, "XML": 140, "Kotlin": 135, "Java": 42, "JSON": 109}
package com.tonyodev.fetch2.database import androidx.room.* import androidx.room.OnConflictStrategy.IGNORE import com.tonyodev.fetch2.database.DownloadDatabase.Companion.COLUMN_TAG_ID import com.tonyodev.fetch2.database.DownloadDatabase.Companion.TABLE_NAME import com.tonyodev.fetch2.database.DownloadDatabase.Companion.TABLE_TAG_NAME import com.tonyodev.fetch2.database.join.TagWithDownloads @Dao abstract class TagDao { @Transaction @Query("SELECT * FROM $TABLE_TAG_NAME WHERE $COLUMN_TAG_ID=:tagId") abstract fun getDownloadsByTag(tagId: Int): TagWithDownloads? @Insert(onConflict = IGNORE) abstract fun addTag(tag: Tag): Long @Update abstract fun updateTag(tag: Tag) @Transaction open fun addOrUpdateTag(tag: Tag) { if (addTag(tag) == -1L) { updateTag(tag) } } }
1
null
1
1
efa48a0fa2e08176e27afc3336eb853c1db5ed1f
841
Fetch
Apache License 2.0
ethstats/src/main/kotlin/org/apache/tuweni/ethstats/NodeInfo.kt
apache
178,461,625
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.tuweni.ethstats import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonGetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonPropertyOrder @JsonPropertyOrder(alphabetic = true) data class NodeInfo @JsonCreator constructor( @JsonProperty("name") val name: String, @JsonProperty("node") val node: String, @JsonProperty("port") val port: Int, @JsonProperty("net") val net: String, @JsonProperty("protocol") val protocol: String, @JsonProperty("api") val api: String = "No", @JsonProperty("os") val os: String, @JsonProperty("os_v") private val osVer: String, @JsonProperty("canUpdateHistory") val canUpdateHistory: Boolean = true, @JsonProperty("client") val client: String = "Apache Tuweni Ethstats" ) { @JsonGetter("os_v") fun osVersion() = osVer }
6
null
78
171
0852e0b01ad126b47edae51b26e808cb73e294b1
1,708
incubator-tuweni
Apache License 2.0
fiks-io-melding-validator/src/main/kotlin/TestRunner.kt
ks-no
183,625,702
false
{"Maven POM": 5, "Text": 2, "Ignore List": 1, "Markdown": 1, "JSON": 5, "Kotlin": 20, "INI": 1, "Java": 1}
package no.ks.fiks.gi.melding import org.leadpony.justify.api.JsonValidationService import org.springframework.stereotype.Component import java.io.FileInputStream @Component class TestRunner() { val service = JsonValidationService.newInstance() fun run( tests: List<MeldingTest>): Int { return tests.map { meldingtest -> println(meldingtest.navn + ": Tester meldinger mot jsonspec " + meldingtest.jsonSpec?.name) println() val results: List<Int> = meldingtest.meldinger?.map { melding -> println() println(meldingtest.navn + ": Tester melding " + melding.name) val errors: MutableList<String> = ArrayList() try { val schema = service.readSchema(FileInputStream(meldingtest.jsonSpec)) val handler = service.createProblemPrinter({ errors.add(it) }) service.createParser(FileInputStream(melding), schema, handler).use { parser -> while (parser.hasNext()) { parser.next() } } } catch (e: Exception) { println("Failed to read schema ${meldingtest.jsonSpec} feilet med ${e.message}") return 2 } if (errors.size > 0) { println(meldingtest.navn + ": Errors:") errors.forEach { println(meldingtest.navn + ": " + it) } 1 } else { println(meldingtest.navn + ": Ingen error i " + melding.name) 0 } } ?: listOf(0) results.sum() }.sum() } }
1
null
1
1
725ad8180ec43035282349ab069939aa3d3e8a03
1,763
fiks-io-melding-validator
MIT License
src/main/kotlin/settings/ApplicationSettings.kt
exigow
202,529,822
false
null
package settings import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil import version.VersionService @State(name = "ApplicationSettings", storages = [(Storage("gdscript.xml"))]) class ApplicationSettings( var versionId: String = VersionService.DEFAULT_VERSION ) : PersistentStateComponent<ApplicationSettings> { override fun getState() = this override fun loadState(other: ApplicationSettings) { XmlSerializerUtil.copyBean(other, this) } }
25
null
9
148
2bfc92a68723de75dc75754719490acb3b4e26d0
619
intellij-gdscript
MIT License
module/module-database-core/src/main/kotlin/taboolib/module/database/RunTask.kt
TabooLib
120,413,612
false
null
package taboolib.module.database import java.sql.ResultSet /** * TabooLib * taboolib.module.database.RunTask * * @author sky * @since 2021/6/24 12:52 上午 */ class RunTask(future: Future<ResultSet>) : QueryTask(future) { override fun run(): Int { return future.call { 0 } } override fun find(): Boolean { TODO("Not yet implemented") } override fun <T> first(call: ResultSet.() -> T): T { TODO("Not yet implemented") } override fun <T> map(call: ResultSet.() -> T): List<T> { TODO("Not yet implemented") } override fun forEach(call: ResultSet.() -> Unit) { TODO("Not yet implemented") } }
9
null
81
229
065c8de7033a3073181476fd1ec6f1e830ff9983
678
taboolib
MIT License
src/main/kotlin/sqlbuilder/impl/mappers/LocalDateMapper.kt
laurentvdl
27,872,125
false
null
package sqlbuilder.impl.mappers import sqlbuilder.mapping.BiMapper import sqlbuilder.mapping.ToObjectMappingParameters import sqlbuilder.mapping.ToSQLMappingParameters import java.sql.Date import java.sql.Types import java.time.LocalDate class LocalDateMapper : BiMapper { override fun toObject(params: ToObjectMappingParameters): Any? { val date = params.resultSet.getDate(params.index) return date?.toLocalDate() } override fun handles(targetType: Class<*>): Boolean { return LocalDate::class.java == targetType } override fun toSQL(params: ToSQLMappingParameters) { val dateTime = params.value as LocalDate? if (dateTime != null) { params.preparedStatement.setDate(params.index, Date.valueOf(dateTime)) } else { params.preparedStatement.setNull(params.index, Types.DATE) } } }
1
Kotlin
2
6
4efe1dd61f6da45192a1b2741d654269616535d0
887
sqlbuilder
Apache License 2.0
mbcarkit/src/test/java/com/daimler/mbcarkit/business/model/vehicle/VehicleStatusTest.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.business.model.vehicle import com.daimler.mbcarkit.business.model.vehicle.unit.ClockHourUnit import com.daimler.mbcarkit.business.model.vehicle.unit.DisplayUnitCase import org.junit.Assert import org.junit.Test import java.util.Date class VehicleStatusTest { var myunit = VehicleAttribute.Unit("", DisplayUnitCase.CLOCK_HOUR_UNIT, ClockHourUnit.UNSPECIFIED_CLOCK_HOUR_UNIT) @Test fun testIfBatteryStateIsMappedCorrectly_From0ToGreen() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 0, myunit) val batteryState = VehicleStatus.batteryStateFromInt(vehicleAttribute) Assert.assertEquals(BatteryState.GREEN, batteryState.value) } @Test fun testIfBatteryStateIsMappedCorrectly_From1ToYELLOW() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 1, myunit) val batteryState = VehicleStatus.batteryStateFromInt(vehicleAttribute) Assert.assertEquals(BatteryState.YELLOW, batteryState.value) } @Test fun testIfBatteryStateIsMappedCorrectly_From2ToRED() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 2, myunit) val batteryState = VehicleStatus.batteryStateFromInt(vehicleAttribute) Assert.assertEquals(BatteryState.RED, batteryState.value) } @Test fun testIfBatteryStateIsMappedCorrectly_From3toServiceDisabled() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 3, myunit) val batteryState = VehicleStatus.batteryStateFromInt(vehicleAttribute) Assert.assertEquals(BatteryState.SERVICE_DISABLED, batteryState.value) } @Test fun testIfKeyActivationStateIsMappedCorrectly_From1ToActive() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 1, myunit) val kas = VehicleStatus.keyActivationStateFromInt(vehicleAttribute) Assert.assertEquals(KeyActivationState.ALL_KEYS_ACTIVE, kas.value) } @Test fun testIfKeyActivationStateIsMappedCorrectly_From0ToInactive() { val vehicleAttribute = VehicleAttribute(StatusEnum.VALID, Date(), 0, myunit) val kas = VehicleStatus.keyActivationStateFromInt(vehicleAttribute) Assert.assertEquals(KeyActivationState.ALL_KEYS_INACTIVE, kas.value) } }
1
Kotlin
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
2,317
MBSDK-Mobile-Android
MIT License
ontrack-extension-hook/src/main/java/net/nemerosa/ontrack/extension/hook/records/HookRecordState.kt
nemerosa
19,351,480
false
{"Kotlin": 9309646, "JavaScript": 3062605, "Java": 1043391, "HTML": 507221, "Groovy": 372843, "CSS": 137546, "Less": 35335, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.extension.hook.records import net.nemerosa.ontrack.model.annotations.APIDescription @APIDescription("State a hook request can be in") enum class HookRecordState { RECEIVED, UNDEFINED, DISABLED, DENIED, SUCCESS, ERROR, }
44
Kotlin
25
96
759f17484c9b507204e5a89524e07df871697e74
276
ontrack
MIT License
app/src/main/java/solutions/alterego/android/unisannio/models/Article.kt
sayyidisal
184,558,496
true
{"Java Properties": 2, "YAML": 1, "Gradle": 9, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 7, "Proguard": 6, "XML": 69, "Kotlin": 30, "Java": 71}
package solutions.alterego.android.unisannio.models import android.annotation.SuppressLint import android.os.Parcelable import kotlinx.android.parcel.Parcelize @SuppressLint("ParcelCreator") @Parcelize data class Article( val id: String, val title: String, val author: String, val url: String, val body: String, val date: String ) : Parcelable
0
Java
0
0
8f808f0379afc66642694115ab2988dd740a30e5
370
unisannio-reboot
Apache License 2.0
app/src/main/java/com/first/kotlin/activity/pai/PaiMainActivity.kt
huoqiling
149,223,868
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 31, "Kotlin": 52}
package com.first.kotlin.activity.pai import com.first.kotlin.R import com.first.kotlin.base.BaseActivity /** * @author zhangxin * @date 2018/9/28 * @description 派首页 */ class PaiMainActivity : BaseActivity() { override fun getLayoutResId(): Int { return R.layout.activity_pai_main } override fun initView() { } }
1
null
1
1
422b0549b612af3f83870d584e0867d1c18342d1
351
KotinStudy
Apache License 2.0
KotlinBasicStudy/app/src/main/java/com/yunjaena/kotlinbasicstudy/kotlin/20.Practice.kt
yunjaena
278,050,796
false
null
package com.yunjaena.kotlinbasicstudy.kotlin // 2) 이행 계좌 만들기 // - 계좌 생성 기능 (이름, 생년 월일, 초기금액) // - 잔고를 확인 하는 기능 // - 출금 기능 // - 예금 기능 fun main(args: Array<String>) { val account: Account = Account("홍길동", "1990/3/1", 1000) println(account.checkBalance()) println(account.save(1000)) println(account.withdraw(2000)) println(account.checkBalance()) println() val account2 = Account("홍길동", "1990/3/1", -2000) println(account2.checkBalance()) println() val account3 = Account2("홍길동", "1990/3/1") val account4 = Account2("홍길동", "1990/3/1",4000) println(account3.checkBalance()) println(account4.checkBalance()) } class Account { val name: String val birth: String var balance: Int constructor(name: String, birth: String, balance: Int) { this.name = name this.birth = birth if (balance >= 0) this.balance = balance else this.balance = 0 } fun checkBalance(): Int { return balance } fun withdraw(amount: Int): Boolean { if (balance >= amount) { balance -= amount return true } else { return false } } fun save(amount: Int) { balance += amount } } class Account2(val name : String, val birth: String, var balance: Int = 1000){ fun checkBalance(): Int { return balance } fun withdraw(amount: Int): Boolean { if (balance >= amount) { balance -= amount return true } else { return false } } fun save(amount: Int) { balance += amount } } class Account3(initialBalance : Int){ val balance : Int = if(initialBalance >= 0) initialBalance else 0 fun checkBalance() : Int{ return balance } }
1
null
1
1
a80a9e5a55c58976c6ba2aec5e3365d0687231c4
1,838
android_study
Apache License 2.0
jerry/src/main/java/br/alexandregpereira/jerry/animator/ElevationSpringItemAnimator.kt
alexandregpereira
303,074,104
false
null
package br.alexandregpereira.jerry.animator import android.view.View import androidx.annotation.RequiresApi import androidx.dynamicanimation.animation.SpringForce.DAMPING_RATIO_NO_BOUNCY import androidx.recyclerview.widget.RecyclerView import br.alexandregpereira.jerry.ANIMATION_STIFFNESS import br.alexandregpereira.jerry.add import br.alexandregpereira.jerry.after import br.alexandregpereira.jerry.dpToPx import br.alexandregpereira.jerry.animation.elevationSpring import br.alexandregpereira.jerry.animation.fadeInSpring import br.alexandregpereira.jerry.animation.fadeOutSpring import br.alexandregpereira.jerry.animation.fadeSpring import br.alexandregpereira.jerry.force import br.alexandregpereira.jerry.start import br.alexandregpereira.jerry.animation.translationXSpring import br.alexandregpereira.jerry.animation.translationYSpring @RequiresApi(21) class ElevationSpringItemAnimator( private val elevation: Float? = null, stiffness: Float = ANIMATION_STIFFNESS, dampingRatio: Float = DAMPING_RATIO_NO_BOUNCY ) : BaseItemAnimator() { var elevationStiffness: Float = stiffness * 2.5f var alphaStiffness: Float = stiffness * 2f var translationStiffness: Float = stiffness * 1.2f var elevationDampingRatio: Float = dampingRatio var alphaDampingRatio: Float = dampingRatio var translationDampingRatio: Float = dampingRatio private val translationOrigin = 0f private val elevationNone = 0f private val alphaNone = 0f private val alphaFull = 1f private val View.elevationFull: Float get() = [email protected] ?: 2f.dpToPx(resources) override fun preAnimateAdd(holder: RecyclerView.ViewHolder): Boolean { holder.itemView.alpha = alphaNone holder.itemView.elevation = elevationNone return true } override fun startAddAnimation( holder: RecyclerView.ViewHolder ): Boolean { holder.itemView.startFadeElevationInAnimation { onAnimateAddFinished(holder) } return true } override fun startRemoveAnimation( holder: RecyclerView.ViewHolder ): Boolean { holder.itemView.startFadeElevationOutAnimation { onAnimateRemoveFinished(holder) } return true } override fun startMoveAnimation( holder: RecyclerView.ViewHolder, deltaX: Int, deltaY: Int ): Boolean { holder.itemView.apply { val translationXTargetValue = if (deltaX != 0) translationOrigin else translationX val translationYTargetValue = if (deltaY != 0) translationOrigin else translationY translationXSpring(translationXTargetValue) .translationYSpring(translationYTargetValue) .force(translationStiffness, translationDampingRatio) .start { canceled -> if (canceled) { if (deltaX != 0) translationX = translationOrigin if (deltaY != 0) translationY = translationOrigin } alpha = alphaFull elevation = elevationFull onAnimateMoveFinished(holder) } } return true } override fun startOldHolderChangeAnimation( oldHolder: RecyclerView.ViewHolder, translationX: Float, translationY: Float ): Boolean { oldHolder.startChangeAnimation( alphaTargetValue = alphaNone, translationXTargetValue = translationX, translationYTargetValue = translationY, oldItem = true ) return true } override fun startNewHolderChangeAnimation( newHolder: RecyclerView.ViewHolder ): Boolean { onNewViewAnimateChangeStarted(newHolder) newHolder.startChangeAnimation( alphaTargetValue = alphaFull, translationXTargetValue = translationOrigin, translationYTargetValue = translationOrigin, oldItem = false ) return true } private fun RecyclerView.ViewHolder.startChangeAnimation( alphaTargetValue: Float, translationXTargetValue: Float, translationYTargetValue: Float, oldItem: Boolean ) { val elevationFull = itemView.elevationFull this.itemView.apply { elevationSpring(targetValue = elevationNone) .force(elevationStiffness, elevationDampingRatio) .after( fadeSpring(alphaTargetValue) .force(alphaStiffness, alphaDampingRatio) .add( translationXSpring(translationXTargetValue) .translationYSpring(translationYTargetValue) .force(translationStiffness, translationDampingRatio) ) .after( elevationSpring(targetValue = elevationFull) .force(elevationStiffness, elevationDampingRatio) ) ).start { itemView.alpha = alphaFull itemView.elevation = elevationFull itemView.translationX = translationOrigin itemView.translationY = translationOrigin onAnimateChangeFinished(this@startChangeAnimation, oldItem) } } } private fun View.startFadeElevationInAnimation(onAnimationFinished: () -> Unit) { fadeInSpring().force(stiffness = alphaStiffness, alphaDampingRatio) .after( elevationSpring(targetValue = elevationFull) .force(stiffness = elevationStiffness, dampingRatio = elevationDampingRatio) ) .start { onAnimationFinished() } } private fun View.startFadeElevationOutAnimation(onAnimationFinished: () -> Unit) { elevationSpring(targetValue = elevationNone) .force(elevationStiffness, elevationDampingRatio) .after( fadeOutSpring().force(stiffness = alphaStiffness, alphaDampingRatio) ) .start { alpha = alphaFull elevation = elevationFull onAnimationFinished() } } }
0
null
1
4
7eb4a9c1567c0bbe2e47d423f54b29af182bd1b8
6,435
jerry
Apache License 2.0
app/src/main/java/com/ng/ui/study/clock/ClockTestActivity.kt
jiangzhengnan
185,233,735
false
null
package com.ng.ui.study.clock import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.ng.ui.R /** * 描述:https://blog.csdn.net/qq_31715429/article/details/54668668 * @author Jzn * @date 2020-06-05 */ class ClockTestActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test_clock) } }
0
null
68
243
f528f8ad912f89c66ea3622f2e93a31db062cd93
442
NguiLib
Apache License 2.0
src/main/kotlin/io/snyk/plugin/ui/actions/SnykRunScanAction.kt
snyk
117,852,067
false
{"Kotlin": 1054870, "Java": 67741, "JavaScript": 9475, "SCSS": 3094, "HCL": 562}
package io.snyk.plugin.ui.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import io.snyk.plugin.analytics.getSelectedProducts import io.snyk.plugin.getSnykAnalyticsService import io.snyk.plugin.getSnykTaskQueueService import io.snyk.plugin.isCliDownloading import io.snyk.plugin.isScanRunning import io.snyk.plugin.pluginSettings import snyk.analytics.AnalysisIsTriggered /** * Run scan project with Snyk action. */ class SnykRunScanAction : AnAction(AllIcons.Actions.Execute), DumbAware { override fun actionPerformed(actionEvent: AnActionEvent) { getSnykTaskQueueService(actionEvent.project!!)?.scan(false) getSnykAnalyticsService().logAnalysisIsTriggered( AnalysisIsTriggered.builder() .analysisType(getSelectedProducts(pluginSettings())) .ide(AnalysisIsTriggered.Ide.JETBRAINS) .triggeredByUser(true) .build() ) } override fun update(actionEvent: AnActionEvent) { val project = actionEvent.project if (project != null && !project.isDisposed) { val settings = pluginSettings() actionEvent.presentation.isEnabled = !isCliDownloading() && !isScanRunning(project) && !settings.pluginFirstRun && !settings.token.isNullOrEmpty() } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
8
Kotlin
32
52
576936c7be6606488b38b050d2fea52deb701c2d
1,694
snyk-intellij-plugin
Apache License 2.0
library/src/main/java/org/secfirst/advancedsearch/models/FieldTypes.kt
securityfirst
159,126,929
false
null
package org.secfirst.advancedsearch.models enum class FieldTypes { PILLBOX, STRING, FREE_TEXT, AUTOCOMPLETE}
1
Kotlin
1
4
5f4fcec4c85bc9477d627a6940b8dbbb58159507
109
AdvancedSearch
MIT License
LABA5kt/src/commandInterfacePack/RemoveById.kt
deadxraver
778,738,033
false
{"Text": 3, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java Properties": 3, "Java": 221, "INI": 3, "XML": 27, "Ignore List": 4, "JAR Manifest": 1, "Kotlin": 48, "CSS": 4, "HTML": 85, "JavaScript": 9, "Markdown": 2}
package commandInterfacePack fun interface RemoveById { fun removeById() }
0
Java
0
0
3f262f3175c7142487f8d225e4aac85f8f197d77
79
Programming
MIT License
lib_common/src/main/java/com/dong/lib/common/base/BaseDialog.kt
MartinDong
123,133,917
false
null
package com.dong.lib.common.base import android.app.Activity import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Build import android.view.Gravity import android.view.Window import android.view.WindowManager.LayoutParams import com.dong.lib.common.R /** * 弹框使用的基础引用 */ open class BaseDialog : Dialog { var layoutParams: LayoutParams? = null private set private var mContext: Context? = null constructor(context: Context, themeResId: Int) : super(context, themeResId) { initView(context) } constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) { initView(context) } constructor(context: Context) : super(context) { initView(context) } constructor(activity: Activity) : super(activity) { initView(activity) } private fun initView(context: Context) { this.requestWindowFeature(Window.FEATURE_NO_TITLE) this.window!!.setBackgroundDrawableResource(R.drawable.transparent_bg) mContext = context val window = this.window window.setGravity(Gravity.TOP) layoutParams = window!!.attributes layoutParams!!.alpha = 1f window.attributes = layoutParams if (layoutParams != null) { layoutParams!!.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT layoutParams!!.gravity = Gravity.CENTER } } /** * @param context * * @param alpha 透明度 0.0f--1f(不透明) * * @param gravity 方向(Gravity.BOTTOM,Gravity.TOP,Gravity.LEFT,Gravity.RIGHT) */ constructor(context: Context, alpha: Float, gravity: Int) : super(context) { this.requestWindowFeature(Window.FEATURE_NO_TITLE) this.window!!.setBackgroundDrawableResource(R.drawable.transparent_bg) mContext = context val window = this.window layoutParams = window!!.attributes layoutParams!!.alpha = alpha window.attributes = layoutParams if (layoutParams != null) { layoutParams!!.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT layoutParams!!.gravity = gravity } } /** * 隐藏头部导航栏状态栏 */ fun skipTools() { if (Build.VERSION.SDK_INT < 19) { return } window!!.setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN) } /** * 设置全屏显示 */ fun setFullScreen() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.MATCH_PARENT lp.height = LayoutParams.MATCH_PARENT window.attributes = lp } /** * 设置宽度match_parent */ fun setFullScreenWidth() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.MATCH_PARENT lp.height = LayoutParams.WRAP_CONTENT window.attributes = lp } /** * 设置高度为match_parent */ fun setFullScreenHeight() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.WRAP_CONTENT lp.height = LayoutParams.MATCH_PARENT window.attributes = lp } fun setOnWhole() { window!!.setType(LayoutParams.TYPE_SYSTEM_ALERT) } }
1
null
1
4
071dfe7df24c387386ed033e34777111f54e4671
3,580
AndroidModuleDevPro
Apache License 2.0
lib_common/src/main/java/com/dong/lib/common/base/BaseDialog.kt
MartinDong
123,133,917
false
null
package com.dong.lib.common.base import android.app.Activity import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Build import android.view.Gravity import android.view.Window import android.view.WindowManager.LayoutParams import com.dong.lib.common.R /** * 弹框使用的基础引用 */ open class BaseDialog : Dialog { var layoutParams: LayoutParams? = null private set private var mContext: Context? = null constructor(context: Context, themeResId: Int) : super(context, themeResId) { initView(context) } constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) { initView(context) } constructor(context: Context) : super(context) { initView(context) } constructor(activity: Activity) : super(activity) { initView(activity) } private fun initView(context: Context) { this.requestWindowFeature(Window.FEATURE_NO_TITLE) this.window!!.setBackgroundDrawableResource(R.drawable.transparent_bg) mContext = context val window = this.window window.setGravity(Gravity.TOP) layoutParams = window!!.attributes layoutParams!!.alpha = 1f window.attributes = layoutParams if (layoutParams != null) { layoutParams!!.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT layoutParams!!.gravity = Gravity.CENTER } } /** * @param context * * @param alpha 透明度 0.0f--1f(不透明) * * @param gravity 方向(Gravity.BOTTOM,Gravity.TOP,Gravity.LEFT,Gravity.RIGHT) */ constructor(context: Context, alpha: Float, gravity: Int) : super(context) { this.requestWindowFeature(Window.FEATURE_NO_TITLE) this.window!!.setBackgroundDrawableResource(R.drawable.transparent_bg) mContext = context val window = this.window layoutParams = window!!.attributes layoutParams!!.alpha = alpha window.attributes = layoutParams if (layoutParams != null) { layoutParams!!.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT layoutParams!!.gravity = gravity } } /** * 隐藏头部导航栏状态栏 */ fun skipTools() { if (Build.VERSION.SDK_INT < 19) { return } window!!.setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN) } /** * 设置全屏显示 */ fun setFullScreen() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.MATCH_PARENT lp.height = LayoutParams.MATCH_PARENT window.attributes = lp } /** * 设置宽度match_parent */ fun setFullScreenWidth() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.MATCH_PARENT lp.height = LayoutParams.WRAP_CONTENT window.attributes = lp } /** * 设置高度为match_parent */ fun setFullScreenHeight() { val window = window window!!.decorView.setPadding(0, 0, 0, 0) val lp = window.attributes lp.width = LayoutParams.WRAP_CONTENT lp.height = LayoutParams.MATCH_PARENT window.attributes = lp } fun setOnWhole() { window!!.setType(LayoutParams.TYPE_SYSTEM_ALERT) } }
1
null
1
4
071dfe7df24c387386ed033e34777111f54e4671
3,580
AndroidModuleDevPro
Apache License 2.0
src/problemOfTheDay/problem169_MergeSort/problem196_MergeSort.kt
cunrein
159,861,371
false
null
package problemOfTheDay.problem169_MergeSort data class Node<T : Comparable<T>>(val value: T, var next: Node<T>? = null) class LinkedList<T : Comparable<T>>(var head: Node<T>?) { fun push(new_data: T) { /* allocate node */ val newNode = Node<T>(new_data) /* link the old list off the new node */ newNode.next = head /* move the head to point to the new node */ head = newNode } // Utility function to print the linked list fun print() { println(toString()) } override fun toString(): String { var headref = head var out = "" while (headref != null) { out += headref.value.toString() + " " headref = headref.next } return out } } private fun <T : Comparable<T>> sortedMerge(a: Node<T>?, b: Node<T>?): Node<T>? { val result: Node<T>? /* Base cases */ if (a == null) return b if (b == null) return a /* Pick either a or b, and recur */ if (a.value <= b.value) { result = a result.next = sortedMerge(a.next, b) } else { result = b result.next = sortedMerge(a, b.next) } return result } fun <T : Comparable<T>> mergeSort(h: Node<T>?): Node<T>? { if (h == null || h.next == null) return h // get the middle of the list val middle = getMiddle(h) val nextOfMiddle = middle?.next // set the next of middle node to null middle?.next = null // Apply mergeSort on left list val left = mergeSort(h) // Apply mergeSort on right list val right = mergeSort(nextOfMiddle) // Merge the left and right lists return sortedMerge(left, right) } fun <T : Comparable<T>> getMiddle(h: Node<T>?): Node<T>? { // Base case if (h == null) return h var fastptr = h.next var slowptr = h // Move fastptr by two and slow ptr by one // Finally slowptr will point to middle node while (fastptr != null) { fastptr = fastptr.next if (fastptr != null) { slowptr = slowptr?.next fastptr = fastptr.next } } return slowptr } fun main() { val node = Node(-2) val linkedList = LinkedList(node) linkedList.push(4) linkedList.push(0) linkedList.push(-1) linkedList.push(10) linkedList.push(12) linkedList.push(5) linkedList.print() val sorted = LinkedList(mergeSort(linkedList.head)) sorted.print() }
1
null
1
1
3488ccb200f993a84f1e9302eca3fe3977dbfcd9
2,501
ProblemOfTheDay
Apache License 2.0
mf/temp/src/main/kotlin/ch/maxant/kdc/mf/temp/boundary/TempResource.kt
maxant
174,798,779
false
{"YAML": 21, "Text": 1, "Ignore List": 24, "Markdown": 25, "Shell": 4, "PlantUML": 4, "Maven POM": 25, "JSON": 21, "HTML": 28, "Java": 88, "Java Properties": 12, "XML": 4, "JavaScript": 68, "SQL": 49, "Dockerfile": 1, "CSS": 5, "INI": 4, "JSON with Comments": 3, "Browserslist": 1, "EditorConfig": 1, "Kotlin": 143}
package ch.maxant.kdc.mf.temp.boundary import java.util.* import javax.inject.Inject import javax.persistence.EntityManager import javax.ws.rs.* import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response @Path("/temp") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) class TempResource( @Inject public var em: EntityManager ) { @GET @Path("/{id}") fun getById(@PathParam("id") id: UUID) = Response.ok("id").build() }
3
Kotlin
2
4
59c965b4635cfc2589fe187f69797d5273f93cca
485
kafka-data-consistency
MIT License
thirdparty/ktfx-jfoenix-layouts/src/main/kotlin/com/jfoenix/controls/KtfxJfxTogglePane.kt
hanggrian
102,934,147
false
{"Kotlin": 1146536, "CSS": 1653}
@file:JvmMultifileClass @file:JvmName("JfoenixLayoutsKt") package ktfx.jfoenix.layouts import com.jfoenix.controls.JFXTogglePane import javafx.scene.Node import ktfx.layouts.NodeContainer /** [JFXTogglePane] with dynamic-layout dsl support. Invoking dsl will only set its content. */ public open class KtfxJfxTogglePane : JFXTogglePane(), NodeContainer { final override fun <T : Node> addChild(child: T): T = child.also { contentNode = it } }
1
Kotlin
2
19
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
458
ktfx
Apache License 2.0
app/src/main/java/io/wookey/wallet/data/dao/SwapAddressBookDao.kt
WooKeyWallet
176,637,569
false
{"Kotlin": 448185, "Java": 407883, "C++": 135434, "CMake": 7579, "Shell": 1922}
package io.wookey.wallet.data.dao import androidx.lifecycle.LiveData import androidx.room.* import io.wookey.wallet.data.entity.AddressBook import io.wookey.wallet.data.entity.Asset import io.wookey.wallet.data.entity.SwapAddressBook @Dao interface SwapAddressBookDao { /** * Insert a addressBook in the database. * * @param addressBook the task to be inserted. */ @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(addressBook: SwapAddressBook) /** * Select all addressBooks from the address_books table. * * @return all addressBooks. */ @Query("SELECT * FROM swap_address_books ORDER BY _id DESC") fun loadAddressBooks(): LiveData<List<SwapAddressBook>> /** * Select all addressBooks from the address_books table by symbol. * * @return all addressBooks. */ @Query("SELECT * FROM swap_address_books WHERE symbol=:symbol ORDER BY _id DESC") fun loadAddressBooksBySymbol(symbol: String): LiveData<List<SwapAddressBook>> /** * Select all addressBooks from the address_books table by symbol and address. * * @return all addressBooks. */ @Query("SELECT * FROM swap_address_books WHERE symbol=:symbol AND address=:address ORDER BY _id DESC") fun loadAddressBooksBySymbolAndAddress(symbol: String, address: String): List<SwapAddressBook>? /** * Update a addressBook in the database * * @param addressBook the addressBook to be updated. */ @Update(onConflict = OnConflictStrategy.REPLACE) fun update(addressBook: SwapAddressBook) /** * Delete addressBook in the database * * @param addressBook the addressBook to be deleted. */ @Delete fun delete(addressBook: SwapAddressBook) }
6
Kotlin
20
23
93d0d6a4743e95ab2455bb6ae24b2cc6b616bd90
1,780
monero-wallet-android-app
MIT License
domain/src/main/java/com/anytypeio/anytype/domain/spaces/GetSpaceConfig.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.domain.spaces import com.anytypeio.anytype.core_models.Config import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.domain.base.AppCoroutineDispatchers import com.anytypeio.anytype.domain.base.ResultInteractor import com.anytypeio.anytype.domain.block.repo.BlockRepository import javax.inject.Inject class GetSpaceConfig @Inject constructor( private val repo: BlockRepository, dispatchers: AppCoroutineDispatchers ) : ResultInteractor<GetSpaceConfig.Params, Config>(dispatchers.io) { override suspend fun doWork(params: Params) = repo.getSpaceConfig(space = params.space) class Params(val space: Id) }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
670
anytype-kotlin
RSA Message-Digest License
feature/main/src/main/java/com/t8rin/imagetoolboxlite/feature/main/presentation/components/DonateSheet.kt
T8RIN
767,600,774
false
{"Kotlin": 3806441}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package com.t8rin.imagetoolboxlite.feature.main.presentation.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ContentCopy import androidx.compose.material.icons.rounded.Payments import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.rememberCoroutineScope 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.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.launch import com.t8rin.imagetoolboxlite.core.domain.BitcoinWallet import com.t8rin.imagetoolboxlite.core.domain.TONSpaceWallet import com.t8rin.imagetoolboxlite.core.domain.TONWallet import com.t8rin.imagetoolboxlite.core.domain.USDTWallet import com.t8rin.imagetoolboxlite.core.resources.R import com.t8rin.imagetoolboxlite.core.settings.presentation.LocalSettingsState import com.t8rin.imagetoolboxlite.core.ui.icons.material.Bitcoin import com.t8rin.imagetoolboxlite.core.ui.icons.material.Ton import com.t8rin.imagetoolboxlite.core.ui.icons.material.USDT import com.t8rin.imagetoolboxlite.core.ui.theme.BitcoinColor import com.t8rin.imagetoolboxlite.core.ui.theme.TONColor import com.t8rin.imagetoolboxlite.core.ui.theme.TONSpaceColor import com.t8rin.imagetoolboxlite.core.ui.theme.USDTColor import com.t8rin.imagetoolboxlite.core.ui.theme.inverse import com.t8rin.imagetoolboxlite.core.ui.utils.helper.ContextUtils.copyToClipboard import com.t8rin.imagetoolboxlite.core.ui.widget.buttons.EnhancedButton import com.t8rin.imagetoolboxlite.core.ui.widget.modifier.container import com.t8rin.imagetoolboxlite.core.ui.widget.other.LocalToastHostState import com.t8rin.imagetoolboxlite.core.ui.widget.preferences.PreferenceItem import com.t8rin.imagetoolboxlite.core.ui.widget.sheets.SimpleSheet import com.t8rin.imagetoolboxlite.core.ui.widget.text.AutoSizeText import com.t8rin.imagetoolboxlite.core.ui.widget.text.TitleItem private val topShape = RoundedCornerShape( topStart = 16.dp, topEnd = 16.dp, bottomStart = 6.dp, bottomEnd = 6.dp ) private val centerShape = RoundedCornerShape(6.dp) private val bottomShape = RoundedCornerShape( topStart = 6.dp, topEnd = 6.dp, bottomStart = 16.dp, bottomEnd = 16.dp ) @Composable fun DonateSheet( visible: MutableState<Boolean> ) { val context = LocalContext.current val toastHostState = LocalToastHostState.current val scope = rememberCoroutineScope() SimpleSheet( visible = visible, title = { TitleItem( text = stringResource(R.string.donation), icon = Icons.Rounded.Payments ) }, confirmButton = { EnhancedButton( containerColor = MaterialTheme.colorScheme.secondaryContainer, onClick = { visible.value = false }, ) { AutoSizeText(stringResource(R.string.close)) } }, sheetContent = { val darkMode = !LocalSettingsState.current.isNightMode Box { Column(Modifier.verticalScroll(rememberScrollState())) { Box( modifier = Modifier .padding(16.dp) .container(color = MaterialTheme.colorScheme.tertiaryContainer), contentAlignment = Alignment.Center ) { Text( text = stringResource(R.string.donation_sub), fontSize = 12.sp, modifier = Modifier.padding(8.dp), textAlign = TextAlign.Center, fontWeight = FontWeight.SemiBold, lineHeight = 14.sp, color = LocalContentColor.current.copy(alpha = 0.5f) ) } PreferenceItem( color = TONSpaceColor, contentColor = TONSpaceColor.inverse( fraction = { 1f }, darkMode = true ), shape = topShape, onClick = { context.apply { copyToClipboard( label = getString(R.string.ton_space), value = TONSpaceWallet ) scope.launch { toastHostState.showToast( icon = Icons.Rounded.ContentCopy, message = getString(R.string.copied), ) } } }, endIcon = Icons.Rounded.ContentCopy, startIcon = Icons.Rounded.Ton, title = stringResource(R.string.ton_space), subtitle = TONSpaceWallet ) Spacer(Modifier.height(4.dp)) PreferenceItem( color = TONColor, contentColor = TONColor.inverse( fraction = { 1f }, darkMode = darkMode ), shape = centerShape, onClick = { context.apply { copyToClipboard( label = getString(R.string.ton), value = TONWallet ) scope.launch { toastHostState.showToast( icon = Icons.Rounded.ContentCopy, message = getString(R.string.copied), ) } } }, endIcon = Icons.Rounded.ContentCopy, startIcon = Icons.Rounded.Ton, title = stringResource(R.string.ton), subtitle = TONWallet ) Spacer(Modifier.height(4.dp)) PreferenceItem( color = BitcoinColor, contentColor = BitcoinColor.inverse( fraction = { 1f }, darkMode = darkMode ), shape = centerShape, onClick = { context.apply { copyToClipboard( label = getString(R.string.bitcoin), value = BitcoinWallet ) scope.launch { toastHostState.showToast( icon = Icons.Rounded.ContentCopy, message = getString(R.string.copied), ) } } }, endIcon = Icons.Rounded.ContentCopy, title = stringResource(R.string.bitcoin), startIcon = Icons.Filled.Bitcoin, subtitle = BitcoinWallet ) Spacer(Modifier.height(4.dp)) PreferenceItem( color = USDTColor, shape = bottomShape, contentColor = USDTColor.inverse( fraction = { 1f }, darkMode = darkMode ), onClick = { context.apply { copyToClipboard( label = getString(R.string.usdt), value = USDTWallet ) scope.launch { toastHostState.showToast( icon = Icons.Rounded.ContentCopy, message = getString(R.string.copied), ) } } }, endIcon = Icons.Rounded.ContentCopy, title = stringResource(R.string.usdt), startIcon = Icons.Filled.USDT, subtitle = USDTWallet ) Spacer(Modifier.height(16.dp)) } } } ) }
5
Kotlin
0
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
10,636
ImageToolboxLite
Apache License 2.0
core/src/commonMain/kotlin/com/symbiosis/sdk/stuck/ClientsManagerExt.kt
symbiosis-finance
473,611,783
false
{"Kotlin": 563820, "Swift": 5851, "Ruby": 1700}
package com.symbiosis.sdk.stuck import com.symbiosis.sdk.ClientsManager import com.symbiosis.sdk.getCrossChainClient import com.symbiosis.sdk.network.NetworkClient import dev.icerock.moko.web3.WalletAddress import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.toList suspend fun ClientsManager.getStuckTransactions(address: WalletAddress): List<StuckTransaction> = getStuckTransactionsAsFlow(address).toList() suspend fun ClientsManager.getStuckTransactionsAsFlow(address: WalletAddress): Flow<StuckTransaction> = flow { allClients.forEach { client -> val advisorUrl = findAdvisorUrl(client.networkClient) ?: return@forEach emitAll(client.getStuckTransactions(address, allClients, advisorUrl).asFlow()) } } private fun ClientsManager.findAdvisorUrl(networkClient: NetworkClient): String? { val crossChains = allClients.mapNotNull { otherClient -> getCrossChainClient(networkClient.network, otherClient.networkClient.network) } if (crossChains.isEmpty()) return null val firstAdvisorUrl = crossChains.first().crossChain.advisorUrl if (crossChains.any { it.crossChain.advisorUrl != firstAdvisorUrl }) error("Multiple advisor url available for current configuration, but this is not supported yet") return firstAdvisorUrl }
0
Kotlin
2
4
e8b1c424c62a847a5339039864223e65fdb2cbae
1,447
mobile-sdk
Apache License 2.0
delegapter/src/main/kotlin/net/aquadc/delegapter/diff.kt
Miha-x64
486,312,447
false
null
package net.aquadc.delegapter import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil /** * A delegate which supports diffing. */ abstract class DiffDelegate<D : Any> : DiffUtil.ItemCallback<D>(), (ViewGroup) -> VH<*, *, D> // Delegate<D> /** * Creates a [DiffDelegate] from [this] one using [itemDiffer]. */ operator fun <D : Any> ((ViewGroup) -> VH<*, *, D>).plus(itemDiffer: DiffUtil.ItemCallback<D>): DiffDelegate<D> = object : DelegatedDiffDelegate<D>(this) { override fun areItemsTheSame(oldItem: D, newItem: D): Boolean = itemDiffer.areItemsTheSame(oldItem, newItem) override fun areContentsTheSame(oldItem: D, newItem: D): Boolean = itemDiffer.areContentsTheSame(oldItem, newItem) override fun getChangePayload(oldItem: D, newItem: D): Any? = itemDiffer.getChangePayload(oldItem, newItem) } /** * Creates a [DiffDelegate] from [this] one * accepting separate [areItemsTheSame], [areContentsTheSame], and [getChangePayload] functions. */ inline fun <D : Any> ((ViewGroup) -> VH<*, *, D>).diff( crossinline areItemsTheSame: (oldItem: D, newItem: D) -> Boolean = { _, _ -> true }, crossinline areContentsTheSame: (oldItem: D, newItem: D) -> Boolean = Any::equals, crossinline getChangePayload: (oldItem: D, newItem: D) -> Any? = { _, _ -> null } ): DiffDelegate<D> = object : DelegatedDiffDelegate<D>(this) { override fun areItemsTheSame(oldItem: D, newItem: D): Boolean = areItemsTheSame.invoke(oldItem, newItem) override fun areContentsTheSame(oldItem: D, newItem: D): Boolean = areContentsTheSame.invoke(oldItem, newItem) override fun getChangePayload(oldItem: D, newItem: D): Any? = getChangePayload.invoke(oldItem, newItem) } /** * Avoids overriding existing diffing machinery of [this] delegate. */ @Suppress("DeprecatedCallableAddReplaceWith", "UnusedReceiverParameter") @Deprecated("Why you wanna do this?!", level = DeprecationLevel.ERROR) inline fun <D : Any> DiffDelegate<D>.diff( crossinline areItemsTheSame: (oldItem: D, newItem: D) -> Boolean = { _, _ -> true }, crossinline areContentsTheSame: (oldItem: D, newItem: D) -> Boolean = Any::equals, crossinline getChangePayload: (oldItem: D, newItem: D) -> Any? = { _, _ -> null } ): DiffDelegate<D> = throw AssertionError() /** * Avoids overriding existing diffing machinery of [this] delegate. */ @Suppress("DeprecatedCallableAddReplaceWith", "UNUSED_PARAMETER") @Deprecated("Why you wanna do this?!", level = DeprecationLevel.ERROR) operator fun <D : Any> DiffDelegate<D>.plus(cb: DiffUtil.ItemCallback<D>): DiffDelegate<D> = throw AssertionError() /** * Creates an equating predicate. */ @Suppress("UNCHECKED_CAST", "USELESS_CAST") fun <D : Any> equate(): (D, D) -> Boolean = { old: D, new: D -> (old == new) as Any } as (D, D) -> Boolean /** * Creates an equating predicate using the [selector] function to extract a value for equating. */ @Suppress("UNCHECKED_CAST", "USELESS_CAST") inline fun <D> equateBy(crossinline selector: (D) -> Any?): (D, D) -> Boolean = { old: D, new: D -> (selector(old) == selector(new)) as Any } as (D, D) -> Boolean @PublishedApi internal abstract class DelegatedDiffDelegate<D : Any>( private val d: (parent: ViewGroup) -> VH<*, *, D> // Delegate<D> ) : DiffDelegate<D>() { final override fun invoke(p1: ViewGroup): VH<*, *, D> = d.invoke(p1) final override fun hashCode(): Int = d.hashCode() final override fun equals(other: Any?): Boolean = other is DelegatedDiffDelegate<*> && d == other.d final override fun toString(): String = d.toString() }
0
Kotlin
0
10
e8518734d42b73f8c7a1eb164c07285d2c81ccd0
3,595
Delegapter
Apache License 2.0
app/src/main/java/uk/co/sentinelweb/qcstechtest/ui/main/CommitModelMapper.kt
sentinelweb
212,645,607
false
null
package uk.co.sentinelweb.qcstechtest.ui.main import uk.co.sentinelweb.qcstechtest.domain.Commit class CommitModelMapper { fun map(commitDomain: Commit): CommitModel { return CommitModel( commitDomain.sha, commitDomain.message, commitDomain.date.toString(), commitDomain.author.name, commitDomain.author.imageUrl ) } }
0
Kotlin
0
0
c708afe20bbee3fd54b0598803517e32566bbc29
406
qcs_test
Apache License 2.0
geo/src/androidMain/kotlin/dev/icerock/moko/geo/LocationTracker.kt
ln-12
328,631,686
true
{"Kotlin": 17753, "Shell": 54}
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.geo import android.content.Context import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import dev.icerock.moko.permissions.Permission import dev.icerock.moko.permissions.PermissionsController import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch actual class LocationTracker( actual val permissionsController: PermissionsController, interval: Long = 1000, priority: Int = LocationRequest.PRIORITY_HIGH_ACCURACY ) : LocationCallback() { private var locationProviderClient: FusedLocationProviderClient? = null private var isStarted: Boolean = false private val locationRequest = LocationRequest().also { it.interval = interval it.priority = priority } private val locationsChannel = Channel<LatLng>(Channel.BUFFERED) private val trackerScope = CoroutineScope(Dispatchers.Main) fun bind(lifecycle: Lifecycle, context: Context, fragmentManager: FragmentManager) { permissionsController.bind(lifecycle, fragmentManager) locationProviderClient = FusedLocationProviderClient(context) if (isStarted) { locationProviderClient?.requestLocationUpdates(locationRequest, this, null) } lifecycle.addObserver(object : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { locationProviderClient?.removeLocationUpdates(this@LocationTracker) locationProviderClient = null } }) } override fun onLocationResult(locationResult: LocationResult) { super.onLocationResult(locationResult) val latLng = LatLng( locationResult.lastLocation.latitude, locationResult.lastLocation.longitude ) trackerScope.launch { locationsChannel.send(latLng) } } actual suspend fun startTracking() { permissionsController.providePermission(Permission.LOCATION) // if permissions request failed - execution stops here isStarted = true locationProviderClient?.requestLocationUpdates(locationRequest, this, null) } actual fun stopTracking() { isStarted = false locationProviderClient?.removeLocationUpdates(this) } actual fun getLocationsFlow(): Flow<LatLng> { return channelFlow { val sendChannel = channel val job = launch { while (isActive) { val latLng = locationsChannel.receive() sendChannel.send(latLng) } } awaitClose { job.cancel() } } } }
0
null
0
0
8bbb5ed14ed7ab22cf5b45b62dd72f9fae60e2dd
3,347
moko-geo
Apache License 2.0
annotations/src/main/kotlin/io/github/pshegger/rag/ModelBinding.kt
PsHegger
219,745,585
false
null
package io.github.pshegger.rag @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.SOURCE) annotation class ModelBinding( val layoutId: Int, val clickListener: Boolean = false, val namePrefix: String = "" )
0
Kotlin
3
55
158fd0078044d753ba5a3376bfe100cd33611848
231
recycleradapter-generator
MIT License
basick/src/main/java/com/mozhimen/basick/taskk/temps/TaskKPoll.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.taskk.temps import androidx.lifecycle.LifecycleOwner import com.mozhimen.basick.taskk.commons.ITaskK import kotlinx.coroutines.* class TaskKPoll(owner: LifecycleOwner) : ITaskK(owner) { private var _pollingScope: CoroutineScope? = null fun isActive(): Boolean = _pollingScope != null && _pollingScope!!.isActive fun start(interval: Long, task: suspend () -> Unit) { if (isActive()) return val scope = CoroutineScope(Dispatchers.IO) scope.launch { while (isActive) { try { task.invoke() } catch (e: Exception) { if (e is CancellationException) return@launch e.printStackTrace() } delay(interval) } } _pollingScope = scope } override fun cancel() { if (!isActive()) return _pollingScope?.cancel() _pollingScope = null } }
0
Kotlin
0
2
0b6d7642b1bd7c697d9107c4135c1f2592d4b9d5
996
SwiftKit
Apache License 2.0
app/src/main/java/com/nexhub/homedia/views/home/presentation/components/HomeSideBar.kt
NexhubFR
788,051,929
false
{"Kotlin": 68024}
package com.nexhub.homedia.views.home.presentation.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.tv.material3.ExperimentalTvMaterial3Api import androidx.tv.material3.Icon import androidx.tv.material3.MaterialTheme import com.nexhub.homedia.R import com.nexhub.homedia.utils.components.HomediaButtonCustomContent enum class SideBarItem { SEARCH, HOME, RECORD, SETTINGS } @Composable fun HomeSideBar( modifier: Modifier, sideBarItemSize: Modifier, sideBarItemIconSize: Dp, sideBarItemRoundedCornerShape: Dp, spaceBetweenSideBarItem: Dp, selectedCallback: (SideBarItem) -> Unit) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { HomeSideBarItem( modifier = sideBarItemSize, type = SideBarItem.SEARCH, icon = painterResource(id = R.drawable.search), iconSize = sideBarItemIconSize, roundedCornerShape = sideBarItemRoundedCornerShape, selectedCallback = selectedCallback, ) Spacer(modifier = Modifier.size(spaceBetweenSideBarItem)) HomeSideBarItem( modifier = sideBarItemSize, type = SideBarItem.HOME, icon = painterResource(id = R.drawable.home), iconSize = sideBarItemIconSize, roundedCornerShape = sideBarItemRoundedCornerShape, selectedCallback = selectedCallback ) Spacer(modifier = Modifier.size(spaceBetweenSideBarItem)) HomeSideBarItem( modifier = sideBarItemSize, type = SideBarItem.RECORD, icon = painterResource(id = R.drawable.movie), iconSize = sideBarItemIconSize, roundedCornerShape = sideBarItemRoundedCornerShape, selectedCallback = selectedCallback ) Spacer(modifier = Modifier.size(spaceBetweenSideBarItem)) HomeSideBarItem( modifier = sideBarItemSize, type = SideBarItem.SETTINGS, icon = painterResource(id = R.drawable.settings), iconSize = sideBarItemIconSize, roundedCornerShape = sideBarItemRoundedCornerShape, selectedCallback = selectedCallback ) } } @Composable @OptIn(ExperimentalTvMaterial3Api::class) fun HomeSideBarItem( modifier: Modifier, type: SideBarItem, icon: Painter, iconSize: Dp, roundedCornerShape: Dp, selectedCallback: (SideBarItem) -> Unit) { HomediaButtonCustomContent( modifier = modifier, containerColor = MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5F), focusedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.7F), shape = RoundedCornerShape(roundedCornerShape), focusedShape = RoundedCornerShape(roundedCornerShape), scale = 1F, focusedScale = 1.05F, onClick = { selectedCallback(type) }) { Box( contentAlignment = Alignment.Center, modifier = modifier.fillMaxWidth() ) { Icon( icon, contentDescription = "", modifier = Modifier.size(iconSize), tint = MaterialTheme.colorScheme.secondary, ) } } }
1
Kotlin
0
0
fc0b4f26568fdb12200197c11644ceb874b0e448
3,933
homedia
MIT License
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/CustomFrameDialogContent.kt
dansanduleac
232,394,039
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.customFrameDecorations.header import net.miginfocom.swing.MigLayout import java.awt.Color import java.awt.Container import java.awt.Window import javax.swing.* class CustomFrameDialogContent private constructor(val window: Window, content: Container, titleBackgroundColor: Color? = null): JPanel() { companion object { @JvmStatic fun getCustomContentHolder(window: Window, content: JComponent) = getCustomContentHolder(window, content, null) @JvmStatic fun getCustomContentHolder(window: Window, content: JComponent, titleBackgroundColor: Color? = null): JComponent { if (content is CustomFrameDialogContent) return content when (window) { is JWindow -> window.rootPane is JDialog -> { if (window.isUndecorated) null else window.rootPane } is JFrame -> window.rootPane else -> null } ?: return content return CustomFrameDialogContent(window, content, titleBackgroundColor) } } private val header: CustomHeader = CustomHeader.create(window) init { layout = MigLayout("novisualpadding, ins 0, gap 0, fill, flowy, hidemode 2", "", "[min!][]") titleBackgroundColor?.let { header.background = it } add(header, "growx, wmin 100") add(content, "grow") } fun updateLayout() { if(window is JDialog && window.isUndecorated) header.isVisible = false } val headerHeight: Int get() = if(header.isVisible) header.preferredSize.height else 0 }
1
null
1
1
9d972139413a00942fd4a0c58998ac8a2d80a493
1,825
intellij-community
Apache License 2.0
ChangeSkinDemo/app/src/main/java/com/renyu/changeskindemo/skin/SkinFactory.kt
r17171709
23,950,456
false
{"Java": 796606, "Kotlin": 611868, "Dart": 421620, "Groovy": 32447, "C++": 31140, "CMake": 9722, "Python": 8028, "HTML": 4392, "Ruby": 1354, "Objective-C": 791, "C": 734, "Swift": 404}
package com.renyu.changeskindemo.skin import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import androidx.appcompat.app.AppCompatDelegate import com.renyu.changeskindemo.R class SkinFactory : LayoutInflater.Factory2 { private lateinit var delegate: AppCompatDelegate private val skinViewList by lazy { ArrayList<SkinView>() } fun setDelegate(delegate: AppCompatDelegate) { this.delegate = delegate } override fun onCreateView( parent: View?, name: String, context: Context, attrs: AttributeSet ): View? { var view = delegate.createView(parent, name, context, attrs) // 万一系统创建出来是空,那么我们来补救 if (view == null) { val utils = Utils() view = utils.createViewFromTag(name, context, attrs) } // 收集需要换肤的View collectSkinView(context, attrs, view) return view } /** * Factory2是继承Factory的,所以主要重写Factory2的onCreateView,不必理会Factory的重写方法了 */ override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? { return null } /** * 通过自定义属性isSupport,从创建出来的很多View中找到支持换肤的那些保存到map中 */ private fun collectSkinView(context: Context, attrs: AttributeSet, view: View) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.Skinable) val isSupport = typedArray.getBoolean(R.styleable.Skinable_isSupport, false) if (isSupport) { val length = attrs.attributeCount val attrMap = HashMap<String, String>() // 遍历所有属性 for (i in 0 until length) { val attrName = attrs.getAttributeName(i) val attrValue = attrs.getAttributeValue(i) attrMap[attrName] = attrValue } val skinView = SkinView(view, attrMap) skinViewList.add(skinView) } typedArray.recycle() } fun changeSkin() { skinViewList.forEach { it.changeSkin() } } }
8
Java
333
612
ee75780c1187355d81bab329e62ecaad985d6832
2,105
StudyDemo
Apache License 2.0
app/src/main/java/dev/staticvar/vlr/utils/TimeElapsed.kt
unused-variable
395,079,125
false
null
package dev.staticvar.vlr.utils import androidx.annotation.VisibleForTesting import java.util.* import kotlin.time.Duration /** * Time elapsed A simple in-memory time system to prevent a key from being accessed before its * allocated elapsed time. * * @constructor Create empty Time elapsed */ object TimeElapsed { private var timeMap: MutableMap<String, Long> = mutableMapOf() fun start(key: String, expireIn: Duration) { // Create a new entry in map or override existing with expiration time timeMap[key] = (Calendar.getInstance().timeInMillis + expireIn.inWholeMilliseconds) println( "$key started at ${Calendar.getInstance().timeInMillis} will expire in ${expireIn.absoluteValue}" ) } fun hasElapsed(key: String): Boolean { return timeMap[key]?.let { expireDuration -> // If key exists then perform check println( "Elapsed check for $key, current time ${Calendar.getInstance().timeInMillis}, set to expire at $expireDuration" ) expireDuration < Calendar.getInstance().timeInMillis } ?: true.also { // Key doesn't exist, return true println("$key not in records") } } fun reset(key: String) { // Set expired time i { "Resetting $key" } timeMap[key] = Calendar.getInstance().timeInMillis - 1 } @VisibleForTesting internal fun timeForKey(key: String) = timeMap[key] @VisibleForTesting internal fun resetCache() = timeMap.clear() }
7
Kotlin
0
7
9726fc482150c7d66a2b6c00b46dca2942819151
1,455
vlr-gg
The Unlicense
app/src/main/java/com/wisal/android/todoapp/testing/repositories/TasksRepository.kt
wisalmuhammad
466,711,487
false
null
package com.wisal.android.todoapp.testing.repositories import androidx.lifecycle.LiveData import com.wisal.android.todoapp.testing.data.Result import com.wisal.android.todoapp.testing.data.Task interface TasksRepository { fun observeTasks(): LiveData<Result<List<Task>>> fun observeTask(id: String): LiveData<Result<Task>> suspend fun completeTask(id: String) suspend fun completeTask(task: Task) suspend fun activateTask(id: String) suspend fun activateTask(task: Task) suspend fun getTask(taskId: String): Result<Task> suspend fun getTasks(): Result<List<Task>> suspend fun saveTask(task: Task) suspend fun updateTask(task: Task) suspend fun clearAllCompletedTasks() suspend fun deleteAllTasks() suspend fun deleteTask(taskId: String) suspend fun fetchAllToDoTasks(isUpdate: Boolean): Result<List<Task>> }
0
Kotlin
0
0
43e98f033707628a4ad2be2bfce847e6d5e811af
880
ToDo-App-with-TestDriven-Development
MIT License
src/test/kotlin/de/cvguy/kotlin/koreander/KoreanderTest.kt
lukasjapan
112,826,577
false
null
package de.cvguy.kotlin.koreander import de.cvguy.kotlin.koreander.filter.KoreanderFilter import org.hamcrest.CoreMatchers.* import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import java.io.File import java.io.InputStream class KoreanderTest { val koreander = Koreander() val unit = Koreander.typeOf(Unit) val string = Koreander.typeOf(String) @Test fun canCompileString() { val result = koreander.compile("", unit) assertThat(result, instanceOf(CompiledTemplate::class.java)) } @Test fun canCompileURL() { val url = javaClass.getResource("/empty.kor") val result = koreander.compile(url, unit) assertThat(result, instanceOf(CompiledTemplate::class.java)) } @Test fun conCompileInputStream() { val inputStream: InputStream = "".byteInputStream() val result = koreander.compile(inputStream, unit) assertThat(result, instanceOf(CompiledTemplate::class.java)) } @Test fun canCompileFile() { val file = File("src/test/resources/empty.kor") val result = koreander.compile(file, unit) assertThat(result, instanceOf(CompiledTemplate::class.java)) } @Test fun canRenderCompiledTemplate() { val compiled = koreander.compile("", unit) val result = koreander.render(compiled, Unit) assertThat(result, instanceOf(String::class.java)) } @Test fun multipleCompiles() { val compiled = koreander.compile("", unit) val result = koreander.render(compiled, Unit) assertThat(result, instanceOf(String::class.java)) val compiled2 = koreander.compile("", string) val result2 = koreander.render(compiled2, String) assertThat(result2, instanceOf(String::class.java)) val result3 = koreander.render(compiled, Unit) assertThat(result3, instanceOf(String::class.java)) } @Test fun canRenderCompiledTemplateUnsafe() { val compiled = koreander.compile("", unit) val result = koreander.render(compiled, Unit) assertThat(result, instanceOf(String::class.java)) } @Test fun canRenderString() { val result = koreander.render("", unit) assertThat(result, instanceOf(String::class.java)) } @Test fun canRenderURL() { val url = javaClass.getResource("/empty.kor") val result = koreander.render(url, unit) assertThat(result, instanceOf(String::class.java)) } @Test fun canRenderFile() { val file = File("src/test/resources/empty.kor") val result = koreander.render(file, unit) assertThat(result, instanceOf(String::class.java)) } @Test fun conRenderInputStream() { val inputStream: InputStream = "".byteInputStream() val result = koreander.render(inputStream, unit) assertThat(result, instanceOf(String::class.java)) } @Test fun canAddCustomFilter() { koreander.filters["test"] = object : KoreanderFilter { override fun filter(input: String) = "out" } val result = koreander.render(":test", unit) assertThat(result, equalTo("out")) } }
3
Kotlin
3
28
4bb233d5d4b36055fcdba53e8d9e92fa500cf6e6
3,199
koreander
MIT License
app/src/main/java/com/example/socialhelper/viewmodels/IntroViewModel.kt
VaasKout
290,493,681
false
null
package com.example.socialhelper.viewmodels import android.app.Application import android.view.animation.AnimationUtils import android.widget.TextView import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import com.example.socialhelper.R import com.example.socialhelper.database.Info import com.example.socialhelper.database.DataBase import com.example.socialhelper.database.WheelData import com.example.socialhelper.repository.InfoRepository import kotlinx.coroutines.* class IntroViewModel(application: Application) : AndroidViewModel(application) { private val repository: InfoRepository val allInfo: LiveData<Info> val data: LiveData<List<WheelData>> //init data from databases init { val infoDao = DataBase.getInfoDatabase(application).infoDao() repository = InfoRepository(infoDao) allInfo = repository.allInfo data = repository.allWheelData } suspend fun animate(list: List<TextView>) { val appear = AnimationUtils.loadAnimation(getApplication(), R.anim.fade_in) for (i in list) { i.alpha = 1.0F i.startAnimation(appear) delay(appear.duration) i.clearAnimation() } delay(appear.duration) } }
1
null
1
1
8ab7da3ebb0c15e323a2944d2435d602b0c356e5
1,285
SocialHelper_AndroidApp
Apache License 2.0
src/main/kotlin/org/phc1990/mammok/random/Random.kt
phc1990
266,526,841
false
null
package org.phc1990.mammok.random import java.util.Random /** * Singleton used for all random operations. * * @author [<NAME>](https://github.com/phc1990) - May 25, 2020 */ object Random { /** The underlying Java random instance. */ private val random = Random() /** Returns the underlying Java random instance. */ internal fun getJava(): Random = random /** Sets the [seed] of the random generator. */ fun setSeed(seed: Long) = random.setSeed(seed) /** Returns a random uniformly-distributed double in the [0,1] interval. */ internal fun uniformDouble(): Double = random.nextDouble() /** Returns a random uniformly-distributed integer in the [0, [max]) interval (i.e. excluding [max]). */ internal fun uniformInteger(max: Int) = random.nextInt(max) /** Returns a random uniformly-distributed integer in the [[min], [max]) interval (i.e. excluding [max]). */ internal fun uniformInteger(min: Int, max: Int) = min + random.nextInt(max - min) /** * Returns an iterator over a random non-repeated uniformly-distributed integer iterator in the [[min], [max]) * interval (i.e. excluding [max]). */ internal fun nonRepeatingUniformInteger(min: Int, max: Int): Iterator<Int> = NonRepeatingInteger(min, max) /** Returns a random uniformly distributed boolean in the [false, true] interval. */ internal fun uniformBoolean(): Boolean = random.nextBoolean() }
0
Kotlin
0
0
32fc16ca4758c3c283ee4aa873ccf790a2d24210
1,441
mammok
Apache License 2.0
android/app/src/main/java/uvg/edu/gt/smartfridge/ui/theme/Type.kt
DanielRasho
680,686,449
false
{"Kotlin": 63772, "Nix": 825, "Rust": 45}
package uvg.edu.gt.smartfridge.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import uvg.edu.gt.smartfridge.R // Definition of Outfit font family, the main app font. val outfitFamily = FontFamily( Font(R.font.outfit_regular, FontWeight.Normal), Font(R.font.outfit_black, FontWeight.Black), Font(R.font.outfit_bold, FontWeight.Bold), Font(R.font.outfit_extrabold, FontWeight.ExtraBold), Font(R.font.outfit_semibold, FontWeight.SemiBold), Font(R.font.outfit_medium, FontWeight.Medium), Font(R.font.outfit_light, FontWeight.Light), Font(R.font.outfit_extralight, FontWeight.ExtraLight), Font(R.font.outfit_thin, FontWeight.Thin) ) // Definition of Typography styles. val appTypography = Typography( displayLarge = TextStyle( fontFamily = outfitFamily, fontSize = 44.sp, fontWeight = FontWeight.Black ), //44 displayMedium = TextStyle( fontFamily = outfitFamily, fontSize = 24.sp, fontWeight = FontWeight.Black ), //24 titleMedium = TextStyle( fontFamily = outfitFamily, fontSize = 24.sp, fontWeight = FontWeight.Normal ), // 32 bodyLarge = TextStyle( fontFamily = outfitFamily, fontSize = 20.sp, fontWeight = FontWeight.Normal ), //20 bodyMedium = TextStyle( fontFamily = outfitFamily, fontSize = 16.sp, fontWeight = FontWeight.Normal ), // 16 labelLarge = TextStyle( fontFamily = outfitFamily, fontSize = 20.sp, fontWeight = FontWeight.Normal ), // 16 labelMedium = TextStyle( fontFamily = outfitFamily, fontSize = 16.sp, fontWeight = FontWeight.Normal ), // 12 labelSmall = TextStyle( fontFamily = outfitFamily, fontSize = 12.sp, fontWeight = FontWeight.Normal ), // 8 )
0
Kotlin
0
0
44b83608ccdef7a65f68211fa9689b38baf97658
2,086
SmartFridge
MIT License
app/src/main/java/com/example/androiddevchallenge/components/Controllers.kt
GerardPaligot
344,247,312
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.components import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Pause import androidx.compose.material.icons.rounded.Stop import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.ui.theme.greenDark import com.example.androiddevchallenge.ui.theme.purpleDark import com.example.androiddevchallenge.ui.theme.purpleLightest @Composable fun Controllers( modifier: Modifier = Modifier, onPause: () -> Unit, onStart: () -> Unit, onStop: () -> Unit ) { Row( modifier = modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround ) { Pause(onPause = onPause) Start(onStart = onStart) Stop(onStop = onStop) } } @Composable internal fun Stop(onStop: () -> Unit) { Button( color = purpleLightest, onClick = onStop ) { Icon( imageVector = Icons.Rounded.Stop, contentDescription = "Stop", tint = purpleDark, modifier = Modifier .size(45.dp) .align(alignment = Alignment.Center) ) } } @Composable internal fun Start(onStart: () -> Unit) { Button( color = com.example.androiddevchallenge.ui.theme.green, onClick = onStart ) { Text( text = "START", style = MaterialTheme.typography.button, color = greenDark, modifier = Modifier.align(alignment = Alignment.Center) ) } } @Composable internal fun Pause(onPause: () -> Unit) { Button( color = purpleLightest, onClick = onPause ) { Icon( imageVector = Icons.Rounded.Pause, contentDescription = "Pause", tint = purpleDark, modifier = Modifier .size(35.dp) .align(alignment = Alignment.Center) ) } } @Composable internal fun Button( color: Color, onClick: () -> Unit, modifier: Modifier = Modifier, content: @Composable BoxScope.() -> Unit ) { val interaction = remember { MutableInteractionSource() } val isPressed by interaction.collectIsPressedAsState() val colorAnimated by animateColorAsState( targetValue = if (isPressed) color else Color.White, animationSpec = tween(400) ) val elevation by animateDpAsState( targetValue = if (isPressed) 3.dp else 8.dp, animationSpec = tween(400) ) val brush = Brush.verticalGradient(listOf(color, colorAnimated)) Box( modifier .shadow(elevation = elevation, shape = CircleShape) .border(width = 5.dp, color = Color.White, shape = CircleShape) .background(brush = brush, shape = CircleShape) .clip(CircleShape) .width(100.dp) .aspectRatio(1f) .clickable( interactionSource = interaction, indication = null, onClick = onClick ), content = content ) }
0
Kotlin
11
52
21478e5b2f33bf7f783ae2d7bae2e1c4d6c3c529
5,068
android-countdown
Apache License 2.0
ml-development-tools/src/test/kotlin/com/marklogic/client/test/dbfunction/fntestconf.kt
marklogic
17,642,544
false
null
/* * Copyright (c) 2022 MarkLogic Corporation * * 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.marklogic.client.test.dbfunction import com.fasterxml.jackson.databind.ObjectWriter import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.marklogic.client.DatabaseClientFactory import com.marklogic.client.io.DocumentMetadataHandle import com.marklogic.client.io.InputStreamHandle import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody const val contentDbName = "DBFUnitTest" const val modulesDbName = "DBFUnitTestModules" const val serverName = "DBFUnitTest" val host = System.getenv("TEST_HOST") ?: "localhost" val serverPort = System.getenv("TEST_PORT")?.toInt() ?: 8016 fun main(args: Array<String>) { val mapper = jacksonObjectMapper() val serializer = mapper.writerWithDefaultPrettyPrinter() /* TODO: skip setup operations where result is present teardown where result is absent amp the test inspector to add header create roles and users parameterize the port, user name, etc */ when(val operation = if (args.isNotEmpty()) args[0] else "setup") { "setup" -> dbfTestSetup(serializer) "teardown" -> dbfTestTeardown(serializer) else -> throw java.lang.IllegalArgumentException("unknown operation: $operation") } } fun dbfTestSetup(serializer: ObjectWriter) { setupServer(serializer) setupModules() } fun dbfTestTeardown(serializer: ObjectWriter) { teardownServer(serializer) } fun setupServer(serializer: ObjectWriter) { val dbClient = DatabaseClientFactory.newClient( host, 8002, DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val client = dbClient.clientImplementation as OkHttpClient for (dbName in listOf(contentDbName, modulesDbName)) { createEntity( client, serializer, "databases", "database", dbName, mapOf("database-name" to dbName) ) val forestName = "$dbName-1" createEntity( client, serializer, "forests", "forest", forestName, mapOf("forest-name" to forestName, "database" to dbName) ) } val userName = "rest-reader" if (!existsEntity(client, "users", "user", userName)) { createEntity( client, serializer, "users", "user", userName, mapOf( "user-name" to userName, "password" to "x", "role" to listOf(userName) ) ) } createEntity( client, serializer, "servers?group-id=Default&server-type=http", "appserver", serverName, mapOf( "server-name" to serverName, "root" to "/", "port" to serverPort, "content-database" to contentDbName, "modules-database" to modulesDbName ) ) dbClient.release() } fun existsEntity(client: OkHttpClient, address: String, name: String, instanceName: String) : Boolean { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}/${instanceName}""") .get() .build() ).execute() val status = response.code if (status < 400) return true if (status == 404) return false throw RuntimeException("""Could not create $instanceName ${name}: $status""") } fun createEntity(client: OkHttpClient, serializer: ObjectWriter, address: String, name: String, instanceName: String, instancedef: Map<String,Any>) { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}""") .post( serializer.writeValueAsString(instancedef).toRequestBody("application/json".toMediaTypeOrNull()) ) .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not create $instanceName ${name}: ${response.code}""") } } fun setupModules() { val dbClient = DatabaseClientFactory.newClient( host, 8000, "DBFUnitTestModules", DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val docMgr = dbClient.newJSONDocumentManager() val docMeta = DocumentMetadataHandle() val docPerm = docMeta.permissions docPerm.add("rest-reader", DocumentMetadataHandle.Capability.EXECUTE) for (scriptName in listOf("testInspector")) { val scriptPath = """./${scriptName}.sjs""" val scriptUri = """/dbf/test/${scriptName}.sjs""" val inspectorStream = DBFunctionTestUtil.getResourceAsStream(scriptPath) docMgr.write(scriptUri, docMeta, InputStreamHandle(inspectorStream)) } dbClient.release() } fun teardownServer(serializer: ObjectWriter) { val dbClient = DatabaseClientFactory.newClient( host, 8002, DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val client = dbClient.clientImplementation as OkHttpClient val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/servers/$serverName/properties?group-id=Default""") .put(serializer.writeValueAsString( mapOf("content-database" to 0, "modules-database" to 0) ).toRequestBody("application/json".toMediaTypeOrNull()) ) .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not detach $serverName appserver: ${response.code}""") } for (dbName in listOf(contentDbName, modulesDbName)) { deleteEntity(client, """databases/${dbName}?forest-delete=data""", "database", dbName) } deleteEntity(client, """servers/$serverName?group-id=Default""", "appserver", serverName) dbClient.release() } fun deleteEntity(client: OkHttpClient, address: String, name: String, instanceName: String) { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}""") .delete() .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not delete $instanceName ${name}: ${response.code}""") } }
5
null
75
55
b25a122c0b63a7dd4e04e30613392463f1673955
6,616
java-client-api
Apache License 2.0
shared/src/commonMain/kotlin/com/movies/datasource/network/MovieService.kt
ahmedorabi94
630,220,598
false
null
package com.movies.datasource.network import com.movies.domain.model.MovieResponse import com.movies.domain.model.get_movie.MovieDetailResponse interface MovieService { suspend fun getNowPlayingMoviesAsync(page: Int): MovieResponse suspend fun getMovieDetailsAsync(movieId: Int): MovieDetailResponse suspend fun searchMoviesApi(query: String): MovieResponse }
0
Kotlin
0
0
f6f2dc4c49e9f15dcdbf0c6a024b8bec1696afbe
376
MoviesKMMCompose
Apache License 2.0
data-layer/src/main/kotlin/es/plexus/android/plexuschuck/datalayer/domain/DomainDto.kt
pablodeafsapps
397,339,000
false
null
package es.plexus.android.plexuschuck.datalayer.domain import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import es.plexus.android.plexuschuck.domainlayer.domain.ErrorMessage import okhttp3.ResponseBody /** * This data class represents the Data Transfer Object related to a user login datum */ data class UserLoginDto(val email: String, val password: String) /** * This data class models a wrapper over a [JokeDto] datum */ data class JokeDtoWrapper(val type: String, val value: List<JokeDto>) /** * This data class represents the Data Transfer Object related to a joke datum */ @JsonClass(generateAdapter = true) data class JokeDto( @Json(name = "id") val id: Int?, @Json(name = "joke") val joke: String?, @Json(name = "categories") val categories: List<String>? ) /** * A class which models any failure coming from the 'data-layer' */ sealed class FailureDto(val msg: String?) { companion object { private const val DEFAULT_ERROR_CODE = -1 } object NoConnection : FailureDto(msg = ErrorMessage.ERROR_NO_CONNECTION) class RequestError( val code: Int = DEFAULT_ERROR_CODE, msg: String?, val errorBody: ResponseBody? = null ) : FailureDto(msg = msg) object FirebaseLoginError : FailureDto(msg = ErrorMessage.ERROR_LOGIN_REQUEST) class FirebaseRegisterError(msg: String?) : FailureDto(msg = msg) object NoData : FailureDto(msg = ErrorMessage.ERROR_NO_DATA) object Unknown : FailureDto(msg = ErrorMessage.ERROR_UNKNOWN) class Error(msg: String?) : FailureDto(msg = msg) }
0
Kotlin
0
0
266de29731b0357aa5bc2525794edd9e5d88105e
1,584
clean-app
Plexus Classworlds License
api_viewing/src/main/kotlin/com/madness/collision/unit/api_viewing/ui/pref/DiffHistoryFragment.kt
cliuff
231,891,447
false
{"Kotlin": 1565135}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.madness.collision.unit.api_viewing.ui.pref import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.fragment.app.activityViewModels import com.madness.collision.Democratic import com.madness.collision.main.MainViewModel import com.madness.collision.unit.api_viewing.R import com.madness.collision.util.TaggedFragment import com.madness.collision.util.mainApplication import com.madness.collision.util.os.OsUtils class DiffHistoryFragment : TaggedFragment(), Democratic { override val category: String = "AV" override val id: String = "DiffHistory" private var mutableComposeView: ComposeView? = null private val composeView: ComposeView get() = mutableComposeView!! private val mainViewModel: MainViewModel by activityViewModels() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val composeView = ComposeView(inflater.context).apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) } mutableComposeView = composeView return composeView } override fun onDestroyView() { mutableComposeView = null super.onDestroyView() } override fun createOptions(context: Context, toolbar: Toolbar, iconColor: Int): Boolean { mainViewModel.configNavigation(toolbar, iconColor) toolbar.setTitle(R.string.av_settings_diff_title) return true } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { democratize(mainViewModel) val context = context ?: return val colorScheme = if (OsUtils.satisfy(OsUtils.S)) { if (mainApplication.isDarkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { if (mainApplication.isDarkTheme) darkColorScheme() else lightColorScheme() } composeView.setContent { MaterialTheme(colorScheme = colorScheme) { DiffHistoryPage(mainViewModel = mainViewModel) } } } }
0
Kotlin
6
83
575a37448fa490eb8939a863da61cb297a2c173c
3,205
boundo
Apache License 2.0
src/main/kotlin/com/lop/addon/Main.kt
12rcu
800,156,546
false
{"Kotlin": 1520, "TypeScript": 202}
package com.lop.addon import com.lop.devtools.monstera.addon.addon import com.lop.devtools.monstera.addon.dev.zipper.zipWorld import com.lop.devtools.monstera.files.beh.entitiy.components.Components import com.lop.devtools.monstera.loadConfig import java.awt.Color fun main(args: Array<String>) { val conf = addon(loadConfig().getOrElse { it.printStackTrace() return }) { entity("test_1_19") { behaviour { unsafeBehEntityVersion = "1.19.0" components { rideableComponents() } } resource { components { spawnEgg { eggByColor(Color.BLUE, Color.CYAN) } } } } entity("test_1_20") { behaviour { unsafeBehEntityVersion = "1.20.81" components { rideableComponents() } } resource { components { spawnEgg { eggByColor(Color.GREEN, Color.ORANGE) } } } } } if (args.contains("zip-world")) zipWorld(conf, System.getenv("CI_PROJECT_NAME") ?: "local") } fun Components.rideableComponents() { physics { } movement = 0.2 inputGroundControlled { } rideable { seat { position(0, 1, 0) } } }
0
Kotlin
0
0
07b36a3bacbb8386be98237e9be6419e0aad07ee
1,520
mc-rideable-bug
Apache License 2.0
src/main/kotlin/br/com/torresmath/key/manager/exceptions/PixKeyAlreadyExistsException.kt
torresmath
355,570,283
true
{"Kotlin": 82169}
package br.com.torresmath.key.manager.exceptions class PixKeyAlreadyExistsException( message: String, val code: Int = 422 ) : RuntimeException(message)
0
Kotlin
0
0
bc4785cd295e19485705f523f8ab2469bb3c5461
160
orange-talents-02-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/abidria/data/picture/PictureMapper.kt
TonyTangAndroid
115,438,401
true
{"Kotlin": 203035}
package com.abidria.data.picture data class PictureMapper(val smallUrl: String, val mediumUrl: String, val largeUrl: String) { fun toDomain() = Picture(smallUrl = this.smallUrl, mediumUrl = this.mediumUrl, largeUrl = this.largeUrl) }
0
Kotlin
0
0
9ad533e44910cd3534b85d23e42da671c6d48502
240
abidria-android
Apache License 2.0
src/main/kotlin/io/cutebot/telegram/tgmodel/TgDocument.kt
asundukov
274,611,303
false
null
package io.cutebot.telegram.tgmodel import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class TgDocument ( @field: JsonProperty("file_id") val fileId: String, @field: JsonProperty("file_unique_id") val fileUniqueId: String, @field: JsonProperty("file_size") val fileSize: Int, @field: JsonProperty("file_name") val fileName: String, @field: JsonProperty("mime_type") val mimeType: String )
8
Kotlin
0
0
a63cf4954c2a388714e93da2e13675cc840dd3cf
588
mark-on-image-bot
Apache License 2.0
app/src/androidTest/kotlin/aa/weather/app/test/RESTMockRule.kt
marwinxxii
608,084,351
false
null
package aa.weather.app.test import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import org.junit.rules.ExternalResource class RESTMockRule : ExternalResource() { private val mockWebServer by lazy { MockWebServer() } private val dispatcher = MockDispatcher() override fun before() { mockWebServer.dispatcher = dispatcher mockWebServer.start() } override fun after() { mockWebServer.shutdown() } val baseUrl: String get() = mockWebServer.url("/").toString() fun addResponse( path: String, queryParameters: Map<String, String>, responseFile: String, ) = apply { val response = MockResponse() .setResponseCode(200) .addHeader("Content-Type", "application/json; charset=utf-8") .addHeader("Cache-Control", "no-cache") .setBody(readResource(responseFile)) dispatcher.addResponse(ExpectedRequest(path, queryParameters), response) } fun removeAllMocks() = apply { dispatcher.removeAllMocks() } fun addResponse(path: String, httpCode: Int) = apply { val response = MockResponse() .setResponseCode(httpCode) dispatcher.addResponse(ExpectedRequest(path, queryParameters = null), response) } private fun readResource(fileName: String): String = javaClass.classLoader!! .getResourceAsStream(fileName) .reader() .readText() } private data class ExpectedRequest( val path: String, val queryParameters: Map<String, String>?, ) private class MockDispatcher : Dispatcher() { private val mocks = linkedMapOf<ExpectedRequest, MockResponse>() override fun dispatch(request: RecordedRequest): MockResponse { val requestQueryParameters = request.queryParameters return mocks.entries.firstOrNull { (expected, _) -> expected.path == request.requestUrl?.encodedPath && (expected.queryParameters?.let { it == requestQueryParameters } ?: true) } ?.value ?: error("No mock found for $request in $mocks") } fun addResponse(request: ExpectedRequest, response: MockResponse) = apply { mocks[request] = response } fun removeAllMocks() { mocks.keys.clear() } } private val RecordedRequest.queryParameters: Map<String, String> get() = requestUrl ?.queryParameterNames ?.mapNotNull { name -> requestUrl?.queryParameter(name)?.let { name to it } } ?.toMap() ?: emptyMap()
0
Kotlin
0
0
a127546016050b62944139d09e5491ebc4d6ea3a
2,708
weather-app
Apache License 2.0
app/src/main/kotlin/com/subtlefox/currencyrates/presentation/RatesActivity.kt
Subtle-fox
177,306,258
false
null
package com.subtlefox.currencyrates.presentation import android.os.Bundle import android.util.Log import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.subtlefox.currencyrates.App import com.subtlefox.currencyrates.R import com.subtlefox.currencyrates.presentation.utils.hideKeyboard import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class RatesActivity : AppCompatActivity() { @Inject lateinit var listAdapter: RatesListAdapter @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val compositeDisposable = CompositeDisposable() private lateinit var recyclerView: RecyclerView private lateinit var viewModel: RatesViewModel override fun onCreate(savedInstanceState: Bundle?) { (application as App).appComponent.plus().inject(this) super.onCreate(savedInstanceState) setContentView(R.layout.fragment_exchange_rates) recyclerView = findViewById<RecyclerView>(R.id.recycler_view) .apply { layoutManager = LinearLayoutManager(context) adapter = listAdapter itemAnimator?.moveDuration = 400 setHasFixedSize(true) addOnScrollListener(scrollListener) } viewModel = ViewModelProviders.of(this, viewModelFactory).get(RatesViewModel::class.java) .apply { lifecycle.addObserver(this) observeData() observeNetworkStatus() } } override fun onStart() { super.onStart() observeActiveCurrency() } override fun onStop() { compositeDisposable.clear() super.onStop() } override fun onDestroy() { compositeDisposable.dispose() super.onDestroy() } private fun RatesViewModel.observeData() { val loadingView = findViewById<TextView>(R.id.txt_loading) currenciesData.observe(this@RatesActivity, Observer { list -> loadingView.visibility = View.GONE if (recyclerView.isAnimating || scrollListener.isScrollingOrFlinging()) { Log.d(TAG, "scrolling or animating => drop update (will update next second)") } else { listAdapter.data = list ?: emptyList() } }) } private fun RatesViewModel.observeNetworkStatus() { val networkStatusView = findViewById<TextView>(R.id.network_status) networkStatus.observe(this@RatesActivity, Observer { if (it == true) { networkStatusView.setText(R.string.status_online) networkStatusView.setBackgroundResource(R.color.status_online) } else { networkStatusView.setText(R.string.status_offline) networkStatusView.setBackgroundResource(R.color.status_offline) } }) } private fun observeActiveCurrency() { compositeDisposable.add( listAdapter .clicks() .mergeWith(listAdapter.textChanges()) .subscribe(viewModel::setBaseCurrency) { Log.e(TAG, it.message, it) } ) } private val scrollListener = object : RecyclerView.OnScrollListener() { private var state = RecyclerView.SCROLL_STATE_IDLE fun isScrollingOrFlinging() = state != RecyclerView.SCROLL_STATE_IDLE override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { state = newState if (isScrollingOrFlinging()) { currentFocus?.hideKeyboard() } super.onScrollStateChanged(recyclerView, newState) } } companion object { const val TAG = "Rates" } }
0
Kotlin
0
0
cdcaf7d6ccef790aa903de419ffbc6206dc3c4d8
4,049
currency-exchange-rates
Apache License 2.0
app2/src/main/java/com/aos/app2/bean/Dtos.kt
ltqi
279,073,843
false
null
package com.aos.app2.bean import java.io.Serializable data class ArticleList( val offset: Int, val size: Int, val total: Int, val pageCount: Int, val curPage: Int, val over: Boolean, val datas: List<Article>): Serializable data class Article( val id: Int, val originId: Int, val title: String, val chapterId: Int, val chapterName: String, val envelopePic: String, val link: String, val author: String, val origin: String, val publishTime: Long, val zan: Int, val desc: String, val visible: Int, val niceDate: String, val niceShareDate: String, val courseId: Int, var collect: Boolean, val apkLink:String, val projectLink:String, val superChapterId:Int, val superChapterName:String?, val type:Int, val fresh:Boolean, val audit:Int, val prefix:String, val selfVisible:Int, val shareDate:Long, val shareUser:String, val tags:Any, val userId:Int):Serializable data class Banner(val desc: String, val id: Int, val imagePath: String, val isVisible: Int, val order: Int, val title: String, val type: Int, val url: String) data class Hot(val id: Int, val link: String, val name: String, val order: Int, val visible: Int, val icon: String) data class Navigation(val articles: List<Article>, val cid: Int, val name: String) data class SystemChild(val child: List<SystemChild>, val courseId: Int, val id: Int, val name: String, val order: Int, val parentChapterId: Int, val visible: Int):Serializable data class SystemParent(val children: List<SystemChild>, val courseId: Int, val id: Int, val name: String, val order: Int, val parentChapterId: Int, val visible: Int, val userControlSetTop: Boolean) : Serializable data class User(val admin: Boolean, val chapterTops: List<String>, val collectIds: List<Int>, val email: String, val icon: String, val id: Int, val nickname: String, val password: String, val publicName: String, val token: String, val type: Int, val username: String){ override fun equals(other: Any?): Boolean { return if (other is User){ this.id == other.id }else false } }
0
Kotlin
0
1
723c297f97b42868febed4eaa906af57adbfe14a
3,020
aos
MIT License
brigitte/src/main/java/brigitte/bindingadapter/ViewPager2BindingAdapter.kt
aucd29
238,183,471
false
null
package brigitte.bindingadapter import androidx.databinding.BindingAdapter import androidx.viewpager2.widget.ViewPager2 import org.slf4j.LoggerFactory /** * Created by <a href="mailto:<EMAIL>"><NAME></a> on 2020-01-23 <p/> * * https://developer.android.com/training/animation/vp2-migration */ object ViewPager2BindingAdapter { private val logger = LoggerFactory.getLogger(ViewPager2BindingAdapter::class.java) @JvmStatic @BindingAdapter("bindOffscreenPageLimit") fun bindOffscreenPageLimit(viewpager: ViewPager2, limit: Int) { if (logger.isDebugEnabled) { logger.debug("bindOffscreenPageLimit : $limit") } viewpager.offscreenPageLimit = limit } @JvmStatic @BindingAdapter("bindItems") fun <T> bindItems(viewpager: ViewPager2, items: List<T>?) { if (items == null) { // items 이 없으면 넘어가기 return } if (logger.isDebugEnabled) { logger.debug("bindItems") } viewpager.adapter?.let { } } // @JvmStatic // @BindingAdapter("bindOrientation") // fun bindOrientation(viewpager: ViewPager2, orientation: Int?) { // if (orientation == null) { // return // } // // if (logger.isDebugEnabled) { // logger.debug("bindOrientation : $orientation") // } // // viewpager.orientation = orientation // } // view 가 있네 그려 // @JvmStatic // @BindingAdapter("bindPageTransformer") // fun bindItemAnimator(viewpager: ViewPager2, transformer: ViewPager2.PageTransformer?) { // if (transformer == null) { // return // } // // if (logger.isDebugEnabled) { // logger.debug("bindPageTransformer") // } // // } @JvmStatic @BindingAdapter("bindPageChangeCallback") fun bindPageChangeCallback(viewpager: ViewPager2, callback: ((Int) -> Unit)?) { if (callback == null) { // callback 이 없으면 그냥 넘어가기 return } if (logger.isDebugEnabled) { logger.debug("bindPageChangeCallback") } viewpager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) callback.invoke(position) } }) } @JvmStatic @BindingAdapter("bindCurrentItem", "bindSmoothScroll", requireAll = false) fun bindCurrentItem(viewpager: ViewPager2, pos: Int, smoothScroll: Boolean?) { if (smoothScroll == null) { viewpager.currentItem = pos } else { viewpager.setCurrentItem(pos, smoothScroll) } } }
0
Kotlin
0
0
2cfa0a63b2eaa0cabfb84983c25c0c61b1a63b66
2,740
mbt
Apache License 2.0
Ios-Emoji/src/main/java/com/example/ios_emoji/category/FlagsCategoryChunk0.kt
anorld-droid
455,482,156
false
null
/* * Copyright (C) 2016 - <NAME>, <NAME>, <NAME> and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.example.ios_emoji.category import com.example.ios_emoji.IosEmoji internal object FlagsCategoryChunk0 { fun get(): Array<IosEmoji> { return arrayOf( IosEmoji(0x1F3C1, arrayOf("checkered_flag"), 8, 39, false), IosEmoji(0x1F6A9, arrayOf("triangular_flag_on_post"), 35, 0, false), IosEmoji(0x1F38C, arrayOf("crossed_flags"), 7, 48, false), IosEmoji(0x1F3F4, arrayOf("waving_black_flag"), 11, 17, false), IosEmoji(intArrayOf(0x1F3F3, 0xFE0F), arrayOf("waving_white_flag"), 11, 12, false), IosEmoji( intArrayOf(0x1F3F3, 0xFE0F, 0x200D, 0x1F308), arrayOf("rainbow-flag"), 11, 11, false ), IosEmoji( intArrayOf(0x1F3F4, 0x200D, 0x2620, 0xFE0F), arrayOf("pirate_flag"), 11, 13, false ), IosEmoji(intArrayOf(0x1F1E6, 0x1F1E8), arrayOf("flag-ac"), 0, 31, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1E9), arrayOf("flag-ad"), 0, 32, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1EA), arrayOf("flag-ae"), 0, 33, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1EB), arrayOf("flag-af"), 0, 34, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1EC), arrayOf("flag-ag"), 0, 35, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1EE), arrayOf("flag-ai"), 0, 36, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F1), arrayOf("flag-al"), 0, 37, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F2), arrayOf("flag-am"), 0, 38, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F4), arrayOf("flag-ao"), 0, 39, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F6), arrayOf("flag-aq"), 0, 40, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F7), arrayOf("flag-ar"), 0, 41, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F8), arrayOf("flag-as"), 0, 42, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1F9), arrayOf("flag-at"), 0, 43, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1FA), arrayOf("flag-au"), 0, 44, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1FC), arrayOf("flag-aw"), 0, 45, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1FD), arrayOf("flag-ax"), 0, 46, false), IosEmoji(intArrayOf(0x1F1E6, 0x1F1FF), arrayOf("flag-az"), 0, 47, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1E6), arrayOf("flag-ba"), 0, 48, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1E7), arrayOf("flag-bb"), 0, 49, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1E9), arrayOf("flag-bd"), 0, 50, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1EA), arrayOf("flag-be"), 0, 51, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1EB), arrayOf("flag-bf"), 0, 52, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1EC), arrayOf("flag-bg"), 0, 53, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1ED), arrayOf("flag-bh"), 0, 54, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1EE), arrayOf("flag-bi"), 0, 55, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1EF), arrayOf("flag-bj"), 0, 56, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F1), arrayOf("flag-bl"), 1, 0, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F2), arrayOf("flag-bm"), 1, 1, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F3), arrayOf("flag-bn"), 1, 2, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F4), arrayOf("flag-bo"), 1, 3, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F6), arrayOf("flag-bq"), 1, 4, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F7), arrayOf("flag-br"), 1, 5, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F8), arrayOf("flag-bs"), 1, 6, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1F9), arrayOf("flag-bt"), 1, 7, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1FB), arrayOf("flag-bv"), 1, 8, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1FC), arrayOf("flag-bw"), 1, 9, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1FE), arrayOf("flag-by"), 1, 10, false), IosEmoji(intArrayOf(0x1F1E7, 0x1F1FF), arrayOf("flag-bz"), 1, 11, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1E6), arrayOf("flag-ca"), 1, 12, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1E8), arrayOf("flag-cc"), 1, 13, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1E9), arrayOf("flag-cd"), 1, 14, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1EB), arrayOf("flag-cf"), 1, 15, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1EC), arrayOf("flag-cg"), 1, 16, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1ED), arrayOf("flag-ch"), 1, 17, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1EE), arrayOf("flag-ci"), 1, 18, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F0), arrayOf("flag-ck"), 1, 19, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F1), arrayOf("flag-cl"), 1, 20, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F2), arrayOf("flag-cm"), 1, 21, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F3), arrayOf("cn", "flag-cn"), 1, 22, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F4), arrayOf("flag-co"), 1, 23, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F5), arrayOf("flag-cp"), 1, 24, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1F7), arrayOf("flag-cr"), 1, 25, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FA), arrayOf("flag-cu"), 1, 26, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FB), arrayOf("flag-cv"), 1, 27, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FC), arrayOf("flag-cw"), 1, 28, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FD), arrayOf("flag-cx"), 1, 29, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FE), arrayOf("flag-cy"), 1, 30, false), IosEmoji(intArrayOf(0x1F1E8, 0x1F1FF), arrayOf("flag-cz"), 1, 31, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1EA), arrayOf("de", "flag-de"), 1, 32, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1EC), arrayOf("flag-dg"), 1, 33, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1EF), arrayOf("flag-dj"), 1, 34, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1F0), arrayOf("flag-dk"), 1, 35, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1F2), arrayOf("flag-dm"), 1, 36, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1F4), arrayOf("flag-do"), 1, 37, false), IosEmoji(intArrayOf(0x1F1E9, 0x1F1FF), arrayOf("flag-dz"), 1, 38, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1E6), arrayOf("flag-ea"), 1, 39, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1E8), arrayOf("flag-ec"), 1, 40, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1EA), arrayOf("flag-ee"), 1, 41, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1EC), arrayOf("flag-eg"), 1, 42, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1ED), arrayOf("flag-eh"), 1, 43, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1F7), arrayOf("flag-er"), 1, 44, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1F8), arrayOf("es", "flag-es"), 1, 45, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1F9), arrayOf("flag-et"), 1, 46, false), IosEmoji(intArrayOf(0x1F1EA, 0x1F1FA), arrayOf("flag-eu"), 1, 47, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1EE), arrayOf("flag-fi"), 1, 48, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1EF), arrayOf("flag-fj"), 1, 49, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1F0), arrayOf("flag-fk"), 1, 50, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1F2), arrayOf("flag-fm"), 1, 51, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1F4), arrayOf("flag-fo"), 1, 52, false), IosEmoji(intArrayOf(0x1F1EB, 0x1F1F7), arrayOf("fr", "flag-fr"), 1, 53, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1E6), arrayOf("flag-ga"), 1, 54, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1E7), arrayOf("gb", "uk", "flag-gb"), 1, 55, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1E9), arrayOf("flag-gd"), 1, 56, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1EA), arrayOf("flag-ge"), 2, 0, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1EB), arrayOf("flag-gf"), 2, 1, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1EC), arrayOf("flag-gg"), 2, 2, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1ED), arrayOf("flag-gh"), 2, 3, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1EE), arrayOf("flag-gi"), 2, 4, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F1), arrayOf("flag-gl"), 2, 5, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F2), arrayOf("flag-gm"), 2, 6, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F3), arrayOf("flag-gn"), 2, 7, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F5), arrayOf("flag-gp"), 2, 8, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F6), arrayOf("flag-gq"), 2, 9, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F7), arrayOf("flag-gr"), 2, 10, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F8), arrayOf("flag-gs"), 2, 11, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1F9), arrayOf("flag-gt"), 2, 12, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1FA), arrayOf("flag-gu"), 2, 13, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1FC), arrayOf("flag-gw"), 2, 14, false), IosEmoji(intArrayOf(0x1F1EC, 0x1F1FE), arrayOf("flag-gy"), 2, 15, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1F0), arrayOf("flag-hk"), 2, 16, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1F2), arrayOf("flag-hm"), 2, 17, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1F3), arrayOf("flag-hn"), 2, 18, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1F7), arrayOf("flag-hr"), 2, 19, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1F9), arrayOf("flag-ht"), 2, 20, false), IosEmoji(intArrayOf(0x1F1ED, 0x1F1FA), arrayOf("flag-hu"), 2, 21, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1E8), arrayOf("flag-ic"), 2, 22, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1E9), arrayOf("flag-id"), 2, 23, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1EA), arrayOf("flag-ie"), 2, 24, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F1), arrayOf("flag-il"), 2, 25, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F2), arrayOf("flag-im"), 2, 26, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F3), arrayOf("flag-in"), 2, 27, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F4), arrayOf("flag-io"), 2, 28, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F6), arrayOf("flag-iq"), 2, 29, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F7), arrayOf("flag-ir"), 2, 30, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F8), arrayOf("flag-is"), 2, 31, false), IosEmoji(intArrayOf(0x1F1EE, 0x1F1F9), arrayOf("it", "flag-it"), 2, 32, false), IosEmoji(intArrayOf(0x1F1EF, 0x1F1EA), arrayOf("flag-je"), 2, 33, false), IosEmoji(intArrayOf(0x1F1EF, 0x1F1F2), arrayOf("flag-jm"), 2, 34, false), IosEmoji(intArrayOf(0x1F1EF, 0x1F1F4), arrayOf("flag-jo"), 2, 35, false), IosEmoji(intArrayOf(0x1F1EF, 0x1F1F5), arrayOf("jp", "flag-jp"), 2, 36, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1EA), arrayOf("flag-ke"), 2, 37, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1EC), arrayOf("flag-kg"), 2, 38, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1ED), arrayOf("flag-kh"), 2, 39, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1EE), arrayOf("flag-ki"), 2, 40, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1F2), arrayOf("flag-km"), 2, 41, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1F3), arrayOf("flag-kn"), 2, 42, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1F5), arrayOf("flag-kp"), 2, 43, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1F7), arrayOf("kr", "flag-kr"), 2, 44, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1FC), arrayOf("flag-kw"), 2, 45, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1FE), arrayOf("flag-ky"), 2, 46, false), IosEmoji(intArrayOf(0x1F1F0, 0x1F1FF), arrayOf("flag-kz"), 2, 47, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1E6), arrayOf("flag-la"), 2, 48, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1E7), arrayOf("flag-lb"), 2, 49, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1E8), arrayOf("flag-lc"), 2, 50, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1EE), arrayOf("flag-li"), 2, 51, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1F0), arrayOf("flag-lk"), 2, 52, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1F7), arrayOf("flag-lr"), 2, 53, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1F8), arrayOf("flag-ls"), 2, 54, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1F9), arrayOf("flag-lt"), 2, 55, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1FA), arrayOf("flag-lu"), 2, 56, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1FB), arrayOf("flag-lv"), 3, 0, false), IosEmoji(intArrayOf(0x1F1F1, 0x1F1FE), arrayOf("flag-ly"), 3, 1, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1E6), arrayOf("flag-ma"), 3, 2, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1E8), arrayOf("flag-mc"), 3, 3, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1E9), arrayOf("flag-md"), 3, 4, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1EA), arrayOf("flag-me"), 3, 5, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1EB), arrayOf("flag-mf"), 3, 6, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1EC), arrayOf("flag-mg"), 3, 7, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1ED), arrayOf("flag-mh"), 3, 8, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F0), arrayOf("flag-mk"), 3, 9, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F1), arrayOf("flag-ml"), 3, 10, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F2), arrayOf("flag-mm"), 3, 11, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F3), arrayOf("flag-mn"), 3, 12, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F4), arrayOf("flag-mo"), 3, 13, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F5), arrayOf("flag-mp"), 3, 14, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F6), arrayOf("flag-mq"), 3, 15, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F7), arrayOf("flag-mr"), 3, 16, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F8), arrayOf("flag-ms"), 3, 17, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1F9), arrayOf("flag-mt"), 3, 18, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FA), arrayOf("flag-mu"), 3, 19, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FB), arrayOf("flag-mv"), 3, 20, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FC), arrayOf("flag-mw"), 3, 21, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FD), arrayOf("flag-mx"), 3, 22, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FE), arrayOf("flag-my"), 3, 23, false), IosEmoji(intArrayOf(0x1F1F2, 0x1F1FF), arrayOf("flag-mz"), 3, 24, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1E6), arrayOf("flag-na"), 3, 25, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1E8), arrayOf("flag-nc"), 3, 26, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1EA), arrayOf("flag-ne"), 3, 27, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1EB), arrayOf("flag-nf"), 3, 28, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1EC), arrayOf("flag-ng"), 3, 29, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1EE), arrayOf("flag-ni"), 3, 30, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1F1), arrayOf("flag-nl"), 3, 31, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1F4), arrayOf("flag-no"), 3, 32, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1F5), arrayOf("flag-np"), 3, 33, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1F7), arrayOf("flag-nr"), 3, 34, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1FA), arrayOf("flag-nu"), 3, 35, false), IosEmoji(intArrayOf(0x1F1F3, 0x1F1FF), arrayOf("flag-nz"), 3, 36, false), IosEmoji(intArrayOf(0x1F1F4, 0x1F1F2), arrayOf("flag-om"), 3, 37, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1E6), arrayOf("flag-pa"), 3, 38, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1EA), arrayOf("flag-pe"), 3, 39, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1EB), arrayOf("flag-pf"), 3, 40, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1EC), arrayOf("flag-pg"), 3, 41, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1ED), arrayOf("flag-ph"), 3, 42, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F0), arrayOf("flag-pk"), 3, 43, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F1), arrayOf("flag-pl"), 3, 44, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F2), arrayOf("flag-pm"), 3, 45, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F3), arrayOf("flag-pn"), 3, 46, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F7), arrayOf("flag-pr"), 3, 47, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F8), arrayOf("flag-ps"), 3, 48, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1F9), arrayOf("flag-pt"), 3, 49, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1FC), arrayOf("flag-pw"), 3, 50, false), IosEmoji(intArrayOf(0x1F1F5, 0x1F1FE), arrayOf("flag-py"), 3, 51, false), IosEmoji(intArrayOf(0x1F1F6, 0x1F1E6), arrayOf("flag-qa"), 3, 52, false), IosEmoji(intArrayOf(0x1F1F7, 0x1F1EA), arrayOf("flag-re"), 3, 53, false), IosEmoji(intArrayOf(0x1F1F7, 0x1F1F4), arrayOf("flag-ro"), 3, 54, false), IosEmoji(intArrayOf(0x1F1F7, 0x1F1F8), arrayOf("flag-rs"), 3, 55, false), IosEmoji(intArrayOf(0x1F1F7, 0x1F1FA), arrayOf("ru", "flag-ru"), 3, 56, false), IosEmoji(intArrayOf(0x1F1F7, 0x1F1FC), arrayOf("flag-rw"), 4, 0, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1E6), arrayOf("flag-sa"), 4, 1, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1E7), arrayOf("flag-sb"), 4, 2, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1E8), arrayOf("flag-sc"), 4, 3, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1E9), arrayOf("flag-sd"), 4, 4, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1EA), arrayOf("flag-se"), 4, 5, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1EC), arrayOf("flag-sg"), 4, 6, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1ED), arrayOf("flag-sh"), 4, 7, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1EE), arrayOf("flag-si"), 4, 8, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1EF), arrayOf("flag-sj"), 4, 9, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F0), arrayOf("flag-sk"), 4, 10, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F1), arrayOf("flag-sl"), 4, 11, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F2), arrayOf("flag-sm"), 4, 12, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F3), arrayOf("flag-sn"), 4, 13, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F4), arrayOf("flag-so"), 4, 14, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F7), arrayOf("flag-sr"), 4, 15, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F8), arrayOf("flag-ss"), 4, 16, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1F9), arrayOf("flag-st"), 4, 17, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1FB), arrayOf("flag-sv"), 4, 18, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1FD), arrayOf("flag-sx"), 4, 19, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1FE), arrayOf("flag-sy"), 4, 20, false), IosEmoji(intArrayOf(0x1F1F8, 0x1F1FF), arrayOf("flag-sz"), 4, 21, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1E6), arrayOf("flag-ta"), 4, 22, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1E8), arrayOf("flag-tc"), 4, 23, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1E9), arrayOf("flag-td"), 4, 24, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1EB), arrayOf("flag-tf"), 4, 25, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1EC), arrayOf("flag-tg"), 4, 26, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1ED), arrayOf("flag-th"), 4, 27, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1EF), arrayOf("flag-tj"), 4, 28, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F0), arrayOf("flag-tk"), 4, 29, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F1), arrayOf("flag-tl"), 4, 30, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F2), arrayOf("flag-tm"), 4, 31, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F3), arrayOf("flag-tn"), 4, 32, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F4), arrayOf("flag-to"), 4, 33, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F7), arrayOf("flag-tr"), 4, 34, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1F9), arrayOf("flag-tt"), 4, 35, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1FB), arrayOf("flag-tv"), 4, 36, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1FC), arrayOf("flag-tw"), 4, 37, false), IosEmoji(intArrayOf(0x1F1F9, 0x1F1FF), arrayOf("flag-tz"), 4, 38, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1E6), arrayOf("flag-ua"), 4, 39, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1EC), arrayOf("flag-ug"), 4, 40, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1F2), arrayOf("flag-um"), 4, 41, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1F3), arrayOf("flag-un"), 4, 42, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1F8), arrayOf("us", "flag-us"), 4, 43, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1FE), arrayOf("flag-uy"), 4, 44, false), IosEmoji(intArrayOf(0x1F1FA, 0x1F1FF), arrayOf("flag-uz"), 4, 45, false) ) } }
0
Kotlin
0
1
2a42822d3e000651f0f30768055e878882fc0cd7
22,544
compose-emojis
Apache License 2.0
server/src/main/kotlin/com/jaychang/food/api/UsersApi.kt
jaychang0917
462,185,290
false
{"Kotlin": 429866, "Dart": 68481, "Ruby": 1354, "Shell": 608, "Swift": 404, "Objective-C": 38}
/** * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1). * https://openapi-generator.tech * Do not edit the class manually. */ package com.jaychang.food.api import com.jaychang.food.api.ApiError import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.validation.annotation.Validated import org.springframework.web.context.request.NativeWebRequest import org.springframework.beans.factory.annotation.Autowired import javax.validation.Valid import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import kotlin.collections.List import kotlin.collections.Map @Validated @RequestMapping("\${api.base-path:/api}") interface UsersApi { @GetMapping( value = ["/users/{userId}"], produces = ["application/json"] ) fun getUsersUserId( @PathVariable("userId") userId: kotlin.String ): ResponseEntity<Any> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } }
0
Kotlin
0
0
4bfd868ffd8523eea78257cc8b6e01bb480c754f
1,355
food
Apache License 2.0
app/src/main/java/io/mangel/issuemanager/repositories/SyncRepository.kt
baupen
198,594,527
false
{"Kotlin": 125520}
package io.mangel.issuemanager.repositories import io.mangel.issuemanager.api.FileDownloadRequest import io.mangel.issuemanager.api.ObjectMeta import io.mangel.issuemanager.api.ReadRequest import io.mangel.issuemanager.api.tasks.* import io.mangel.issuemanager.events.* import io.mangel.issuemanager.factories.ClientFactory import io.mangel.issuemanager.services.AuthenticationService import io.mangel.issuemanager.services.FileService import io.mangel.issuemanager.services.SettingService import io.mangel.issuemanager.services.data.ConstructionSiteDataService import io.mangel.issuemanager.services.data.CraftsmanDataService import io.mangel.issuemanager.services.data.IssueDataService import io.mangel.issuemanager.services.data.MapDataService import io.mangel.issuemanager.services.data.store.StoreConverter import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class SyncRepository( private val storeConverter: StoreConverter, private val constructionSiteDataService: ConstructionSiteDataService, private val mapDataService: MapDataService, private val issueDataService: IssueDataService, private val craftsmanDataService: CraftsmanDataService, private val fileService: FileService, private val settingService: SettingService, private val clientFactory: ClientFactory, private val authenticationService: AuthenticationService ) { init { EventBus.getDefault().register(this) } private var refreshTasksActive = 0 fun sync() { // throw event always if some view is too late EventBus.getDefault().post(SyncStartedEvent()) synchronized(this) { if (refreshTasksActive > 0) { return } refreshTasksActive = 1 } val authToken = authenticationService.getAuthenticationToken() val user = settingService.readUser() ?: return val userMeta = ObjectMeta(user.id, user.lastChangeTime) val craftsmanMetas = craftsmanDataService.getAllAsObjectMeta() val constructionSiteMetas = constructionSiteDataService.getAllAsObjectMeta() val mapMetas = mapDataService.getAllAsObjectMeta() val issueMetas = issueDataService.getAllAsObjectMeta() val readRequest = ReadRequest( authToken.authenticationToken, userMeta, craftsmanMetas, constructionSiteMetas, mapMetas, issueMetas ) val client = clientFactory.getClient(authToken.host) val readTask = ReadTask(client) readTask.execute(readRequest) } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun on(event: ReadTaskFinished) { if (event.changedUser != null) { refreshUser(event.changedUser) } processChangedAndDeletedElements(event) EventBus.getDefault().post(SavedConstructionSitesEvent()) downloadFiles() someRefreshTaskHasFinished(true) } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun on(event: ReadTaskFailed) { someRefreshTaskHasFinished(false) } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun on(event: TaskFinishedEvent) { if (event.taskType == FileDownloadTask::class.java) { someRefreshTaskHasFinished() } } private fun someRefreshTaskHasFinished(successful: Boolean? = null) { refreshTasksActive-- if (refreshTasksActive == 0) { EventBus.getDefault().post(SyncFinishedEvent(successful)) } } private fun downloadFiles() { val fileDownloadTasks = ArrayList<FileDownloadTaskEntry>() val allFiles = ArrayList<String>() val constructionSiteImages = constructionSiteDataService.getConstructionSiteImages() for (image in constructionSiteImages) { addDownloadTaskIfImageMissing( image.imagePath, image.meta, { authToken, meta -> FileDownloadRequest(authToken, constructionSite = meta) }, fileDownloadTasks, allFiles ) } val mapFiles = mapDataService.getMapImages() for (mapFile in mapFiles) { addDownloadTaskIfImageMissing( mapFile.filePath, mapFile.meta, { authToken, meta -> FileDownloadRequest(authToken, map = meta) }, fileDownloadTasks, allFiles ) } val issueImages = issueDataService.getIssueImages() for (issueImage in issueImages) { addDownloadTaskIfImageMissing( issueImage.imagePath, issueImage.meta, { authToken, meta -> FileDownloadRequest(authToken, issue = meta) }, fileDownloadTasks, allFiles ) } fileService.deleteOthers(allFiles.toSet()) if (fileDownloadTasks.isEmpty()) { return } val host = authenticationService.getAuthenticationToken().host val client = clientFactory.getClient(host) if (fileDownloadTasks.size > 10) { // make two background tasks to parallelize val batch1 = fileDownloadTasks.filterIndexed { index, _ -> index % 2 == 0 } val batch2 = fileDownloadTasks.filterIndexed { index, _ -> index % 2 == 1 } refreshTasksActive += 2 FileDownloadTask(client).execute(*batch1.toTypedArray()) FileDownloadTask(client).execute(*batch2.toTypedArray()) } else { refreshTasksActive += 1 FileDownloadTask(client).execute(*fileDownloadTasks.toTypedArray()) } } private fun addDownloadTaskIfImageMissing( filePath: String, meta: ObjectMeta, createFileDownloadRequest: (authToken: String, meta: ObjectMeta) -> FileDownloadRequest, fileDownloadTasks: ArrayList<FileDownloadTaskEntry>, allFiles: ArrayList<String> ) { allFiles.add(filePath) if (!fileService.exists(filePath)) { val authToken = authenticationService.getAuthenticationToken().authenticationToken val fileDownloadRequest = createFileDownloadRequest(authToken, meta) val fileDownloadTaskEntry = FileDownloadTaskEntry(fileDownloadRequest, filePath) fileDownloadTasks.add(fileDownloadTaskEntry) } } private fun processChangedAndDeletedElements(event: ReadTaskFinished) { // process construction sites val storeConstructionSites = event.changedConstructionSites.map { cs -> storeConverter.convert(cs) } constructionSiteDataService.store(storeConstructionSites) constructionSiteDataService.delete(event.removedConstructionSiteIDs) if (storeConstructionSites.isNotEmpty() || event.removedConstructionSiteIDs.isNotEmpty()) { EventBus.getDefault().post(SavedConstructionSitesEvent()) } // process craftsman val storeCraftsmen = event.changedCraftsmen.map { cs -> storeConverter.convert(cs) } craftsmanDataService.store(storeCraftsmen) craftsmanDataService.delete(event.removedCraftsmanIDs) if (storeCraftsmen.isNotEmpty() || event.removedCraftsmanIDs.isNotEmpty()) { EventBus.getDefault().post(SavedCraftsmenEvent()) } // process maps val storeMaps = event.changedMaps.map { cs -> storeConverter.convert(cs) } mapDataService.store(storeMaps) mapDataService.delete(event.removedMapIDs) if (storeMaps.isNotEmpty() || event.removedMapIDs.isNotEmpty()) { EventBus.getDefault().post(SavedMapsEvent()) } // process issues val storeIssues = event.changedIssues.map { cs -> storeConverter.convert(cs) } issueDataService.store(storeIssues) issueDataService.delete(event.removedIssueIDs) if (storeIssues.isNotEmpty() || event.removedIssueIDs.isNotEmpty()) { EventBus.getDefault().post(SavedIssuesEvent()) } } private fun refreshUser(apiUser: io.mangel.issuemanager.api.User) { val storeUser = storeConverter.convert(apiUser) settingService.saveUser(storeUser) EventBus.getDefault().post(SavedUserEvent(storeUser)) } } class SyncStartedEvent class SyncFinishedEvent(val result: Boolean?)
0
Kotlin
0
1
cb04e3b82925c230fc112f4a1f6397bdb2863b91
8,515
Android
MIT License
app/src/main/java/com/anamarin/bitcoinpricesapp/core/di/modules/ActivityModule.kt
anamarin09041995
228,681,425
false
null
package com.anamarin.bitcoinpricesapp.core.di.modules import com.anamarin.bitcoinpricesapp.presentation.ui.MainActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class ActivityModule { @ContributesAndroidInjector abstract fun binMainActivity(): MainActivity }
0
Kotlin
0
0
886261390e5bf1dedf24032bb9b2078512768664
316
BitcoinPricesApp
MIT License
app/src/main/java/com/a/vocabulary15/presentation/test/composables/TestCharItem.kt
thedeveloperworldisyours
405,696,476
false
{"Kotlin": 188765}
package com.a.vocabulary15.presentation.test.composables import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Card import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.a.vocabulary15.presentation.ui.theme.Typography @Composable fun TestCharItem(text: String, backgroundColor: Color) { Surface { Card( backgroundColor = backgroundColor, elevation = 5.dp, modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp, vertical = 8.dp) ) { Box { Text( text = text, fontWeight = FontWeight.Bold, color = Color.White, modifier = Modifier .width(16.dp) .align(Alignment.CenterStart) .padding(4.dp, 4.dp, 0.dp, 4.dp), style = Typography.body1 ) } } } }
0
Kotlin
6
33
ef97e70a9eb9a71d4d8e44269711f47de220d072
1,479
ComposeClean
MIT License
src/main/kotlin/com/korrit/kotlin/ktor/controllers/patch/PatchOf.kt
Koriit
217,274,651
false
null
package korrit.kotlin.ktor.controllers.patch import io.ktor.util.KtorExperimentalAPI import java.util.concurrent.ConcurrentHashMap import korrit.kotlin.ktor.controllers.exceptions.InputException import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KParameter import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.instanceParameter import kotlin.reflect.full.memberFunctions import kotlin.reflect.full.primaryConstructor /** * Base class that allows defining patch request bodies with delegates. * * **patch** and **patched** functions follow *PATCH* semantics. * * **update** and **updated** functions follow *PUT* semantics. * * This is semi-compatible with RFC7396 as there are constraints imposed by type system * which are not considered by this rfc because it is defined on generic JSON. * RFC7396 is also kind of broken by required constraint that can be forced on patch property. * * There are no public fields as they would limit possible patch property names. * * @param T Target patched class */ @KtorExperimentalAPI open class PatchOf<T : Any?> { companion object { /** Cache of copy function and mapping of patch delegates to copy params. */ private val copyCache = ConcurrentHashMap<KClass<*>, Pair<KFunction<*>, Map<KProperty1<*, *>, KParameter>>>() /** Cache of primary constructor and mapping of patch delegates to constructor params. */ private val constructorCache = ConcurrentHashMap<KClass<*>, Pair<KFunction<*>, Map<KProperty1<*, *>, KParameter>>>() } /** * Internal reference to class object of patched class. * * We must use star projection because T must be nullable and KClass<*> does not accept T? */ private lateinit var patchedClass: KClass<*> /** * Whether in-place modifications are possible for this patch object. */ private var canModifyInPlace = true /** * List of delegates defined in this patch object. */ private val delegates = mutableListOf<AbstractPatchDelegate<T, Any?>>() /** * Helper function to create required patch delegates. * * Patch value overrides entirely the patched property. * * @param prop Definition of patched property, i.e. PatchedClass::patchedProperty * @param required Must be true. Additional param allows us to have an overload that declares different return type * @param D Target patched class. Hacky [T] redeclaration to get it reified * @param P Type of patched property */ inline fun <reified D : T, P : Any?> patchOf(prop: KProperty1<D, P>, required: Boolean): RequiredPatchDelegateProvider<P> { assert(required) { "Parameter 'required' of 'patchOf' delegate builder must be true or omitted" } return RequiredPatchDelegateProvider(prop, D::class) } /** * Helper function to create patch delegates. * * Patch value overrides entirely the patched property. * * @param prop Definition of patched property, i.e. PatchedClass::patchedProperty * @param D Target patched class. Hacky [T] redeclaration to get it reified * @param P Type of patched property */ inline fun <reified D : T, P : Any?> patchOf(prop: KProperty1<D, P>): PatchDelegateProvider<P> { return PatchDelegateProvider(prop, D::class) } /** * Helper function to create required nested patch delegates. * * Patch value updates patched property with the same logic as is applied to the patched object. * * @param prop Definition of patched property, i.e. PatchedClass::nestedObject (which is of type NestedClass) * @param by The patch class to be used for this property, i.e. NestedClassPatch::class (which is PatchOf<NestedClass>) * @param required Must be true. Additional param allows us to have an overload that declares different return type * @param D Target patched class. Hacky [T] redeclaration to get it reified * @param P Type of patched property * @param U Type of Patch Class that is going to patch property */ @Suppress("UNUSED_PARAMETER") // param `by` allows the compiler to infer generic type U inline fun <reified D : T, P : Any?, U : PatchOf<P>> patchOf(prop: KProperty1<D, P>, by: KClass<U>, required: Boolean): RequiredNestedPatchDelegateProvider<P, U> { assert(required) { "Parameter 'required' of 'patchOf' delegate builder must be true or omitted" } return RequiredNestedPatchDelegateProvider(prop, D::class) } /** * Helper function to create nested patch delegates. * * Patch value updates patched property with the same logic as is applied to the patched object. * * @param prop Definition of patched property, i.e. PatchedClass::nestedObject (which is of type NestedClass) * @param by The patch class to be used for this property, i.e. NestedClassPatch::class (which is PatchOf<NestedClass>) * @param D Target patched class. Hacky [T] redeclaration to get it reified * @param P Type of patched property * @param U Type of Patch Class that is going to patch property */ @Suppress("UNUSED_PARAMETER") // param `by` allows the compiler to infer generic type U inline fun <reified D : T, P : Any?, U : PatchOf<P>> patchOf(prop: KProperty1<D, P>, by: KClass<U>): NestedPatchDelegateProvider<P, U> { return NestedPatchDelegateProvider(prop, D::class) } /** * Creates new instance of patched class. * * There are following constraints: * 1. Patched class must have a primary constructor * 2. There are no delegates targeting properties outside of primary constructor * 3. All non-optional parameters of primary constructor are mapped to delegates * 4. Values are present for all required, non-optional and non-nullable properties * * @see getConstructor */ open fun instance(): T { if (!::patchedClass.isInitialized) throw UnsupportedOperationException("${javaClass.simpleName} does not define any patch delegate") val (ctor, ctorParams) = getConstructor() val params: MutableMap<KParameter, Any?> = mutableMapOf() for (patch in delegates) { val param = ctorParams.getValue(patch.patchedProp) if (!patch.isSet) { if (patch.isRequired) throw InputException("Missing field: ${patch.name}") // missing but optional so we can skip it if (param.isOptional) continue // missing nullable, non-optional fields are implicitly considered null if (!patch.isNullable) throw InputException("Missing field: ${patch.name}") } params[param] = when (patch) { is PatchDelegate<T, Any?> -> patch.value is NestedPatchDelegate<T, *, *> -> patch.patch!!.instance() } } @Suppress("UNCHECKED_CAST") // safe return ctor.callBy(params) as T } /** * Modifies object in-place with *PATCH* semantics. * * Requires all delegates to target mutable properties(defined with **var**). * This also applies to all nested patches. * * It uses [instance] function internally, so, the same constraints apply if * some nested object is null on the patched object. * * Exception is thrown if some patch value is required but is missing. * * @param obj Object to patch */ open fun patch(obj: T) { if (!::patchedClass.isInitialized) throw UnsupportedOperationException("${javaClass.simpleName} does not define any patch delegate") if (obj == null) throw IllegalArgumentException("Patched object cannot be null") if (!canModifyInPlace) throw UnsupportedOperationException("This operation is only supported for patches of mutable properties") for (patch in delegates) { if (!patch.isSet) { if (patch.isRequired) throw InputException("Missing field: ${patch.name}") continue } val value = when (patch) { is PatchDelegate<T, Any?> -> { patch.value } is NestedPatchDelegate<T, *, *> -> { @Suppress("UNCHECKED_CAST") // safe cast patch as NestedPatchDelegate<T, Any?, PatchOf<Any?>> val nestedPatch = patch.patch!! val nestedValue = patch.patchedProp.get(obj) if (nestedValue != null) { nestedPatch.patch(nestedValue) nestedValue } else { nestedPatch.instance() } } } patch.mutableProp.set(obj, value) } } /** * Returns new copy of object, modified with *PATCH* semantics. * Original object is not modified. * * This does not require all patched properties to be mutable(**var**) like [patch]. * * It uses [instance] function internally, so, the same constraints apply if * some nested object is null on the patched object. * * Additionally it only supports data classes. * @see getCopy * * Exception is thrown if some patch value is required but is missing. * * @param obj Object to be patched */ open fun patched(obj: T): T { if (!::patchedClass.isInitialized) throw UnsupportedOperationException("${javaClass.simpleName} does not define any patch delegate") if (obj == null) throw IllegalArgumentException("Patched object cannot be null") val (copy, copyParams) = getCopy() val params: MutableMap<KParameter, Any?> = mutableMapOf( copy.instanceParameter!! to obj ) for (patch in delegates) { if (!patch.isSet) { if (patch.isRequired) throw InputException("Missing field: ${patch.name}") continue } val param = copyParams.getValue(patch.patchedProp) val value = when (patch) { is PatchDelegate<T, Any?> -> { patch.value } is NestedPatchDelegate<T, *, *> -> { @Suppress("UNCHECKED_CAST") // safe cast patch as NestedPatchDelegate<T, Any?, PatchOf<Any?>> val nestedPatch = patch.patch!! val nestedValue = patch.patchedProp.get(obj) if (nestedValue != null) { nestedPatch.patched(nestedValue) } else { nestedPatch.instance() } } } params[param] = value } @Suppress("UNCHECKED_CAST") // safe return copy.callBy(params) as T } /** * Modifies object in-place with *PUT* semantics. * * Requires all delegates to target mutable properties(defined with **var**). * This also applies to all nested patches. * * It uses [instance] function internally, so, the same constraints apply if * some nested object is null on the patched object. * * Exception is thrown if some patch value is non-nullable or required but is missing. * * @param obj Object to update */ open fun update(obj: T) { if (!::patchedClass.isInitialized) throw UnsupportedOperationException("${javaClass.simpleName} does not define any patch delegate") if (obj == null) throw IllegalArgumentException("Updated object cannot be null") if (!canModifyInPlace) throw UnsupportedOperationException("This operation is only supported for updates of mutable properties") for (update in delegates) { if (!update.isSet) { if (!update.isNullable || update.isRequired) throw InputException("Missing field: ${update.name}") // missing nullable fields are implicitly considered null update.mutableProp.set(obj, null) continue } val value = when (update) { is PatchDelegate<T, Any?> -> { update.value } is NestedPatchDelegate<T, *, *> -> { @Suppress("UNCHECKED_CAST") // safe cast update as NestedPatchDelegate<T, Any?, PatchOf<Any?>> val nestedUpdate = update.patch!! val nestedValue = update.patchedProp.get(obj) if (nestedValue != null) { nestedUpdate.update(nestedValue) nestedValue } else { nestedUpdate.instance() } } } update.mutableProp.set(obj, value) } } /** * Returns new copy of object, modified with *PUT* semantics. * Original object is not modified. * * This does not require all patched properties to be mutable(**var**) like [update]. * * It uses [instance] function internally, so, the same constraints might apply if * some nested object is null on the patched object. * * Additionally it only supports data classes. * @see getCopy * * Exception is thrown if some patch value is non-nullable or required but is missing. * * @param obj Object to be patched */ open fun updated(obj: T): T { if (!::patchedClass.isInitialized) throw UnsupportedOperationException("${javaClass.simpleName} does not define any patch delegate") if (obj == null) throw IllegalArgumentException("Updated object cannot be null") val (copy, copyParams) = getCopy() val params: MutableMap<KParameter, Any?> = mutableMapOf( copy.instanceParameter!! to obj ) for (update in delegates) { val param = copyParams.getValue(update.patchedProp) if (!update.isSet) { if (!update.isNullable || update.isRequired) throw InputException("Missing field: ${update.name}") // missing nullable fields are implicitly considered null params[param] = null continue } val value = when (update) { is PatchDelegate<T, Any?> -> { update.value } is NestedPatchDelegate<T, *, *> -> { @Suppress("UNCHECKED_CAST") // safe cast update as NestedPatchDelegate<T, Any?, PatchOf<Any?>> val nestedUpdate = update.patch!! val nestedValue = update.patchedProp.get(obj) if (nestedValue != null) { nestedUpdate.updated(nestedValue) } else { nestedUpdate.instance() } } } params[param] = value } @Suppress("UNCHECKED_CAST") // safe return copy.callBy(params) as T } /** * Retrieves "copy constructor" of patched class and maps its parameters to defined delegates. * * Currently, only supports data classes as they have well defined standard copy function. * * Disallows delegates that target properties outside of primary constructor. */ private fun getCopy() = copyCache.getOrPut(patchedClass) { if (!patchedClass.isData) throw UnsupportedOperationException("${patchedClass.simpleName} is not a data class") val copy = patchedClass.memberFunctions.first { it.name == "copy" } val params: Map<KProperty1<*, *>, KParameter> = delegates.map { delegate -> val param = copy.parameters.find { it.name == delegate.patchedProp.name } ?: throw UnsupportedOperationException("One of the patches targets property which is not defined in primary constructor") delegate.patchedProp to param }.toMap() copy to params } /** * Retrieves primary constructor of patched class and maps its parameters to defined delegates. * * All constructor parameters without default arguments must be matched, otherwise an exception is thrown. * * Disallows delegates that target properties outside of primary constructor. */ private fun getConstructor() = constructorCache.getOrPut(patchedClass) { val ctor = patchedClass.primaryConstructor ?: throw UnsupportedOperationException("${patchedClass.simpleName} does not have primary constructor") val delegateProps = delegates.map { it.patchedProp.name } val ctorParams = ctor.parameters.mapNotNull { it.name } val unmapped = delegateProps - ctorParams if (unmapped.isNotEmpty()) throw UnsupportedOperationException("Patch class ${javaClass.simpleName} targets targets properties which are not defined in primary constructor: $unmapped") val params: Map<KProperty1<*, *>, KParameter> = ctor.parameters.mapNotNull { param -> val delegate = delegates.find { it.patchedProp.name == param.name } if (delegate == null) { // missing but optional so we can skip it if (param.isOptional) return@mapNotNull null else throw UnsupportedOperationException("Patch class ${javaClass.simpleName} is missing a delegate for ${param.name} constructor parameter") } delegate.patchedProp to param }.toMap() ctor to params } /** * Provides patch delegates. * * @param P Type of patched property * @property patchedProp Definition of patched property * @property patchedClazz Definition of patched class */ inner class PatchDelegateProvider<P : Any?>( private val patchedProp: KProperty1<*, P>, private val patchedClazz: KClass<*> ) { /** Provides a delegate for given instance. */ operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): PatchDelegate<T, P> { if (::patchedClass.isInitialized && patchedClass != patchedClazz) throw IllegalArgumentException("All delegate targets must belong to ${patchedClass.simpleName} and '${property.name}' does not") patchedClass = patchedClazz if (patchedProp !is KMutableProperty1<*, *>) canModifyInPlace = false if (property !is KMutableProperty1<*, *>) throw UnsupportedOperationException("Delegated property must be mutable: ${property.name}") @Suppress("UNCHECKED_CAST") // Safe if not called from outside of this class val patch = PatchDelegate(property.name, patchedProp as KProperty1<T, P>) @Suppress("UNCHECKED_CAST") // Safe delegates.add(patch as AbstractPatchDelegate<T, Any?>) return patch } } /** * Provides required patch delegates. * * @param P Type of patched property * @property patchedProp Definition of patched property * @property patchedClazz Definition of patched class */ inner class RequiredPatchDelegateProvider<P : Any?>( private val patchedProp: KProperty1<*, P>, private val patchedClazz: KClass<*> ) { /** Provides a delegate for given instance. */ operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): RequiredPatchDelegate<T, P> { if (::patchedClass.isInitialized && patchedClass != patchedClazz) throw IllegalArgumentException("All delegate targets must belong to ${patchedClass.simpleName} and '${property.name}' does not") patchedClass = patchedClazz if (patchedProp !is KMutableProperty1<*, *>) canModifyInPlace = false if (property !is KMutableProperty1<*, *>) throw UnsupportedOperationException("Delegated property must be mutable: ${property.name}") @Suppress("UNCHECKED_CAST") // Safe if not called from outside of this class val patch = RequiredPatchDelegate(property.name, patchedProp as KProperty1<T, P>) @Suppress("UNCHECKED_CAST") // Safe delegates.add(patch as AbstractPatchDelegate<T, Any?>) return patch } } /** * Provides nested patch delegates. * * @param P Type of patched property * @param U Type of Patch Class that is going to patch property * @property patchedProp Definition of patched property * @property patchedClazz Definition of patched class */ inner class NestedPatchDelegateProvider<P : Any?, U : PatchOf<P>>( private val patchedProp: KProperty1<*, P>, private val patchedClazz: KClass<*> ) { /** Provides a delegate for given instance. */ operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): NestedPatchDelegate<T, P, U> { if (::patchedClass.isInitialized && patchedClass != patchedClazz) throw IllegalArgumentException("All delegate targets must belong to ${patchedClass.simpleName} and '${property.name}' does not") patchedClass = patchedClazz if (patchedProp !is KMutableProperty1<*, *>) canModifyInPlace = false if (property !is KMutableProperty1<*, *>) throw UnsupportedOperationException("Delegated property must be mutable: ${property.name}") @Suppress("UNCHECKED_CAST") // Safe if not called from outside of this class val patch = NestedPatchDelegate<T, P, U>(property.name, patchedProp as KProperty1<T, P>) @Suppress("UNCHECKED_CAST") // Safe delegates.add(patch as AbstractPatchDelegate<T, Any?>) return patch } } /** * Provides required nested patch delegates. * * @param P Type of patched property * @param U Type of Patch Class that is going to patch property * @property patchedProp Definition of patched property * @property patchedClazz Definition of patched class */ inner class RequiredNestedPatchDelegateProvider<P : Any?, U : PatchOf<P>>( private val patchedProp: KProperty1<*, P>, private val patchedClazz: KClass<*> ) { /** Provides a delegate for given instance. */ operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): RequiredNestedPatchDelegate<T, P, U> { if (::patchedClass.isInitialized && patchedClass != patchedClazz) throw IllegalArgumentException("All delegate targets must belong to ${patchedClass.simpleName} and '${property.name}' does not") patchedClass = patchedClazz if (patchedProp !is KMutableProperty1<*, *>) canModifyInPlace = false if (property !is KMutableProperty1<*, *>) throw UnsupportedOperationException("Delegated property must be mutable: ${property.name}") @Suppress("UNCHECKED_CAST") // Safe if not called from outside of this class val patch = RequiredNestedPatchDelegate<T, P, U>(property.name, patchedProp as KProperty1<T, P>) @Suppress("UNCHECKED_CAST") // Safe delegates.add(patch as AbstractPatchDelegate<T, Any?>) return patch } } }
1
null
0
6
6ba84d7635e08cbb29215687d0a5f6f5cf808fea
23,401
ktor-controllers
MIT License
acc2/src/main/java/com/angcyo/acc2/parse/ConditionParse.kt
angcyo
229,037,615
false
null
package com.angcyo.acc2.parse import android.os.Build import com.angcyo.acc2.action.Action import com.angcyo.acc2.bean.ConditionBean import com.angcyo.library._screenHeight import com.angcyo.library._screenWidth import com.angcyo.library.component.appBean import com.angcyo.library.ex.isDebug import com.angcyo.library.ex.subEnd import com.angcyo.library.ex.subStart import com.angcyo.library.getAppVersionCode import com.angcyo.library.utils.CpuUtils import com.angcyo.library.utils.Device import kotlin.random.Random /** * 条件解析, 判断是否满足约束的条件 * * Email:<EMAIL> * @author angcyo * @date 2021/01/30 * Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved. */ class ConditionParse(val accParse: AccParse) : BaseParse() { companion object { /**条件是或者的关系*/ val OR = "!or!" } /**判断给定的条件, 是否有满足 * [conditionList] 一组条件, 只要满足其中一个, 就会返回true * @return true 表示有条件满足*/ fun parse(conditionList: List<ConditionBean>?): ConditionResult { val result = ConditionResult() if (conditionList.isNullOrEmpty()) { result.success = true } else { for (condition in conditionList) { if (parse(condition)) { result.success = true result.conditionBean = condition break } } } return result } /**约束条件是否解析通过 * @return true 条件满足*/ fun parse(condition: ConditionBean): Boolean { var result = true val accControl = accParse.accControl condition.apply { //random if (random) { result = Random.nextBoolean() } //system if (result && system != null) { result = verifySystem(system) } //app if (result && app != null) { val packageList = accParse.textParse.parsePackageName( null, accParse.findParse.windowBean()?.packageName ?: accControl._taskBean?.packageName ) //有一个包, 验证通过即可 var verifyApp = false for (packageName in packageList) { verifyApp = verifyApp(packageName, app) if (verifyApp) { break } } result = verifyApp } //debug if (result && debug != null) { result = if (debug == true) isDebug() else !isDebug() } val or = condition.or //textMapList if (result && !textMapList.isNullOrEmpty()) { for (key in textMapList!!) { val value = accControl._taskBean?.textListMap?.get(key) ?: accControl._taskBean?.textMap?.get(key) if (value == null) { //指定key对应的value没有值, 则条件不满足 result = false break } } } if (or && result) { return result } //noTextMapList if (result && !noTextMapList.isNullOrEmpty()) { for (key in noTextMapList!!) { val value = accControl._taskBean?.textListMap?.get(key) ?: accControl._taskBean?.textMap?.get(key) if (value != null) { //指定key对应的value有值, 则条件不满足 result = false break } } } if (or && result) { return result } //textInputFinishList if (result && !textInputFinishList.isNullOrEmpty()) { //约束文本书否输入完成 result = false for (textKey in textInputFinishList!!) { if (accControl.accSchedule.inputFinishList.contains(textKey)) { result = true break } } } if (or && result) { return result } //noTextInputFinishList if (result && !noTextInputFinishList.isNullOrEmpty()) { //约束文本书否输入未完成 for (textKey in noTextInputFinishList!!) { if (accControl.accSchedule.inputFinishList.contains(textKey)) { result = false break } } } if (or && result) { return result } //actionResultList if (result && !actionResultList.isNullOrEmpty()) { for (actionId in actionResultList!!) { if (accControl.accSchedule.actionResultMap[actionId] != true) { //指定id的action执行失败, 则条件不满足 result = false break } } } if (or && result) { return result } //检查次数是否满足表达式 [100:>=9] [.:>=9] fun checkCount(expression: String, countGetAction: (actionId: Long) -> Long): Boolean { val actionExp = expression.subStart(Action.ARG_SPLIT) val exp = expression.subEnd(Action.ARG_SPLIT) if (!exp.isNullOrEmpty()) { val actionBean = if (actionExp == ".") { accControl.accSchedule._scheduleActionBean } else { val actionId = actionExp?.toLongOrNull() accControl.findAction(actionId) } if (actionBean != null) { val count = countGetAction(actionBean.actionId) if (!accParse.expParse.parseAndCompute(exp, inputValue = count.toFloat())) { //运行次数不满足条件 return false } } } return true } if (or && result) { return result } //actionRunList if (result && !actionRunList.isNullOrEmpty()) { for (expression in actionRunList!!) { var actionId = -1L val check = checkCount(expression) { actionId = it accControl.accSchedule.getRunCount(it) } if (check) { if (expression.contains(Action.CLEAR)) { accControl.accSchedule.clearRunCount(actionId) } } else { //运行次数不满足条件 result = false break } } } if (or && result) { return result } //检查时长是否满足表达式 [100:>=9] [.:>=9] fun checkTime(expression: String, timeGetAction: (actionId: Long) -> Long): Boolean { val actionExp = expression.subStart(Action.ARG_SPLIT) val actionId = actionExp?.toLongOrNull() val exp = expression.subEnd(Action.ARG_SPLIT) if (!exp.isNullOrEmpty()) { val actionBean = if (actionExp == ".") { accControl.accSchedule._scheduleActionBean } else { accControl.findAction(actionId) } if (actionBean != null) { val time = timeGetAction(actionBean.actionId) if (!accParse.expParse.parseAndCompute(exp, inputValue = time.toFloat())) { //运行次数不满足条件 return false } } } return true } if (or && result) { return result } //actionTimeList if (result && !actionTimeList.isNullOrEmpty()) { for (expression in actionTimeList!!) { var actionId = -1L val check = checkTime(expression) { actionId = it accControl.accSchedule.getActionRunTime(it) } if (check) { if (expression.contains(Action.CLEAR)) { accControl.accSchedule.clearActionRunTime(actionId) } } else { //运行时长不满足条件 result = false break } } } if (or && result) { return result } //actionJumpList if (result && !actionJumpList.isNullOrEmpty()) { for (expression in actionJumpList!!) { var actionId = -1L val check = checkCount(expression) { actionId = it accControl.accSchedule.getJumpCount(it) } if (check) { if (expression.contains(Action.CLEAR)) { accControl.accSchedule.clearJumpCount(actionId) } } else { //跳转次数不满足条件 result = false break } } } if (or && result) { return result } //actionEnableList if (result && !actionEnableList.isNullOrEmpty()) { for (actionId in actionEnableList!!) { val actionBean = accControl.findAction(actionId) if (actionBean != null) { if (!actionBean.enable) { //未激活, 则不满足条件 result = false break } } } } if (or && result) { return result } //actionIndex if (result && actionIndex != null) { val pass = accParse.expParse.parseAndCompute( actionIndex, inputValue = accControl.accSchedule._currentIndex.toFloat() ) if (!pass) { //不符合 result = false } } } return result } fun verifySystem(value: String?): Boolean { if (value.isNullOrEmpty()) { return true } fun _verify(v: String, def: Boolean = false): Boolean { val all = v.split(";") var result = true for (con in all) { if (con.isNotEmpty()) { result = when { con.startsWith("windowFullscreen:") -> { //约束浮窗全屏状态 true } con.startsWith("windowTouchable:") -> { //约束浮窗全屏状态 true } con.startsWith("api") -> { //约束系统api accParse.expParse.parseAndCompute( con.drop(3), inputValue = Build.VERSION.SDK_INT.toFloat() ) } con.startsWith("code") -> { //约束应用程序版本 accParse.expParse.parseAndCompute( con.drop(4), inputValue = getAppVersionCode().toFloat() ) } con.startsWith("brand") -> { //约束手机品牌 Build.BRAND == con.drop(5) } con.startsWith("model") -> { //约束手机型号 Build.MODEL == con.drop(5) } con.startsWith("cpu") -> { //约束手机cpu最大频率 /*CpuUtils.cpuMaxFreq >= 2_800_000L*/ accParse.expParse.parseAndCompute( con.drop(3), inputValue = CpuUtils.cpuMaxFreq.toFloat() ) } con.startsWith("mem") -> { //约束手机cpu最大的内存大小 accParse.expParse.parseAndCompute( con.drop(3), inputValue = Device.getTotalMemory().toFloat() ) } //字母少的, 放在后面匹配 con.startsWith("w") -> { //约束手机屏幕宽度 accParse.expParse.parseAndCompute( con.drop(1), inputValue = _screenWidth.toFloat() ) } con.startsWith("h") -> { //约束手机屏幕高度 accParse.expParse.parseAndCompute( con.drop(1), inputValue = _screenHeight.toFloat() ) } else -> { //无法识别的指令 def } } if (!result) { break } } } return result } val groups = value.split(OR) var result = false for (group in groups) { if (_verify(group, result)) { result = true break } } return result } fun verifyApp(packageName: String?, value: String?): Boolean { if (packageName.isNullOrEmpty() || value.isNullOrEmpty()) { return true } val appBean = packageName.appBean() ?: return false fun _verify(v: String, def: Boolean = false): Boolean { val all = v.split(";") var result = true for (con in all) { if (con.isNotEmpty()) { result = when { con.startsWith("code") -> { //约束应用程序版本 accParse.expParse.parseAndCompute( con.drop(4), inputValue = appBean.versionCode.toFloat() ) } else -> { //无法识别的指令 def } } if (!result) { break } } } return result } val groups = value.split(OR) var result = false for (group in groups) { if (_verify(group, result)) { result = true break } } return result } }
0
null
6
5
e1eaccee8648133d8fe35713127439b06c8dfef0
15,974
UICore
MIT License
app/src/main/kotlin/jp/co/yumemi/android/code_check/model/dataClass/Item.kt
NoriyoshiTanaka
779,711,026
false
{"Kotlin": 29018}
package jp.co.yumemi.android.code_check.model.dataClass import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Item( @SerialName("forks_count") val forksCount: Int, @SerialName("full_name") val fullName: String, @SerialName("language") val language: String?, @SerialName("open_issues_count") val openIssuesCount: Int, @SerialName("owner") val owner: Owner, @SerialName("stargazers_count") val stargazersCount: Int, @SerialName("watchers_count") val watchersCount: Int, )
2
Kotlin
0
0
d9744a19882feeb35158da9dc3647e6b7cc03212
581
engineer-codecheck
Apache License 2.0
src/main/kotlin/com/kentrino/db/Book.kt
kentrino
200,906,140
false
null
package com.kentrino.db data class Book( val id: Int, val title: String )
0
Kotlin
0
0
8f02cd7cc62e14b1d955b87f5a3f1eb9b1829101
91
graphql-ktor-minimal
Apache License 2.0
lib/src/main/java/org/altbeacon/beacon/Settings.kt
AltBeacon
22,342,877
false
{"Java": 782435, "Kotlin": 42700}
package org.altbeacon.beacon import android.app.Notification import android.os.Build import org.altbeacon.beacon.distance.DistanceCalculatorFactory import org.altbeacon.beacon.distance.ModelSpecificDistanceCalculatorFactory import org.altbeacon.beacon.logging.LogManager import org.altbeacon.beacon.service.RunningAverageRssiFilter import org.altbeacon.beacon.simulator.BeaconSimulator data class AppliedSettings ( val debug: Boolean = Settings.Defaults.debug, val regionStatePersistenceEnabled: Boolean = Settings.Defaults.regionStatePeristenceEnabled, val hardwareEqualityEnforced: Boolean = Settings.Defaults.hardwareEqualityEnforced, val scanPeriods: Settings.ScanPeriods = Settings.Defaults.scanPeriods, val regionExitPeriodMillis: Int = Settings.Defaults.regionExitPeriodMillis, val useTrackingCache: Boolean = Settings.Defaults.useTrackingCache, val maxTrackingAgeMillis: Int = Settings.Defaults.maxTrackingAgeMillis, val manifestCheckingDisabled: Boolean = Settings.Defaults.manifestCheckingDisabled, val beaconSimulator: BeaconSimulator = Settings.Defaults.beaconSimulator, val rssiFilterImplClass: Class<RunningAverageRssiFilter>? = Settings.Defaults.rssiFilterImplClass, val distanceModelUpdateUrl: String = Settings.Defaults.distanceModelUpdateUrl, val distanceCalculatorFactory: DistanceCalculatorFactory = Settings.Defaults.distanceCalculatorFactory, val scanStrategy: Settings.ScanStrategy = Settings.Defaults.scanStrategy.clone(), val longScanForcingEnabled: Boolean = Settings.Defaults.longScanForcingEnabled ) { companion object { /** * Makes a new settings object from the active settings, applying the non-null changes in the delta */ fun fromDeltaSettings(settings: AppliedSettings, delta:Settings) : AppliedSettings { return AppliedSettings(scanPeriods = delta.scanPeriods ?: settings.scanPeriods, debug = delta.debug ?: settings.debug, regionStatePersistenceEnabled = delta.regionStatePersistenceEnabled ?: settings.regionStatePersistenceEnabled, useTrackingCache = delta.useTrackingCache ?: settings.useTrackingCache, hardwareEqualityEnforced = delta.hardwareEqualityEnforced ?: settings.hardwareEqualityEnforced, regionExitPeriodMillis = delta.regionExitPeriodMillis ?: settings.regionExitPeriodMillis, maxTrackingAgeMillis = delta.maxTrackingAgeMillis ?: settings.maxTrackingAgeMillis, manifestCheckingDisabled = delta.manifestCheckingDisabled ?: settings.manifestCheckingDisabled, beaconSimulator = delta.beaconSimulator ?: settings.beaconSimulator, rssiFilterImplClass = delta.rssiFilterImplClass ?: settings.rssiFilterImplClass, scanStrategy = delta.scanStrategy?.clone() ?: settings.scanStrategy, longScanForcingEnabled = delta.longScanForcingEnabled ?: settings.longScanForcingEnabled, distanceModelUpdateUrl = delta.distanceModelUpdateUrl ?: settings.distanceModelUpdateUrl, distanceCalculatorFactory = delta.distanceCalculatorFactory ?: settings.distanceCalculatorFactory) } fun withDefaultValues(): AppliedSettings { return AppliedSettings(scanPeriods = Settings.Defaults.scanPeriods, debug = Settings.Defaults.debug, regionStatePersistenceEnabled = Settings.Defaults.regionStatePeristenceEnabled, useTrackingCache = Settings.Defaults.useTrackingCache, hardwareEqualityEnforced = Settings.Defaults.hardwareEqualityEnforced, regionExitPeriodMillis = Settings.Defaults.regionExitPeriodMillis, maxTrackingAgeMillis = Settings.Defaults.maxTrackingAgeMillis, manifestCheckingDisabled = Settings.Defaults.manifestCheckingDisabled, beaconSimulator = Settings.Defaults.beaconSimulator, rssiFilterImplClass = Settings.Defaults.rssiFilterImplClass, scanStrategy = Settings.Defaults.scanStrategy.clone(), longScanForcingEnabled = Settings.Defaults.longScanForcingEnabled, distanceModelUpdateUrl = Settings.Defaults.distanceModelUpdateUrl, distanceCalculatorFactory = Settings.Defaults.distanceCalculatorFactory) } fun fromSettings(other: AppliedSettings) : AppliedSettings { return AppliedSettings(scanPeriods = other.scanPeriods, debug = other.debug, regionStatePersistenceEnabled = other.regionStatePersistenceEnabled, useTrackingCache = other.useTrackingCache, hardwareEqualityEnforced = other.hardwareEqualityEnforced, regionExitPeriodMillis = other.regionExitPeriodMillis, maxTrackingAgeMillis = other.maxTrackingAgeMillis, manifestCheckingDisabled = other.manifestCheckingDisabled, beaconSimulator = other.beaconSimulator, rssiFilterImplClass = other.rssiFilterImplClass, scanStrategy = other.scanStrategy.clone(), longScanForcingEnabled = other.longScanForcingEnabled, distanceModelUpdateUrl = other.distanceModelUpdateUrl, distanceCalculatorFactory = other.distanceCalculatorFactory) } } } data class Settings( // TODO: where should javadoc comments be? on class or builder methods or both? // I guess both, because the builder is used by Java and the class methods are used by kotlin // not part of this api // --------- // BeaconParsers // rangingRegions // monitoringRegions // rangingNotifiers // monitoringNotifiers // nonBeaconScanCallback // not carried forward // ------------------- // isAndroidLScanningDisabled() /** * Sets the log level on the library to debug (true) or info (false) * Default is false */ val debug: Boolean? = null, /** * Determines if monitored regions are persisted to app shared preferences so if the app restarts, * the same regions are monitored. * Default is true */ val regionStatePersistenceEnabled: Boolean? = null, /** * Determines if two beacons with the same identifiers but with different hardware MAC addresses * are treated as different beacons. * Default is false */ val hardwareEqualityEnforced: Boolean? = null, val scanPeriods: ScanPeriods? = null, /** * How many milliseconds to wait after seeing the last beacon in a region before marking it as exited. */ val regionExitPeriodMillis: Int? = null, val useTrackingCache: Boolean? = null, val maxTrackingAgeMillis: Int? = null, val manifestCheckingDisabled: Boolean? = null, val beaconSimulator: BeaconSimulator? = null, val rssiFilterImplClass: Class<RunningAverageRssiFilter>? = null, val distanceModelUpdateUrl: String? = null, val distanceCalculatorFactory: DistanceCalculatorFactory? = null, val scanStrategy: ScanStrategy? = null, val longScanForcingEnabled: Boolean? = null ) { companion object { fun fromSettings(other: Settings) : Settings { return Settings(scanPeriods = other.scanPeriods, debug = other.debug, regionStatePersistenceEnabled = other.regionStatePersistenceEnabled, useTrackingCache = other.useTrackingCache, hardwareEqualityEnforced = other.hardwareEqualityEnforced, regionExitPeriodMillis = other.regionExitPeriodMillis, maxTrackingAgeMillis = other.maxTrackingAgeMillis, manifestCheckingDisabled = other.manifestCheckingDisabled, beaconSimulator = other.beaconSimulator, rssiFilterImplClass = other.rssiFilterImplClass, scanStrategy = other.scanStrategy?.clone(), longScanForcingEnabled = other.longScanForcingEnabled, distanceModelUpdateUrl = other.distanceModelUpdateUrl, distanceCalculatorFactory = other.distanceCalculatorFactory) } fun fromBuilder(builder: Builder) : Settings { return Settings(scanPeriods = builder._scanPeriods, debug = builder._debug, regionStatePersistenceEnabled = builder._regionStatePeristenceEnabled, useTrackingCache = builder._useTrackingCache, hardwareEqualityEnforced = builder._hardwareEqualityEnforced, regionExitPeriodMillis = builder._regionExitPeriodMillis, maxTrackingAgeMillis = builder._maxTrackingAgeMillis, manifestCheckingDisabled = builder._manifestCheckingDisabled, beaconSimulator = builder._beaconSimulator, rssiFilterImplClass = builder._rssiFilterImplClass, scanStrategy = builder._scanStrategy?.clone(), longScanForcingEnabled = builder._longScanForcingEnabled, distanceModelUpdateUrl = builder._distanceModelUpdateUrl, distanceCalculatorFactory = builder._distanceCalculatorFactory) } } object Defaults { const val debug = false val scanStrategy: ScanStrategy const val longScanForcingEnabled = false val scanPeriods = ScanPeriods() const val regionExitPeriodMillis = 30000 const val useTrackingCache = true const val maxTrackingAgeMillis = 10000 const val manifestCheckingDisabled = false val beaconSimulator = DisabledBeaconSimulator() val rssiFilterImplClass = RunningAverageRssiFilter::class.java const val regionStatePeristenceEnabled = true const val hardwareEqualityEnforced = false const val distanceModelUpdateUrl = "" // disabled val distanceCalculatorFactory = ModelSpecificDistanceCalculatorFactory() init{ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { scanStrategy = JobServiceScanStrategy() } else { scanStrategy = BackgroundServiceScanStrategy() } } } class Builder { internal var _scanPeriods: ScanPeriods? = null internal var _debug: Boolean? = null internal var _regionStatePeristenceEnabled: Boolean? = null internal var _useTrackingCache: Boolean? = null internal var _hardwareEqualityEnforced: Boolean? = null internal var _regionExitPeriodMillis: Int? = null internal var _maxTrackingAgeMillis: Int? = null internal var _manifestCheckingDisabled: Boolean? = null internal var _beaconSimulator: BeaconSimulator? = null internal var _rssiFilterImplClass: Class<RunningAverageRssiFilter>? = null internal var _distanceModelUpdateUrl: String? = null internal var _distanceCalculatorFactory: DistanceCalculatorFactory? = null internal var _scanStrategy: ScanStrategy? = null internal var _longScanForcingEnabled: Boolean? = null fun setDebug(debug: Boolean): Builder { this._debug = debug return this } fun setScanPeriods(scanPeriods: ScanPeriods): Builder { this._scanPeriods = scanPeriods return this } fun setDistanceModelUpdateUrl(url: String): Builder { this._distanceModelUpdateUrl = url return this } fun setDistanceCalculatorFactory(factory: DistanceCalculatorFactory): Builder { this._distanceCalculatorFactory = factory return this } fun setBeaconSimulator(beaconSimulator: BeaconSimulator): Builder { this._beaconSimulator = beaconSimulator return this } fun setScanStrategy(scanStrategy: ScanStrategy): Builder { this._scanStrategy = scanStrategy return this } fun setLongScanForcingEnabled(longScanForcingEnabled: Boolean): Builder { this._longScanForcingEnabled = longScanForcingEnabled return this } fun build(): Settings { return fromBuilder(this) } // TODO: add all other setters } data class ScanPeriods ( val foregroundScanPeriodMillis: Long = 1100, val foregroundBetweenScanPeriodMillis: Long = 0, val backgroundScanPeriodMillis: Long = 30000, val backgroundBetweenScanPeriodMillis: Long = 0 ) interface ScanStrategy: Comparable<ScanStrategy> { fun clone(): ScanStrategy /** * Internal use only. */ fun configure(beaconManager: BeaconManager) } class JobServiceScanStrategy(val immediateJobId: Long = 208352939, val periodicJobId: Long = 208352940, val jobPersistenceEnabled: Boolean = true): ScanStrategy { override fun clone(): JobServiceScanStrategy { return JobServiceScanStrategy(this.immediateJobId, this.periodicJobId, this.jobPersistenceEnabled) } override fun equals(other: Any?): Boolean { val otherJobServiceScanStrategy = other as? JobServiceScanStrategy if (otherJobServiceScanStrategy != null) { return (this.immediateJobId == otherJobServiceScanStrategy.immediateJobId && this.periodicJobId == otherJobServiceScanStrategy.periodicJobId && this.jobPersistenceEnabled == otherJobServiceScanStrategy.jobPersistenceEnabled) } return false } override fun hashCode(): Int { return javaClass.hashCode() } override fun configure(beaconManager: BeaconManager) { beaconManager.setEnableScheduledScanJobs(true) beaconManager.setIntentScanningStrategyEnabled(false) } override fun compareTo(other: ScanStrategy): Int { return if (other is JobServiceScanStrategy) { if (this.immediateJobId == other.immediateJobId && this.periodicJobId == other.periodicJobId && this.jobPersistenceEnabled == other.jobPersistenceEnabled) { 0 } else { -1 } } else { -1 } } } class BackgroundServiceScanStrategy(): ScanStrategy { override fun clone(): BackgroundServiceScanStrategy { return BackgroundServiceScanStrategy() } override fun equals(other: Any?): Boolean { return other as? BackgroundServiceScanStrategy != null } override fun hashCode(): Int { return javaClass.hashCode() } override fun configure(beaconManager: BeaconManager) { beaconManager.setEnableScheduledScanJobs(false) beaconManager.setIntentScanningStrategyEnabled(false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { LogManager.w( "BackgroundServiceScanStrategy", "Using the BackgroundService scan strategy on Android 8+ may disable delivery of " + "beacon callbacks in the background." ) } } override fun compareTo(other: ScanStrategy): Int { return if (other is BackgroundServiceScanStrategy) { 0 } else { -1 } } } class ForegroundServiceScanStrategy(val notification: Notification, val notificationId: Int): ScanStrategy { var androidLScanningDisabled = true override fun clone(): ForegroundServiceScanStrategy { return ForegroundServiceScanStrategy(notification, notificationId) } override fun equals(other: Any?): Boolean { val otherForegroundServiceScanStrategy = other as? ForegroundServiceScanStrategy if (otherForegroundServiceScanStrategy != null) { return (this.notificationId == otherForegroundServiceScanStrategy.notificationId && this.androidLScanningDisabled == otherForegroundServiceScanStrategy.androidLScanningDisabled) } return false } override fun hashCode(): Int { return javaClass.hashCode() } override fun configure(beaconManager: BeaconManager) { beaconManager.setEnableScheduledScanJobs(false) beaconManager.setIntentScanningStrategyEnabled(false) beaconManager.enableForegroundServiceScanning(notification, notificationId) } override fun compareTo(other: ScanStrategy): Int { return if (other is ForegroundServiceScanStrategy) { if (this.notificationId == other.notificationId && this.androidLScanningDisabled == other.androidLScanningDisabled) { 0 } else { -1 } } else { -1 } } } class IntentScanStrategy: ScanStrategy { override fun clone(): IntentScanStrategy { return IntentScanStrategy() } override fun equals(other: Any?): Boolean { return other as? IntentScanStrategy != null } override fun hashCode(): Int { return javaClass.hashCode() } override fun configure(beaconManager: BeaconManager) { beaconManager.setEnableScheduledScanJobs(false) beaconManager.setIntentScanningStrategyEnabled(true) } override fun compareTo(other: ScanStrategy): Int { return if (other is IntentScanStrategy) { 0 } else { -1 } } } class DisabledBeaconSimulator: BeaconSimulator { override fun getBeacons(): MutableList<Beacon> { return mutableListOf() } } }
165
Java
836
2,840
ae4ce8ad11dd961e6d20b17ea0c1a39107c49c61
17,661
android-beacon-library
Apache License 2.0
mesh-exam/library/nearby/src/main/java/io/flaterlab/meshexam/library/nearby/api/NearbyFacade.kt
chorobaev
434,863,301
false
{"Kotlin": 467494, "Java": 1951}
package io.flaterlab.meshexam.library.nearby.api import io.flaterlab.meshexam.library.nearby.impl.AdvertiserInfo import io.flaterlab.meshexam.library.nearby.impl.ClientInfo import io.flaterlab.meshexam.library.nearby.impl.ConnectionResult import kotlinx.coroutines.flow.Flow interface NearbyFacade { fun advertise(advertiserInfo: AdvertiserInfo): Flow<ConnectionResult<ClientInfo>> fun discover(): Flow<List<Pair<String, AdvertiserInfo>>> fun connect(endpointId: String, clientInfo: ClientInfo): Flow<ConnectionResult<AdvertiserInfo>> fun acceptConnection(endpointId: String): Flow<ByteArray> suspend fun sendPayload(vararg toEndpointId: String, data: ByteArray) }
0
Kotlin
0
2
364c4fcb70a461fc02d2a5ef2590ad5f8975aab5
691
mesh-exam
MIT License
anrspy/src/main/java/pk/farimarwat/anrspy/agent/ANRSpyException.kt
farimarwat
579,959,968
false
{"Kotlin": 17309}
package pk.farimarwat.anrspy.agent class ANRSpyException(title:String, stacktrace:Array<StackTraceElement>):Throwable(title) { init { stackTrace = stacktrace } }
1
Kotlin
11
55
4d01d72a0f8fddded2a204eb0b09110d551087a2
178
ANR-Spy
Apache License 2.0
serialization/src/main/kotlin/com/ing/zkflow/serialization/serializer/string/FixedSizeUtf16StringSerializer.kt
ing-bank
550,239,957
false
{"Kotlin": 1610321, "Shell": 1609}
package com.ing.zkflow.serialization.serializer.string import com.ing.zkflow.serialization.FixedLengthType import com.ing.zkflow.util.require /** * Serializer for [String], using UTF-16 encoding. The UTF-16 encoded byte array is restrained by [maxBytes]. * * UTF-16 is a variable-width character encoding, meaning that single characters may be encoded in multiple positions. */ open class FixedSizeUtf16StringSerializer(maxBytes: Int) : AbstractFixedSizeStringSerializer( maxBytes.require({ it % Short.SIZE_BYTES == 0 }) { "Maximum number of bytes in a ${Charsets.UTF_16.name()} string must be a multiple of ${Short.SIZE_BYTES}." }, FixedLengthType.UTF16_STRING, Charsets.UTF_16, )
0
Kotlin
4
9
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
740
zkflow
MIT License
Concurrency/Demos/src/main/kotlin/palbp/laboratory/demos/synch/exercises/MessageQueue.kt
palbp
463,200,783
false
{"Kotlin": 701033, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Swift": 594, "Makefile": 383}
package palbp.laboratory.demos.synch.exercises import java.lang.Thread.currentThread import java.util.LinkedList import java.util.concurrent.locks.Condition import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.time.Duration /** * A possible solution for the following exercise. * * Implement the message queue synchronizer, to support communication between producer and consumer threads * through messages of generic type T. The communication must use the FIFO criterion (first in first out). * The public interface of this synchronizer is as follows: * * class MessageQueue<T>() { * fun enqueue(message: T): Unit { … } * @Throws(InterruptedException::class) * fun tryDequeue(nOfMessages: Int, timeout: Duration): List<T>? { … } * } * * The [enqueue] method delivers a message to the queue without blocking the caller thread. The [tryDequeue] method * attempts to remove [nOfMessages] messages from the queue, blocking the invoking thread as long as: * 1) this operation cannot complete successfully, or * 2) the timeout time set for the operation does not expire, or * 3) the thread is not interrupted. * Note that message removal cannot be performed partially, i.e. either [nOfMessages] messages are removed or * no messages are removed. These removal operations must be completed on a first-come, first-served basis, * regardless of the values [nOfMessages]. Be aware of the consequences of giving up (either through cancellation * or timeout) on a [tryDequeue] operation. */ class MessageQueue<T> { private class DequeueRequest<T>( val nOfMessages: Int, val condition: Condition, var messages: List<T>? = null ) private val guard = ReentrantLock() private val dequeueRequests = LinkedList<DequeueRequest<T>>() private val messages = LinkedList<T>() fun enqueue(message: T) { guard.withLock { messages.addLast(message) tryCompletePendingDequeues() } } @Throws(InterruptedException::class) fun tryDequeue(nOfMessages: Int, timeout: Duration): List<T>? { guard.withLock { if (dequeueRequests.isEmpty() && messages.size >= nOfMessages) return takeMessages(nOfMessages) val myRequest = DequeueRequest<T>(nOfMessages, guard.newCondition()) dequeueRequests.addLast(myRequest) var remainingTime = timeout.inWholeNanoseconds try { while (true) { remainingTime = myRequest.condition.awaitNanos(remainingTime) if (myRequest.messages != null) return myRequest.messages if (remainingTime <= 0) { dequeueRequests.remove(myRequest) tryCompletePendingDequeues() return null } } } catch (ie: InterruptedException) { if(dequeueRequests.remove(myRequest)) { tryCompletePendingDequeues() throw ie } currentThread().interrupt() return myRequest.messages } } } private fun takeMessages(nOfMessages: Int) = List(nOfMessages) { messages.removeFirst() } private fun tryCompletePendingDequeues() { while(dequeueRequests.isNotEmpty() && messages.size >= dequeueRequests.first.nOfMessages) { val completedRequest = dequeueRequests.removeFirst() completedRequest.messages = takeMessages(completedRequest.nOfMessages) completedRequest.condition.signal() } } }
1
Kotlin
0
5
84df1fe3be31ae2daf1414131d91e960a03ae224
3,741
laboratory
MIT License
app/src/main/java/com/example/weatherapplication/data/Main.kt
JyothiGunnam29
864,795,329
false
{"Kotlin": 62154, "Java": 1165}
package com.example.weatherapplication.data import com.google.gson.annotations.SerializedName class Main { @JvmField @SerializedName("temp") var temp: Double = 0.0 @SerializedName("feels_like") var feels_like: Double = 0.0 @JvmField @SerializedName("temp_min") var temp_min: Double = 0.0 @JvmField @SerializedName("temp_max") var temp_max: Double = 0.0 @SerializedName("pressure") var pressure: Int = 0 @JvmField @SerializedName("humidity") var humidity: Int = 0 @SerializedName("sea_level") var sea_level: Int = 0 @SerializedName("grnd_level") var grnd_level: Int = 0 }
0
Kotlin
0
0
bdfacafee3e24d9de0994c2d0946c5e56e41cbc9
660
WeatherApplication
MIT License
app/src/main/kotlin/com/rodolfonavalon/canadatransit/view/CustomSearchActionMode.kt
poldz123
106,507,508
false
null
package com.rodolfonavalon.canadatransit.view import android.content.Context import android.view.ActionMode import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.EditorInfo import android.widget.EditText import androidx.core.content.ContextCompat import androidx.core.widget.doAfterTextChanged import com.rodolfonavalon.canadatransit.R import com.rodolfonavalon.canadatransit.controller.util.extension.activity import com.rodolfonavalon.canadatransit.controller.util.extension.closeKeyboard import com.rodolfonavalon.canadatransit.controller.util.extension.focus import com.rodolfonavalon.canadatransit.controller.util.extension.listenOnImePressed import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import java.util.concurrent.TimeUnit class CustomSearchActionMode : ActionMode.Callback { private var mode: ActionMode? = null private var context: Context? = null var isShowing = false var onDestroyedListener: (() -> Unit)? = null var onQueryListener: ((String) -> Unit)? = null private var onCreatedListener: ((mode: ActionMode) -> Unit)? = null private var autoCompletePublishSubject = PublishSubject.create<String>() private var autoCompleteDisposable: Disposable? = null fun start(view: View, createdListener: (mode: ActionMode) -> Unit) { this.context = view.context this.onCreatedListener = createdListener mode?.also { actionMode -> // If it is showing already just call the on-created listener all over again to prevent // the action mode to show and hide that can cause a bug. createdListener(actionMode) } ?: view.startActionMode(this) } fun update() { (mode?.customView as EditText).also { editText -> onQueryListener?.invoke(editText.text.toString()) } } fun finish() { mode?.finish() } fun closeKeyboard() { mode?.customView?.also { search -> context?.closeKeyboard(search) } } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { return true } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { isShowing = true val search = View.inflate(context, R.layout.view_search, null) as EditText mode.customView = search this.mode = mode context?.also { context -> context.activity().window?.statusBarColor = ContextCompat.getColor(context, R.color.actionModeColorPrimaryDark) // Show the keyboard automatically when this action mode is created. Must be called after // this view is referenced to the action mode custom view. search.focus() search.listenOnImePressed(EditorInfo.IME_ACTION_DONE) { closeKeyboard() } // Create a autocomplete delay to prevent very fast emissions of the searched text autoCompleteDisposable = autoCompletePublishSubject .debounce(300, TimeUnit.MILLISECONDS) .distinctUntilChanged() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { text -> onQueryListener?.invoke(text) } search.doAfterTextChanged { editable -> val text = editable.toString() autoCompletePublishSubject.onNext(text) } } onCreatedListener?.invoke(mode) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return false } override fun onDestroyActionMode(mode: ActionMode) { isShowing = false // Change back the original status bar color context?.also { context -> context.activity().window?.statusBarColor = ContextCompat.getColor(context, R.color.colorPrimaryDark) closeKeyboard() autoCompleteDisposable?.dispose() autoCompleteDisposable = null onQueryListener = null } this.mode = null this.context = null onDestroyedListener?.invoke() } }
13
Kotlin
0
1
619bda01c045850282865bfeaca823e2ff7887fd
4,403
CanadaTransit
MIT License
app/src/main/kotlin/org/geepawhill/kontentment/app/kwrappers/KPresentationPane.kt
GeePawHill
635,065,699
false
null
package org.geepawhill.kontentment.app.kwrappers import javafx.event.EventTarget import javafx.scene.canvas.Canvas import javafx.scene.layout.StackPane import javafx.scene.paint.Color import org.geepawhill.kontentment.app.Model import tornadofx.* class KPresentationPane(val model: Model) : StackPane() { val canvas = Canvas(1.777 * 300.0, 300.0) private val widthToHeight by model.presentationWidthToHeight init { model.presentationWidthToHeight.addListener { _, _, _ -> resetCanvasDimensions() } prefWidth = 500.0 minHeight = 10.0 minWidth = 10.0 this += canvas drawOnCanvas() } override fun layoutChildren() { println("P: ${width} X ${height}") resetCanvasDimensions() super.layoutChildren() } private fun resetCanvasDimensions() { val newWidth = snapSizeX(width) - (snappedLeftInset() + snappedRightInset()) val newHeight = snapSizeY(height) - (snappedTopInset() + snappedBottomInset()) val widthByHeight = snapSizeY(newWidth / widthToHeight) if (widthByHeight < newHeight) { canvas.width = newWidth canvas.height = widthByHeight } else { val widthFromHeight = snapSizeX(newHeight * widthToHeight) canvas.width = widthFromHeight canvas.height = newHeight } drawOnCanvas() } fun drawOnCanvas() { with(canvas.graphicsContext2D) { fill = Color.BLACK fillRect(0.0, 0.0, canvas.width, canvas.height) stroke = Color.RED lineWidth = 1.0 val endX = canvas.width - 2.0 val endY = canvas.height - 2.0 strokeLine(2.0, 2.0, endX, 2.0) strokeLine(endX, 2.0, endX, endY) strokeLine(endX, endY, 2.0, endY) strokeLine(2.0, endY, 2.0, 2.0) strokeLine(2.0, 2.0, endX, endY) strokeLine(2.0, endY, endX, 2.0) } } } fun EventTarget.kpresentationpane( model: Model, widthToHeight: Double, op: KPresentationPane.() -> Unit = {} ): KPresentationPane { val pane = KPresentationPane(model).apply { model.windowing.normalRegion(this) } return opcr(this, pane, op) }
0
Kotlin
0
0
89bf3aa898a5e6fb93f94d3a23a69919b027707e
2,291
kontentment2
MIT License
idea/testData/refactoring/safeDeleteMultiModule/byImplClass/after/JS/src/test/test.kt
thomasandersen77
102,865,590
true
{"Java": 26482478, "Kotlin": 25028296, "JavaScript": 144916, "Protocol Buffer": 57463, "HTML": 55691, "Lex": 18174, "Groovy": 14228, "ANTLR": 9797, "IDL": 8350, "Shell": 5436, "CSS": 4679, "Batchfile": 4437}
package test impl class ChildOfFoo : Foo()
0
Java
0
1
c4ebfe8e8405e761461921558a9f39826d649920
43
kotlin
Apache License 2.0