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
src/main/kotlin/com/github/dangerground/aoc2020/Day1.kt
dangerground
317,439,198
false
null
package com.github.dangerground.aoc2020 import com.github.dangerground.aoc2020.util.DayInput class Day1 { fun getTwoNumbersMatching(input: List<Int>, matching: Int): List<Int> { input.forEach { it1 -> input.forEach { it2 -> if (it1 + it2 == matching) { return listOf(it1, it2) } } } throw Exception("Unexpectd") } fun getThreeNumbersMatching(input: List<Int>, matching: Int): List<Int> { input.forEach { it1 -> input.forEach { it2 -> input.forEach { it3 -> if (it1 + it2 + it3 == matching) { return listOf(it1, it2, it3) } } } } throw Exception("Unexpectd") } fun getMultipliedIntermediateOfTwo(input: List<Int>, matching: Int) = getTwoNumbersMatching(input, matching) .reduce { num1, num2 -> num1 * num2 } fun getMultipliedIntermediateOfThree(input: List<Int>, matching: Int) = getThreeNumbersMatching(input, matching) .reduce { num1, num2 -> num1 * num2 } } fun main() { val day1 = Day1() val input = DayInput.asIntList(1) // part 1 val part1 = day1.getMultipliedIntermediateOfTwo(input, 2020) println("result part1: $part1") // part 2 val part2 = day1.getMultipliedIntermediateOfThree(input, 2020) println("result part2: $part2") }
0
Kotlin
0
0
c3667a2a8126d903d09176848b0e1d511d90fa79
1,485
adventofcode-2020
MIT License
samples/src/jvmMain/kotlin/com/lehaine/rune/PixelExample.kt
LeHaine
468,806,982
false
{"Kotlin": 88511}
package com.lehaine.rune import com.lehaine.littlekt.Context import com.lehaine.littlekt.createLittleKtApp import com.lehaine.littlekt.file.vfs.readLDtkMapLoader import com.lehaine.littlekt.file.vfs.readTexture import com.lehaine.littlekt.graph.node.Node import com.lehaine.littlekt.graph.node.addTo import com.lehaine.littlekt.graph.node.canvasLayer import com.lehaine.littlekt.graph.node.ui.control import com.lehaine.littlekt.graph.node.ui.label import com.lehaine.littlekt.graphics.Color import com.lehaine.littlekt.graphics.HdpiMode import com.lehaine.littlekt.graphics.g2d.* import com.lehaine.littlekt.graphics.slice import com.lehaine.littlekt.input.Key import com.lehaine.littlekt.math.MutableVec2f import com.lehaine.littlekt.math.random import com.lehaine.littlekt.util.seconds import com.lehaine.rune.engine.GameLevel import com.lehaine.rune.engine.Rune import com.lehaine.rune.engine.RuneSceneDefault import com.lehaine.rune.engine.node.EntityCamera2D import com.lehaine.rune.engine.node.entityCamera2D import com.lehaine.rune.engine.node.pixelPerfectSlice import com.lehaine.rune.engine.node.pixelSmoothFrameBuffer import com.lehaine.rune.engine.node.renderable.ParticleBatch import com.lehaine.rune.engine.node.renderable.entity.LevelEntity import com.lehaine.rune.engine.node.renderable.entity.cd import com.lehaine.rune.engine.node.renderable.ldtkLevel import com.lehaine.rune.engine.node.renderable.particleBatch import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds /** * @author Colton Daily * @date 3/11/2022 */ class PixelExample(context: Context) : Rune(context) { override suspend fun Context.create() { println("OpenGL version is: ${graphics.glVersion}") println("OpenGL Combined: ${graphics.glVersion.combined}") println("Is OpenGL atleast 3.2? ${graphics.glVersion.atleast(3, 2)}") println("System OS: ${System.getProperty("os.name")}") scene = PixelExampleScene(context) } } class PixelExampleScene(context: Context) : RuneSceneDefault(context) { override var ppu: Float = 1f private val particleSimulator = ParticleSimulator(2048) private lateinit var topNormal: ParticleBatch private lateinit var smallCircle: TextureSlice private val mouseCoords = MutableVec2f() override suspend fun Node.initialize() { val person = resourcesVfs["test/heroIdle0.png"].readTexture(mipmaps = false).slice() val mapLoader = resourcesVfs["test/platformer.ldtk"].readLDtkMapLoader() smallCircle = resourcesVfs["test/fxSmallCircle0.png"].readTexture().slice() val world = mapLoader.loadMap(true) canvasLayer { val entityCamera: EntityCamera2D val player: Player val fbo = pixelSmoothFrameBuffer { val level = ldtkLevel<String>(world.levels[0]) { gridSize = 8 } player = player(level, 8f) { sprite.slice = person cx = 20 cy = 17 onUpdate += { if (!cd.has("footstep")) { cd("footstep", 250.milliseconds) runDust(globalX, globalY, -1) } } } topNormal = particleBatch() entityCamera = entityCamera2D { viewBounds.width = world.levels[0].pxWidth.toFloat() viewBounds.height = world.levels[0].pxHeight.toFloat() follow(player, true) camera = canvasCamera onUpdate += { if (input.isKeyJustPressed(Key.Z)) { targetZoom = 0.5f } if (input.isKeyJustPressed(Key.X)) { targetZoom = 1f } } } onUpdate += { mouseCoords.x = mouseX mouseCoords.y = mouseY } } pixelPerfectSlice { this.fbo = fbo onUpdate += { scaledDistX = entityCamera.scaledDistX scaledDistY = entityCamera.scaledDistY } } } control { label { onUpdate += { text = "Mouse coords: $mouseCoords" } } } } private fun create(num: Int, createParticle: (index: Int) -> Unit) { for (i in 0 until num) { createParticle(i) } } private fun allocTopNormal(slice: TextureSlice, x: Float, y: Float) = particleSimulator.alloc(slice, x, y).also { topNormal.add(it) } private fun runDust(x: Float, y: Float, dir: Int) { create(5) { val p = allocTopNormal(smallCircle, x, y) p.scale((0.15f..0.25f).random()) p.color.set(DUST_COLOR) p.xDelta = (0.25f..0.75f).random() * dir p.yDelta = -(0.05f..0.15f).random() p.life = (0.05f..0.15f).random().seconds p.scaleDelta = (0.005f..0.015f).random() } } override fun update(dt: Duration) { super.update(dt) particleSimulator.update(dt, tmod) } @OptIn(ExperimentalContracts::class) private fun Node.player(level: GameLevel<*>, gridCellSize: Float, callback: Player.() -> Unit = {}): Player { contract { callsInPlace(callback, InvocationKind.EXACTLY_ONCE) } return Player(level, gridCellSize).also(callback).addTo(this) } private class Player(level: GameLevel<*>, gridCellSize: Float) : LevelEntity(level, gridCellSize) { private var xDir = 0 private var yDir = 0 override fun update(dt: Duration) { super.update(dt) xDir = 0 yDir = 0 if (context.input.isKeyPressed(Key.W)) { yDir = -1 } if (context.input.isKeyPressed(Key.S)) { yDir = 1 } if (context.input.isKeyPressed(Key.D)) { xDir = 1 } if (context.input.isKeyPressed(Key.A)) { xDir = -1 } if (context.input.isKeyJustPressed(Key.ENTER)) { stretchX = 2f } dir = if (xDir != 0) xDir else dir } override fun fixedUpdate() { super.fixedUpdate() velocityX += 0.12f * xDir velocityY += 0.12f * yDir } } companion object { private val DUST_COLOR = Color.fromHex("#efddc0") } } fun main() { createLittleKtApp { width = 960 height = 540 backgroundColor = Color.DARK_GRAY hdpiMode = HdpiMode.PIXELS }.start { PixelExample(it) } }
0
Kotlin
0
0
7934315a1b86b4b84a633761e6a842121e9c174f
7,098
rune-kt
Apache License 2.0
app/src/main/java/com/example/bank_branch_details/mvp/view/TouchPointListView.kt
SawThanDar18
192,281,355
false
null
package com.example.bank_branch_details.mvp.view import com.example.bank_branch_details.network.response.TouchPointListResponse interface TouchPointListView { fun showPrompt(message : String) fun showLoading() fun dismissLoading() fun showTouchPointList(touchPointListResponse: TouchPointListResponse) }
0
Kotlin
0
0
37f7c03ded5f5cdf62a77cebc4b5963d0381de56
322
Bank_Branch_Details
Apache License 2.0
code/android/app/src/main/java/isel/ps/classcode/domain/deserialization/ClassCodeLeaveClassroomRequestDeserialization.kt
i-on-project
607,828,295
false
null
package isel.ps.classcode.domain.deserialization import com.fasterxml.jackson.annotation.JsonProperty /** * Class used to deserialize the request to leave a classroom response from the database */ data class ClassCodeLeaveClassroomRequestDeserialization( @JsonProperty("leaveClassroom") val leaveClassroom: ClassCodeLeaveClassroomDeserialization, @JsonProperty("leaveTeamRequests") val leaveTeamRequests: List<ClassCodeLeaveTeamWithRepoNameDeserialization>, )
2
Kotlin
0
2
3daeed28d8a2ce9cb90ec642698b9ecb2eb9fe0d
472
repohouse
Apache License 2.0
core/src/jvmTest/kotlin/se/gustavkarlsson/conveyor/internal/ActionIssuerImplTest.kt
gustavkarlsson
291,828,391
false
null
package se.gustavkarlsson.conveyor.internal import kotlinx.coroutines.CancellationException import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeout import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import se.gustavkarlsson.conveyor.testing.NullAction import se.gustavkarlsson.conveyor.testing.runBlockingTest import strikt.api.expectThat import strikt.api.expectThrows import strikt.assertions.isEqualTo import strikt.assertions.message object ActionIssuerImplTest : Spek({ val action = NullAction<Int>() describe("A ActionIssuerImpl") { val subject by memoized { ActionIssuerImpl<Int>() } it("issuedActions suspends waiting for first item") { expectSuspends { subject.issuedActions.first() } } it("issuedActions emits action issued after subscribing") { val result = runBlockingTest { val deferred = async { subject.issuedActions.first() } subject.issue(action) deferred.await() } expectThat(result).isEqualTo(action) } it("issuedActions emits action issued before subscribing") { val result = runBlockingTest { subject.issue(action) subject.issuedActions.first() } expectThat(result).isEqualTo(action) } describe("that was cancelled") { val cancellationMessage = "Purposefully cancelled" val exception = CancellationException(cancellationMessage) beforeEachTest { subject.cancel(exception) } it("issuedActions emits error") { expectThrows<CancellationException> { subject.issuedActions.first() }.message.isEqualTo(cancellationMessage) } it("throws exception when action is issued") { expectThrows<CancellationException> { subject.issue(action) }.message.isEqualTo(cancellationMessage) } it("can be cancelled again") { subject.cancel(Throwable()) } } } }) private fun expectSuspends(block: suspend () -> Unit) { expectThrows<TimeoutCancellationException> { withTimeout(100) { block() } } }
0
Kotlin
1
5
cc05b69c7eb259c999b158e8d0e095183674b1da
2,518
conveyor
MIT License
src/test/kotlin/g0801_0900/s0802_find_eventual_safe_states/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0802_find_eventual_safe_states import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun eventualSafeNodes() { assertThat( Solution() .eventualSafeNodes( arrayOf( intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(5), intArrayOf(0), intArrayOf(5), intArrayOf(), intArrayOf() ) ), equalTo(listOf(2, 4, 5, 6)) ) } @Test fun eventualSafeNodes2() { assertThat( Solution() .eventualSafeNodes( arrayOf( intArrayOf(1, 2, 3, 4), intArrayOf(1, 2), intArrayOf(3, 4), intArrayOf(0, 4), intArrayOf() ) ), equalTo(listOf(4)) ) } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
1,175
LeetCode-in-Kotlin
MIT License
app/src/main/java/com/wagarcdev/der/presentation/screens/screen_login/google_one_tap_sign_in/GoogleOneTapSignIn.kt
wagarcdev
546,044,448
false
null
package com.wagarcdev.der.presentation.screens.screen_login.google_one_tap_sign_in import android.app.Activity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.platform.LocalContext import com.google.android.gms.auth.api.identity.BeginSignInRequest import com.google.android.gms.auth.api.identity.Identity import com.google.android.gms.common.api.ApiException import com.google.android.gms.common.api.CommonStatusCodes import com.wagarcdev.der.domain.model.User // based on https://github.com/stevdza-san/OneTapCompose @Composable fun GoogleOneTapSignIn( state: OneTapSignInState, clientId: String, onUserReceived: (User) -> Unit, onDialogDismissed: (String) -> Unit ) { // todo maybe find a better way to improve this val activity = LocalContext.current as Activity val activityResultLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartIntentSenderForResult() ) { result -> try { when (result.resultCode) { Activity.RESULT_OK -> { val oneTapClient = Identity.getSignInClient(activity) val credentials = oneTapClient.getSignInCredentialFromIntent(result.data) val user = User( name = credentials.displayName ?: "Google User", email = credentials.id, password = credentials.password ?: "" ) onUserReceived(user) state.close() } else -> { onDialogDismissed("Dialog closed") state.close() } } } catch (exception: ApiException) { exception.printStackTrace() when (exception.statusCode) { CommonStatusCodes.CANCELED -> { onDialogDismissed("Dialog canceled") state.close() } CommonStatusCodes.NETWORK_ERROR -> { onDialogDismissed("Network error") state.close() } else -> { onDialogDismissed("Something went wrong") state.close() } } } } LaunchedEffect(key1 = state.opened) { if (state.opened) { signIn( activity = activity, clientId = clientId, launchActivityResult = { intentSenderRequest -> activityResultLauncher.launch(intentSenderRequest) }, onError = { messageError -> onDialogDismissed(messageError) state.close() } ) } } } private fun signIn( activity: Activity, clientId: String, launchActivityResult: (IntentSenderRequest) -> Unit, onError: (String) -> Unit ) { val signInClient = Identity.getSignInClient(activity) val idTokenRequestOptions = BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) .setFilterByAuthorizedAccounts(true) .setServerClientId(clientId) .build() val passwordRequestOptions = BeginSignInRequest.PasswordRequestOptions.builder() .setSupported(true) .build() val signInRequest = BeginSignInRequest.builder() .setPasswordRequestOptions(passwordRequestOptions) .setGoogleIdTokenRequestOptions(idTokenRequestOptions) .setAutoSelectEnabled(true) .build() signInClient.beginSignIn(signInRequest) .addOnSuccessListener { result -> try { launchActivityResult( IntentSenderRequest.Builder( result.pendingIntent.intentSender ).build() ) } catch (exception: Exception) { exception.printStackTrace() onError("Something went wrong") } } .addOnFailureListener { signUp( activity = activity, clientId = clientId, launchActivityResult = launchActivityResult, onError = onError ) } } private fun signUp( activity: Activity, clientId: String, launchActivityResult: (IntentSenderRequest) -> Unit, onError: (String) -> Unit ) { val signInClient = Identity.getSignInClient(activity) val passwordRequestOptions = BeginSignInRequest.PasswordRequestOptions.builder() .setSupported(true) .build() val idTokenRequestOptions = BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) .setFilterByAuthorizedAccounts(false) .setServerClientId(clientId) .build() val signInRequest = BeginSignInRequest.builder() .setPasswordRequestOptions(passwordRequestOptions) .setGoogleIdTokenRequestOptions(idTokenRequestOptions) .build() signInClient.beginSignIn(signInRequest) .addOnSuccessListener { result -> try { launchActivityResult( IntentSenderRequest.Builder( result.pendingIntent.intentSender ).build() ) } catch (exception: Exception) { exception.printStackTrace() onError("Something went wrong") } } .addOnFailureListener { it.printStackTrace() onError("Something went wrong") } }
0
Kotlin
0
0
2578dde2f1bb801b2fd04f49964878ac4159dc25
5,899
DER
MIT License
matrix-sdk-android/src/test/java/org/matrix/android/sdk/internal/network/ComputeUserAgentUseCaseTest.kt
tchapgouv
340,329,238
false
null
/* * Copyright 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sdn.android.sdk.internal.network import android.content.Context import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build import io.mockk.every import io.mockk.mockk import org.amshove.kluent.shouldBeEqualTo import org.junit.Before import org.junit.Test import org.sdn.android.sdk.BuildConfig import org.sdn.android.sdk.api.util.getApplicationInfoCompat import org.sdn.android.sdk.api.util.getPackageInfoCompat import java.lang.Exception private const val A_PACKAGE_NAME = "org.matrix.sdk" private const val AN_APP_NAME = "Element" private const val A_NON_ASCII_APP_NAME = "Élement" private const val AN_APP_VERSION = "1.5.1" private const val A_FLAVOUR = "GooglePlay" class ComputeUserAgentUseCaseTest { private val context = mockk<Context>() private val packageManager = mockk<PackageManager>() private val applicationInfo = mockk<ApplicationInfo>() private val packageInfo = mockk<PackageInfo>() private val computeUserAgentUseCase = ComputeUserAgentUseCase(context) @Before fun setUp() { every { context.applicationContext } returns context every { context.packageName } returns A_PACKAGE_NAME every { context.packageManager } returns packageManager every { packageManager.getApplicationInfoCompat(any(), any()) } returns applicationInfo every { packageManager.getPackageInfoCompat(any(), any()) } returns packageInfo } @Test fun `given a non-null app name and app version when computing user agent then returns expected user agent`() { // Given givenAppName(AN_APP_NAME) givenAppVersion(AN_APP_VERSION) // When val result = computeUserAgentUseCase.execute(A_FLAVOUR) // Then val expectedUserAgent = constructExpectedUserAgent(AN_APP_NAME, AN_APP_VERSION) result shouldBeEqualTo expectedUserAgent } @Test fun `given a null app name when computing user agent then returns user agent with package name instead of app name`() { // Given givenAppName(null) givenAppVersion(AN_APP_VERSION) // When val result = computeUserAgentUseCase.execute(A_FLAVOUR) // Then val expectedUserAgent = constructExpectedUserAgent(A_PACKAGE_NAME, AN_APP_VERSION) result shouldBeEqualTo expectedUserAgent } @Test fun `given a non-ascii app name when computing user agent then returns user agent with package name instead of app name`() { // Given givenAppName(A_NON_ASCII_APP_NAME) givenAppVersion(AN_APP_VERSION) // When val result = computeUserAgentUseCase.execute(A_FLAVOUR) // Then val expectedUserAgent = constructExpectedUserAgent(A_PACKAGE_NAME, AN_APP_VERSION) result shouldBeEqualTo expectedUserAgent } @Test fun `given a null app version when computing user agent then returns user agent with a fallback app version`() { // Given givenAppName(AN_APP_NAME) givenAppVersion(null) // When val result = computeUserAgentUseCase.execute(A_FLAVOUR) // Then val expectedUserAgent = constructExpectedUserAgent(AN_APP_NAME, ComputeUserAgentUseCase.FALLBACK_APP_VERSION) result shouldBeEqualTo expectedUserAgent } private fun constructExpectedUserAgent(appName: String, appVersion: String): String { return buildString { append(appName) append("/") append(appVersion) append(" (") append(Build.MANUFACTURER) append(" ") append(Build.MODEL) append("; ") append("Android ") append(Build.VERSION.RELEASE) append("; ") append(Build.DISPLAY) append("; ") append("Flavour ") append(A_FLAVOUR) append("; ") append("MatrixAndroidSdk2 ") append(BuildConfig.SDK_VERSION) append(")") } } private fun givenAppName(deviceName: String?) { if (deviceName == null) { every { packageManager.getApplicationLabel(any()) } throws Exception("Cannot retrieve application name") } else if (!deviceName.matches("\\A\\p{ASCII}*\\z".toRegex())) { every { packageManager.getApplicationLabel(any()) } returns A_PACKAGE_NAME } else { every { packageManager.getApplicationLabel(any()) } returns deviceName } } private fun givenAppVersion(appVersion: String?) { packageInfo.versionName = appVersion } }
4
null
4
9
9bd50a49e0a5a2a17195507ef3fe96594ddd739e
5,308
tchap-android
Apache License 2.0
android/library-magiccube/src/main/java/com/hellobike/magiccube/loader/insert/IWKInsert.kt
hellof2e
651,011,094
false
{"Kotlin": 499995, "Objective-C": 421129, "JavaScript": 39299, "Java": 29943, "Swift": 24514, "Ruby": 5345, "TypeScript": 3969, "Shell": 255}
package com.hellobike.magiccube.loader.insert interface IWKInsert { /** * 设置插屏弹窗操作的监听 * @param listener 结果监听 [IWKInsertDialogListener] */ fun setOnInsertDialogListener(listener: IWKInsertDialogListener) /** * 开始弹出 */ fun process() /** * 弹窗是否正在展示 */ fun isShowing(): Boolean /** * 关闭,默认位非用户的点击行为导致的关闭 */ fun dismiss() /** * 关闭 * @param byUser 是否是用户的点击交互导致的关闭行为 */ fun dismiss(byUser: Boolean) }
3
Kotlin
9
60
8123fdaafa9ee7eaeee43fb73789b7fa3feac697
499
Wukong
Apache License 2.0
Compose-Bookshelf-App/app/src/main/java/com/example/bookshelfapp/BookshelfApplication.kt
Jaehwa-Noh
741,263,017
false
{"Kotlin": 34421}
package com.example.bookshelfapp import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class BookshelfApplication: Application()
0
Kotlin
0
0
859aa0e8bfc7b0f4297a35d92c26b9cc95a4318f
165
Project-Bookshelf-App
Apache License 2.0
app/src/main/java/com/myth/ticketmasterapp/domain/usecases/GetEventUseCase.kt
MichaelGift
634,539,469
false
{"Kotlin": 93804}
package com.myth.ticketmasterapp.domain.usecases import androidx.lifecycle.LiveData import com.myth.ticketmasterapp.data.eventdatamodels.Event import com.myth.ticketmasterapp.domain.repository.EventRepository class GetEventUseCase(private var eventRepository: EventRepository) { suspend fun execute( keyword: String, distance: String, category: String, location: String ): List<Event>? = eventRepository.getEvent(keyword, distance, category, location) suspend fun getEventsFromDB(): List<Event>? = eventRepository.getEventsFromDB() suspend fun getEventById(eventId: String): List<Event>? = eventRepository.getEventById(eventId) }
0
Kotlin
0
0
1953763bed1923fa6d1203466885b5240038b1f5
689
Event-Finder-App
MIT License
android/src/main/kotlin/com/oztechan/ccc/android/util/ViewExtensions.kt
CurrencyConverterCalculator
102,633,334
false
null
/* * Copyright (c) 2021 <NAME>. All rights reserved. */ @file:Suppress("TooManyFunctions") package com.oztechan.ccc.android.util import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.view.View import android.view.animation.Animation import android.view.animation.Transformation import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import co.touchlab.kermit.Logger import com.github.submob.logmob.w import com.github.submob.scopemob.castTo import com.github.submob.scopemob.whether import com.oztechan.ccc.ad.AdManager import com.oztechan.ccc.client.model.RateState import com.oztechan.ccc.resources.toImageFileName import mustafaozhan.github.com.mycurrencies.R import java.io.FileNotFoundException private const val ANIMATION_DURATION = 500L fun View.hideKeyboard() = context?.getSystemService(Context.INPUT_METHOD_SERVICE) ?.castTo<InputMethodManager>() ?.hideSoftInputFromWindow(windowToken, 0) fun FrameLayout.setBannerAd( adManager: AdManager, adId: String, shouldShowAd: Boolean ) = if (shouldShowAd) { removeAllViews() addView( adManager.getBannerAd(context, width, adId) { height -> if (height != null) animateHeight(0, height) visible() } ) } else { gone() } fun View.animateHeight(startHeight: Int, endHeight: Int) { layoutParams.height = 0 val delta = endHeight - startHeight var newHeight: Int val animation = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { newHeight = (startHeight + delta * interpolatedTime).toInt() layoutParams.height = newHeight requestLayout() } } animation.duration = ANIMATION_DURATION startAnimation(animation) } fun <T> Fragment.getNavigationResult( key: String ) = findNavController() .currentBackStackEntry ?.savedStateHandle ?.getLiveData<T>(key) // todo here needs to be changed @SuppressLint("RestrictedApi") fun <T> Fragment.setNavigationResult( destinationId: Int, result: T, key: String ) = findNavController() .currentBackStackEntry ?.whether { it.destination.id == destinationId } ?.savedStateHandle?.set(key, result) fun View?.visibleIf(visible: Boolean) = if (visible) visible() else gone() fun View.showLoading(visible: Boolean) = if (visible) { visible() bringToFront() } else gone() fun View?.visible() { this?.visibility = View.VISIBLE } fun View?.gone() { this?.visibility = View.GONE } fun TextView.dataState(state: RateState) = when (state) { is RateState.Online -> { text = context.getString(R.string.text_online_last_updated, state.lastUpdate) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_online, 0, 0, 0) visible() } is RateState.Cached -> { text = context.getString(R.string.text_cached_last_updated, state.lastUpdate) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_cached, 0, 0, 0) visible() } is RateState.Offline -> { text = if (state.lastUpdate.isNullOrEmpty()) { context.getString(R.string.text_offline) } else { context.getString(R.string.text_offline_last_updated, state.lastUpdate) } setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_offine, 0, 0, 0) visible() } RateState.Error -> { text = context.getString(R.string.text_no_data) setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_error, 0, 0, 0) visible() } RateState.None -> gone() } private const val CLIPBOARD_LABEL = "clipboard_label" fun View.copyToClipBoard(text: String) { val clipboard = ContextCompat.getSystemService(context, ClipboardManager::class.java) val clip = ClipData.newPlainText(CLIPBOARD_LABEL, text) clipboard?.setPrimaryClip(clip)?.let { showSnack(context.getString(R.string.copied_to_clipboard)) } } fun ImageView.setBackgroundByName( name: String ) = setImageResource(context.getImageResourceByName(name)) fun Context.getImageResourceByName(name: String): Int = try { resources.getIdentifier( name.toImageFileName(), "drawable", packageName ) } catch (e: FileNotFoundException) { Logger.w(e) R.drawable.unknown }
25
null
22
193
375828be4dcca3c99d0b0d084fa125cff1ad9895
4,644
CCC
Apache License 2.0
build-logic/convention/src/main/java/io/photopixels/buildlogic/plugins/AndroidApplicationSigningConventionPlugin.kt
scalefocus
800,965,364
false
{"Kotlin": 323708, "Shell": 1723}
import com.android.build.api.dsl.ApplicationExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure import java.util.Properties class AndroidApplicationSigningConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { val keystorePropsFile = rootProject.file("keystore.properties") val validSigningConfig = keystorePropsFile.exists() val keystoreProps = Properties().apply { if (validSigningConfig) { load(keystorePropsFile.inputStream()) } else { println("Keystore file doesn't exist in [${keystorePropsFile.absolutePath}].") } } val keystorePath: String by keystoreProps val keystorePassword: String by keystoreProps val keyAlias: String by keystoreProps val keyPassword: String by keystoreProps extensions.configure<ApplicationExtension> { signingConfigs { if (validSigningConfig) { create("release") { this.storeFile = file(keystorePath) this.storePassword = <PASSWORD> this.keyAlias = keyAlias this.keyPassword = <PASSWORD> } } } buildTypes { release { if (validSigningConfig) { signingConfig = signingConfigs.getByName("release") } } debug { if (validSigningConfig) { signingConfig = signingConfigs.getByName("release") } } getByName("releaseHttp") { if (validSigningConfig) { signingConfig = signingConfigs.getByName("release") } } } } } } }
1
Kotlin
0
1
09ee2b7ee0bfdf0f5621c9b5b1f818eebc891c96
2,182
photopixels-android
Apache License 2.0
idea/testData/android/lintQuickfix/suppressLint/methodParameter.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
// INTENTION_TEXT: Suppress: Add @SuppressLint("SdCardPath") annotation // INSPECTION_CLASS: org.jetbrains.android.inspections.klint.AndroidLintInspectionToolProvider$AndroidKLintSdCardPathInspection fun foo(path: String = "<caret>/sdcard") = path
0
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
248
kotlin
Apache License 2.0
core/src/main/java/at/specure/data/dao/TestResultGraphItemDao.kt
rtr-nettest
195,193,208
false
{"Kotlin": 1584817, "Java": 669959, "HTML": 43778, "Shell": 4061}
package at.specure.data.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import at.specure.data.Tables import at.specure.data.entity.TestResultGraphItemRecord import timber.log.Timber @Dao abstract class TestResultGraphItemDao { @Query("SELECT * from ${Tables.TEST_RESULT_GRAPH_ITEM} WHERE testUUID == :testUUID AND type == :typeValue GROUP BY time ORDER BY time ASC ") abstract fun getGraphDataLiveData(testUUID: String, typeValue: Int): LiveData<List<TestResultGraphItemRecord>> @Query("DELETE FROM ${Tables.TEST_RESULT_GRAPH_ITEM} WHERE (testUUID == :testOpenUUID AND type == :typeValue)") abstract fun removeGraphItem(testOpenUUID: String, typeValue: Int): Int @Transaction open fun clearInsertItems(graphItems: List<TestResultGraphItemRecord>?) { if (!graphItems.isNullOrEmpty()) { val removedCount = removeGraphItem(graphItems.first().testUUID, graphItems.first().type.typeValue) Timber.d("DB: clearing graph items: $removedCount for uuid: ${graphItems.first().testUUID}, type: ${graphItems.first().type.typeValue}") val inserted = insertItem(graphItems) Timber.d("DB: inserted graph items: $inserted for uuid: ${graphItems.first().testUUID}, type: ${graphItems.first().type.typeValue}") } } @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertItem(graphItem: List<TestResultGraphItemRecord>) @Query("DELETE FROM ${Tables.TEST_RESULT_GRAPH_ITEM}") abstract fun deleteAll(): Int }
1
Kotlin
12
28
4b0754a8bdbf1203ecc5961f642105ec131a9536
1,661
open-rmbt-android
Apache License 2.0
basick/src/main/java/com/mozhimen/basick/elemk/java/util/cons/CDateFormat.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.elemk.java.util.cons import java.text.DateFormat /** * @ClassName CDateFormat * @Description TODO * @Author Mozhimen & <NAME> * @Version 1.0 */ object CDateFormat { object Format { const val yyyy_MM_dd_HH_mm_ss_SS = "yyyy-MM-dd HH:mm:ss:SS" const val yyyy_MM_dd_HH_mm_ss_S = "yyyy-MM-dd HH:mm:ss:S" const val yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss" const val yyyyMMddHHmmss = "yyyyMMddHHmmss" const val yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm" const val yyyy_MM_dd_HH = "yyyy-MM-dd HH" const val yyyy_MM_dd = "yyyy-MM-dd" const val yyyyMMdd = "yyyyMMdd" const val HH_mm_ss = "HH:mm:ss" const val HH_mm = "HH:mm" const val mm_ss = "mm:ss" const val yyyy = "yyyy" const val MM = "MM" const val dd = "dd" const val HH = "HH" const val mm = "mm" const val ss = "ss" } const val FULL = DateFormat.FULL const val LONG = DateFormat.LONG const val MEDIUM = DateFormat.MEDIUM const val SHORT = DateFormat.SHORT const val DEFAULT = DateFormat.DEFAULT }
1
null
15
118
3e9cda57ac87f84134e768cc3756411d5bbd143f
1,143
SwiftKit
Apache License 2.0
fr_yhe_pro/src/main/java/com/friendly_machines/fr_yhe_pro/command/WatchASetTomorrowWeatherCommand.kt
daym
744,679,396
false
{"Kotlin": 453101}
package com.friendly_machines.fr_yhe_pro.command import com.friendly_machines.fr_yhe_pro.WatchOperation import java.nio.ByteBuffer import java.nio.ByteOrder class WatchASetTomorrowWeatherCommand(str1: String, str2: String, str3: String, weatherCode: Short) : WatchCommand(WatchOperation.ASetTomorrowWeather, run { val str1Bytes = str1.toByteArray(Charsets.UTF_8) val str2Bytes = str2.toByteArray(Charsets.UTF_8) val str3Bytes = str3.toByteArray(Charsets.UTF_8) val buf = ByteBuffer.allocate(str1Bytes.size + str2Bytes.size + str3Bytes.size + 3 + 3 + 3 + 3 + 2).order(ByteOrder.LITTLE_ENDIAN) buf.put(2.toByte()) buf.putShort(str3Bytes.size.toShort()) buf.put(str3Bytes) buf.put(0.toByte()) buf.putShort(str1Bytes.size.toShort()) buf.put(str1Bytes) buf.put(1.toByte()) buf.putShort(str2Bytes.size.toShort()) buf.put(str2Bytes) buf.put(4.toByte()) buf.put(2.toByte()) buf.put(0.toByte()) buf.putShort(weatherCode) buf.array() })
0
Kotlin
1
1
d2bc5a833d755bef3bb8886c54fd09b539fb14c9
1,002
frbpdoctor
BSD 2-Clause FreeBSD License
src/main/kotlin/vec/infrastructure/repository/impl/TermsOfServiceRepositoryImpl.kt
tmyksj
374,243,992
false
null
package vec.infrastructure.repository.impl import org.springframework.data.r2dbc.repository.Query import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional import reactor.core.publisher.Mono import vec.domain.entity.TermsOfService import vec.domain.repository.TermsOfServiceRepository @Component @Transactional interface TermsOfServiceRepositoryImpl : TermsOfServiceRepository { @Query( value = """ select * from terms_of_service where applied_date <= now() order by applied_date desc """, ) override fun findCurrentVersion(): Mono<TermsOfService> }
13
Kotlin
0
1
751465126e6ee9b2c75989e9b437540009ac9a6b
684
vec
Apache License 2.0
Pokedex/app/src/main/java/com/example/pokedex/data/remote/responses/GenerationVi.kt
cpinan
378,021,028
false
null
package com.example.pokedex.data.remote.responses import com.google.gson.annotations.SerializedName data class GenerationVi( @SerializedName("omegaruby-alphasapphire") val omegaruby_alphasapphire: OmegarubyAlphasapphire, @SerializedName("x-y") val x_y: XY )
0
Kotlin
0
0
d00f7e91e6b313e151429e4dbce3517f263914fe
267
Pokedex
Apache License 2.0
sources/feature/settingsFragment/src/main/java/com/egoriku/settings/presentation/SettingsPagePresenter.kt
Malligan
170,515,620
true
{"Kotlin": 113759, "Java": 64743}
package com.egoriku.settings.presentation import com.egoriku.core.di.utils.IAnalytics import com.egoriku.ui.arch.pvm.BasePresenter import javax.inject.Inject internal class SettingsPagePresenter @Inject constructor(private val analytics: IAnalytics) : BasePresenter<SettingsPageContract.View>(), SettingsPageContract.Presenter { override fun loadLandingData() { } }
0
Kotlin
0
0
882c0953eb69a9a661f4bbbca8cf38a5f9ae2abe
383
Lady-happy
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Home.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bulk import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup public val BulkGroup.Home: ImageVector get() { if (_home != null) { return _home!! } _home = Builder(name = "Home", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.0693f, 2.8201f) lineTo(3.1393f, 8.3701f) curveTo(2.3593f, 8.9901f, 1.8593f, 10.3001f, 2.0293f, 11.2801f) lineTo(3.3593f, 19.2401f) curveTo(3.5993f, 20.6601f, 4.9593f, 21.8101f, 6.3993f, 21.8101f) horizontalLineTo(17.5993f) curveTo(19.0293f, 21.8101f, 20.3993f, 20.6501f, 20.6393f, 19.2401f) lineTo(21.9693f, 11.2801f) curveTo(22.1293f, 10.3001f, 21.6293f, 8.9901f, 20.8593f, 8.3701f) lineTo(13.9293f, 2.8301f) curveTo(12.8593f, 1.9701f, 11.1293f, 1.9701f, 10.0693f, 2.8201f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 15.5f) curveTo(13.3807f, 15.5f, 14.5f, 14.3807f, 14.5f, 13.0f) curveTo(14.5f, 11.6193f, 13.3807f, 10.5f, 12.0f, 10.5f) curveTo(10.6193f, 10.5f, 9.5f, 11.6193f, 9.5f, 13.0f) curveTo(9.5f, 14.3807f, 10.6193f, 15.5f, 12.0f, 15.5f) close() } } .build() return _home!! } private var _home: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
2,658
VuesaxIcons
MIT License
app/src/main/java/com/zipdabang/zipdabang_android/module/my/data/remote/recipeedit/complete/GetCompleteRecipeStep.kt
zipdabang
666,457,004
false
{"Kotlin": 2208314}
package com.zipdabang.zipdabang_android.module.my.data.remote.recipeedit.complete data class GetCompleteRecipeStep( val description: String, val image: String, val stepNum: Int )
8
Kotlin
1
2
ef22f7d73c2c44065714a6cffe783250b80487c8
191
android
The Unlicense
bibix-core/test/kotlin/com/giyeok/bibix/interpreter/expr/GetTypeDetailsTests.kt
Joonsoo
477,378,536
false
{"Kotlin": 905636, "Java": 29118, "TeX": 16376, "Scala": 3164}
package com.giyeok.bibix.interpreter.expr import com.giyeok.bibix.base.* import com.giyeok.bibix.interpreter.testInterpreter import com.giyeok.bibix.plugins.PluginInstanceProvider import com.giyeok.bibix.plugins.PreloadedPlugin import com.google.common.jimfs.Jimfs import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import kotlin.io.path.writeText class GetTypeDetailsTests { @Test fun test(): Unit = runBlocking { val fs = Jimfs.newFileSystem() val script = """ import abc aaa = abc.testRun() """.trimIndent() fs.getPath("/build.bbx").writeText(script) val abcPlugin = PreloadedPlugin.fromScript( "com.abc", """ import xyz class Class1(field1?: string, field2: Class2) class Class2(field3: string) def testRun(): string = native:com.giyeok.bibix.interpreter.expr.GetTypeDetailsPlugin """.trimIndent(), PluginInstanceProvider(GetTypeDetailsPlugin::class.java) ) val xyzPlugin = PreloadedPlugin.fromScript( "com.xyz", """ enum Enum11 { hello, world } class Class3(field4: string) super class Supers{Class3} """.trimIndent(), PluginInstanceProvider() ) val interpreter = testInterpreter(fs, "/", mapOf("abc" to abcPlugin, "xyz" to xyzPlugin)) assertThat(interpreter.userBuildRequest("aaa")).isEqualTo(StringValue("done")) assertThat(GetTypeDetailsPlugin.typeDetailsMap!!.canonicalNamed).containsExactly( TypeName("com.abc", "Class1"), DataClassTypeDetails( "com.abc", "Class1", listOf( RuleParam("field1", TypeValue.StringTypeValue, true), RuleParam("field2", TypeValue.DataClassTypeValue("com.abc", "Class2"), false) ) ) ) assertThat(GetTypeDetailsPlugin.typeDetailsMap!!.relativeNamed).containsExactly( "Class2", DataClassTypeDetails( "com.abc", "Class2", listOf(RuleParam("field3", TypeValue.StringTypeValue, false)) ), "xyz.Class3", DataClassTypeDetails( "com.xyz", "Class3", listOf(RuleParam("field4", TypeValue.StringTypeValue, false)) ), "xyz.Enum11", EnumTypeDetails( "com.xyz", "Enum11", listOf("hello", "world") ), "xyz.Supers", SuperClassTypeDetails( "com.xyz", "Supers", listOf("Class3") ) ) } } class GetTypeDetailsPlugin { companion object { @JvmStatic var typeDetailsMap: TypeDetailsMap? = null @JvmStatic fun called(typeDetailsMap: TypeDetailsMap) { GetTypeDetailsPlugin.typeDetailsMap = typeDetailsMap } } fun build(context: BuildContext): BuildRuleReturn { return BuildRuleReturn.getTypeDetails( listOf(TypeName("com.abc", "Class1")), listOf("Class2", "xyz.Class3", "xyz.Enum11", "xyz.Supers"), ) { typeDetails -> called(typeDetails) BuildRuleReturn.value(StringValue("done")) } } }
10
Kotlin
1
3
49c847166eaf16dc99bd52bf40d8417859a960b6
3,091
bibix
MIT License
app/src/main/java/de/lemke/oneurl/domain/model/VgdIsgd.kt
Lemkinator
699,106,627
false
{"Kotlin": 311924}
package de.lemke.oneurl.domain.model import android.content.Context import android.util.Log import com.android.volley.Request import com.android.volley.toolbox.JsonObjectRequest import de.lemke.oneurl.R import de.lemke.oneurl.domain.generateURL.GenerateURLError import de.lemke.oneurl.domain.urlEncodeAmpersand /* docs: https://v.gd/apishorteningreference.php https://is.gd/apishorteningreference.php example: https://v.gd/create.php?format=json&url=www.example.com&shorturl=example https://is.gd/create.php?format=json&url=www.example.com&shorturl=example */ val vgd = VgdIsgd.Vgd() val isgd = VgdIsgd.Isgd() sealed class VgdIsgd : ShortURLProvider { final override val group = "v.gd, is.gd" final override val aliasConfig = object : AliasConfig { override val minAliasLength = 5 override val maxAliasLength = 30 override val allowedAliasCharacters = "a-z, A-Z, 0-9, _" override fun isAliasValid(alias: String) = alias.matches(Regex("[a-zA-Z0-9_]+")) } override fun getAnalyticsURL(alias: String) = "$baseURL/stats.php?url=$alias" override fun sanitizeLongURL(url: String) = url.urlEncodeAmpersand().trim() fun getVgdIsgdCreateRequest( context: Context, longURL: String, alias: String, successCallback: (shortURL: String) -> Unit, errorCallback: (error: GenerateURLError) -> Unit ): JsonObjectRequest { val tag = "CreateRequest_$name" val url = apiURL + "?format=json&url=" + longURL + (if (alias.isBlank()) "" else "&shorturl=$alias&logstats=1") Log.d(tag, "start request: $url") return JsonObjectRequest( Request.Method.GET, url, null, { response -> Log.d(tag, "response: $response") if (response.has("errorcode")) { Log.e(tag, "errorcode: ${response.getString("errorcode")}") Log.e(tag, "errormessage: ${response.optString("errormessage")}") /* Error code 1 - there was a problem with the original long URL provided Please specify a URL to shorten. //should not happen, checked before Please enter a valid URL to shorten Sorry, the URL you entered is on our internal blacklist. It may have been used abusively in the past, or it may link to another URL redirection service. Error code 2 - there was a problem with the short URL provided (for custom short URLs) Short URLs must be at least 5 characters long //should not happen, checked before Short URLs may only contain the characters a-z, 0-9 and underscore //should not happen, checked before The shortened URL you picked already exists, please choose another. Error code 3 - our rate limit was exceeded (your app should wait before trying again) Error code 4 - any other error (includes potential problems with our service such as a maintenance period) */ when (response.getString("errorcode")) { "1" -> if (response.optString("errormessage").contains("blacklist", ignoreCase = true)) { errorCallback(GenerateURLError.BlacklistedURL(context)) } else { errorCallback(GenerateURLError.InvalidURL(context)) } "2" -> errorCallback(GenerateURLError.AliasAlreadyExists(context)) "3" -> errorCallback(GenerateURLError.RateLimitExceeded(context)) "4" -> errorCallback(GenerateURLError.ServiceTemporarilyUnavailable(context, this)) else -> errorCallback( GenerateURLError.Custom( context, 200, response.optString("errormessage") + " (${response.getString("errorcode")})" ) ) } return@JsonObjectRequest } if (!response.has("shorturl")) { Log.e(tag, "error, response does not contain shorturl, response: $response") errorCallback(GenerateURLError.Unknown(context, 200)) return@JsonObjectRequest } val shortURL = response.getString("shorturl").trim() Log.d(tag, "shortURL: $shortURL") successCallback(shortURL) }, { error -> try { Log.e(tag, "error: $error") val networkResponse = error.networkResponse val statusCode = networkResponse?.statusCode val data = networkResponse?.data?.toString(Charsets.UTF_8) Log.e(tag, "$statusCode: message: ${error.message} data: $data") when { statusCode == null -> errorCallback(GenerateURLError.Unknown(context)) data.isNullOrBlank() -> errorCallback(GenerateURLError.Unknown(context, statusCode)) error.message?.contains("JSONException", true) == true -> { //https://v.gd/create.php?format=json&url=example.com?test&shorturl=test21 -> Error, database insert failed //Update: Works fine now? Log.e(tag, "error.message == ${error.message} (probably error: database insert failed)") errorCallback(GenerateURLError.Custom(context, statusCode, context.getString(R.string.error_vgd_isgd))) } else -> errorCallback(GenerateURLError.Custom(context, statusCode, data)) } } catch (e: Exception) { Log.e(tag, "error: $e") e.printStackTrace() errorCallback(GenerateURLError.Unknown(context)) } } ) } class Vgd : VgdIsgd() { override val name = "v.gd" override val baseURL = "https://v.gd" override val apiURL = "$baseURL/create.php" override val privacyURL = "$baseURL/privacy.php" override val termsURL = "$baseURL/terms.php" override fun getTipsCardTitleAndInfo(context: Context) = Pair( context.getString(R.string.info), context.getString(R.string.redirect_hint_text) ) override fun getInfoContents(context: Context): List<ProviderInfo> = listOf( ProviderInfo( dev.oneuiproject.oneui.R.drawable.ic_oui_confirm_before_next_action, context.getString(R.string.redirect_hint), context.getString(R.string.redirect_hint_text) ), ProviderInfo( dev.oneuiproject.oneui.R.drawable.ic_oui_tool_outline, context.getString(R.string.alias), context.getString( R.string.alias_text, aliasConfig.minAliasLength, aliasConfig.maxAliasLength, aliasConfig.allowedAliasCharacters ) ), ProviderInfo( dev.oneuiproject.oneui.R.drawable.ic_oui_report, context.getString(R.string.analytics), context.getString(R.string.analytics_text) ) ) override fun getCreateRequest( context: Context, longURL: String, alias: String, successCallback: (shortURL: String) -> Unit, errorCallback: (error: GenerateURLError) -> Unit ): JsonObjectRequest = getVgdIsgdCreateRequest(context, longURL, alias, successCallback, errorCallback) } class Isgd : VgdIsgd() { override val name = "is.gd" override val baseURL = "https://is.gd" override val apiURL = "$baseURL/create.php" override val privacyURL = "$baseURL/privacy.php" override val termsURL = "$baseURL/terms.php" override fun getInfoContents(context: Context): List<ProviderInfo> = listOf( ProviderInfo( dev.oneuiproject.oneui.R.drawable.ic_oui_tool_outline, context.getString(R.string.alias), context.getString( R.string.alias_text, aliasConfig.minAliasLength, aliasConfig.maxAliasLength, aliasConfig.allowedAliasCharacters ) ), ProviderInfo( dev.oneuiproject.oneui.R.drawable.ic_oui_report, context.getString(R.string.analytics), context.getString(R.string.analytics_text) ) ) override fun getCreateRequest( context: Context, longURL: String, alias: String, successCallback: (shortURL: String) -> Unit, errorCallback: (error: GenerateURLError) -> Unit ): JsonObjectRequest = getVgdIsgdCreateRequest(context, longURL, alias, successCallback, errorCallback) } }
2
Kotlin
1
9
19abeedb4540a63f35196b6c0ddc12dcac2eee47
9,453
OneUrl
MIT License
rest/src/main/kotlin/builder/guild/ScheduledEventCreateBuilder.kt
kordlib
202,856,399
false
null
package dev.kord.rest.builder.guild import dev.kord.common.entity.GuildScheduledEventEntityMetadata import dev.kord.common.entity.ScheduledEntityType import dev.kord.common.entity.Snowflake import dev.kord.common.entity.StageInstancePrivacyLevel import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.OptionalSnowflake import dev.kord.common.entity.optional.delegate.delegate import dev.kord.rest.builder.RequestBuilder import dev.kord.rest.json.request.GuildScheduledEventCreateRequest import kotlinx.datetime.Instant class ScheduledEventCreateBuilder( val name: String, val privacyLevel: StageInstancePrivacyLevel, val scheduledStartTime: Instant, val entityType: ScheduledEntityType ) : RequestBuilder<GuildScheduledEventCreateRequest> { private var _channelId: OptionalSnowflake = OptionalSnowflake.Missing var channelId: Snowflake? by ::_channelId.delegate() private var _description: Optional<String> = Optional.Missing() var description: String? by ::_description.delegate() private var _entityMetadata: Optional<GuildScheduledEventEntityMetadata> = Optional.Missing() var entityMetadata: GuildScheduledEventEntityMetadata? by ::_entityMetadata.delegate() private var _scheduledEndTime: Optional<Instant> = Optional.Missing() var scheduledEndTime: Instant? by ::_scheduledEndTime.delegate() override fun toRequest(): GuildScheduledEventCreateRequest = GuildScheduledEventCreateRequest( _channelId, _entityMetadata, name, privacyLevel, scheduledStartTime, _scheduledEndTime, _description, entityType ) }
33
Kotlin
53
435
084f0260ef335a1e3b8919c9adda286473f063ec
1,668
kord
MIT License
app/src/main/java/com/example/randomjoke/MainActivity.kt
Yasamanne
709,086,506
false
{"Kotlin": 5403}
package com.example.randomjoke import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.codepath.asynchttpclient.AsyncHttpClient import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler import okhttp3.Headers import org.json.JSONObject fun JSONObject.contains(key: String): Boolean { return this.has(key) } class MainActivity : AppCompatActivity() { var jokeTextURL = "" private lateinit var recyclerViewJokes: RecyclerView var jokesList = mutableListOf<String>() //list of photo URLs override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerViewJokes = findViewById<RecyclerView>(R.id.jokes_recycler_view) getJoke(15) } private fun getJoke(count: Int) { val client = AsyncHttpClient() for (i in 1..count) { client["https://v2.jokeapi.dev/joke/Any?blacklistFlags=religious,political", object : JsonHttpResponseHandler() { override fun onSuccess( statusCode: Int, headers: Headers, json: JsonHttpResponseHandler.JSON ) { val jokeTextObject = json.jsonObject if (jokeTextObject.contains("joke")) { jokeTextURL = jokeTextObject.getString("joke") } else { val jokeTextSetup = jokeTextObject.getString("setup") val jokeTextDelivery = jokeTextObject.getString("delivery") jokeTextURL = jokeTextSetup + "\n\n\n\n" + jokeTextDelivery } jokesList.add(jokeTextURL) Log.d("sib", jokeTextURL) if (jokesList.size == count) { // All jokes have been fetched, update the UI val adapter = JokeAdapter(jokesList) recyclerViewJokes.adapter = adapter recyclerViewJokes.layoutManager = LinearLayoutManager(this@MainActivity) recyclerViewJokes.addItemDecoration( DividerItemDecoration( this@MainActivity, LinearLayoutManager.VERTICAL ) ) } Log.d("Joke", "response successful") } override fun onFailure( statusCode: Int, headers: Headers?, errorResponse: String, throwable: Throwable? ) { Log.d("Joke Error", errorResponse) } }] } } }
0
Kotlin
0
0
2d69b03551ed12bb89583857d9cfab1b72676296
3,053
and101-random-joke2
Apache License 2.0
app/src/main/kotlin/com/github/shchurov/gitterclient/utils/PagingScrollListener.kt
tantai96nd
96,689,551
false
null
package com.github.shchurov.gitterclient.utils import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView abstract class PagingScrollListener(private val offscreenItemsThreshold: Int) : RecyclerView.OnScrollListener() { private var layoutManager: LinearLayoutManager? = null var enabled: Boolean = true protected abstract fun onLoadMoreItems() override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (!enabled) return initLayoutManagerIfRequired(recyclerView) if (isThresholdPassed()) { enabled = false onLoadMoreItems() } } private fun initLayoutManagerIfRequired(recyclerView: RecyclerView) { if (layoutManager == null) { layoutManager = recyclerView.layoutManager as LinearLayoutManager } } private fun isThresholdPassed(): Boolean { val lastVisible = layoutManager!!.findLastVisibleItemPosition() val totalCount = layoutManager!!.itemCount return totalCount <= lastVisible + offscreenItemsThreshold } }
0
Kotlin
0
1
4e65f404124986f9606bdab2b7040903085604a4
1,129
gitter-kotlin-client
Apache License 2.0
app/src/main/java/com/helloappscrmfsm/features/nearbyshops/presentation/ShopModifiedListResponse.kt
DebashisINT
744,363,248
false
{"Kotlin": 14015110, "Java": 1003163}
package com.helloappscrmfsm.features.nearbyshops.presentation import com.helloappscrmfsm.features.nearbyshops.model.ShopData data class ShopModifiedListResponse (var status:String,var modified_shop_list:ArrayList<ShopData> = ArrayList()) data class ShopModifiedUpdateList (var user_id:String="",var shop_modified_list:ArrayList<ShopIdModified> = ArrayList()) data class ShopIdModified(var shop_id:String)
0
Kotlin
0
0
63ccd9d6d67e2d4ee5afad9d7836396e32b2f953
409
HelloAppsCRM
Apache License 2.0
feature-account-api/src/main/java/io/novafoundation/nova/feature_account_api/presenatation/mixin/selectWallet/SelectedWalletModel.kt
novasamatech
415,834,480
false
{"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_account_api.presenatation.mixin.selectWallet import android.graphics.drawable.Drawable class SelectedWalletModel( val title: String, val subtitle: String, val icon: Drawable, val selectionAllowed: Boolean )
14
Kotlin
30
50
166755d1c3388a7afd9b592402489ea5ca26fdb8
264
nova-wallet-android
Apache License 2.0
app/src/main/java/co/specialforce/data/request/ExerciseInputRequest.kt
osamhack2020
303,081,543
false
null
package co.specialforce.data.request data class ExerciseInputRequest (val exercise_id: Int, val exercise_weight : Int, val exercise_count: Int, val exercise_time : Int)
0
Kotlin
0
4
683b8da58882a78fa583bdda276b906f9e4612c4
202
App_SpecialForces_SpecialWarrior
Apache License 2.0
plugins/server/org.postgresql/postgres/2.2/install.kt
ktorio
729,497,149
false
{"Kotlin": 134762, "HTML": 329, "FreeMarker": 139}
import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import java.sql.* import kotlinx.coroutines.* public fun Application.configureDatabases() { }
4
Kotlin
4
21
875656d68fb605033ef91cc34948cfb2da60a94d
223
ktor-plugin-registry
Apache License 2.0
ee-timeline/src/main/kotlin/ee/timeline/person/PersonUtils.kt
eugeis
80,671,654
false
null
package ee.timeline.person import ee.common.ext.ifElse import ee.common.ext.joinSurroundIfNotEmptyToString import ee.common.ext.then import ee.common.ext.toUrlKey import ee.timeline.* import java.util.* private val cal = Calendar.getInstance() fun Int.toYearStartDate(): Date { cal.set(this, 0, 1) return cal.time } fun Int.toYearEndDate(): Date { cal.set(this, 11, 31) return cal.time } val phaseBackground = Background() val authorBackground = Background() fun Phase.toTimeEvents(): TimeEvents { val ret = TimeEvents(title = TimeEvent(text = Text(headline = name.name, text = """ <div class="intro"> <div> <p><i>Kreative Facharbeit für den Kurs <a href="http://www.lza.de/kurse/gm/gm-1-b-zeitzonen-zeitzeugen-zeitgeist-2017" target="_blank"> ZEITZONEN, ZEITZEUGEN, ZEITGEIST (GM 1-B)</a>. Eugen Eisler</i></p> <ul> <li>Dozent: Dr. Wolfgang Schnabel</li> <li>Fach: Geschichte & Methoden</li> <li>Kurs: Zeitzonen, Zeitzeugen, Zeitgeist –Theologie und Entwicklung der Praktischen Theologie (GM 1)</li> </ul> <br> <p>In dieser interaktiven Zeittafel sind die wesentlichen Strömungen der christlichen Theologie und deren wichtigsten Vertreter in deutschsprachigen Raum zusammengefasst.<br></p> <p><i>Hinweis: Die untere Zeitleiste lässt sich auf der horizontalen Achse bewegen und somit zu dem gewünschten Zeitraum navigieren. Über die '+' und '-' Schaltflächen auf der Linke Seite lässt sich der Zeitraster vergrössern bzw. verkleinern.</i></p> </div> </div> """))) phases[0].fillTimeEvents(ret) phases[1].fillTimeEvents(ret) return ret } fun Phase.sortByDates(): Phase { phases.sortBy { it.period.start } authors.sortBy { it.birth.date } phases.forEach { it.sortByDates() } return this } fun Phase.fillTimeEvents(timeEvents: TimeEvents, parent: Phase? = null): TimeEvents { val group = parent?.name?.name ?: "" val groupAuthors = when (group) { "Liberale" -> "Spekulationstheologen" "bibeltreue" -> "Offenbarungstheologen" else -> { "$group Vertreter" } } authors.forEach { author -> val fullName = author.fullName() val photo = author.fotoLink.isNotBlank().then { """<img class="im" src="${author.fotoLink}" height="160px"/>""" } val quotes = author.quotes.isNotEmpty().then { """<q class="q">${author.quotes.first()}</q>""" } timeEvents.events.add(TimeEvent(id = fullName.toUrlKey(), start = author.birth.date, end = author.death.date, group = groupAuthors, markerBackground = background(color), media = Media(author.name.link), text = Text( headline = author.name.link.isNotBlank().ifElse( { """<a href="${author.name.link}" target="_blank">$fullName</a>""" }, { "${author.name.firstName} ${author.name.lastName}" }), text = """ <div class="ph"> <a href="#event-${name.name.toUrlKey()}" onclick="timeline.goToId('${name.name.toUrlKey()}');">${name.name}</a> </div>$photo$quotes"""))) } phases.forEach { phase -> val group = name.name val groupSchulen = "$group Schulen" val authors = phase.authors.map { author -> val fullName = author.fullName() """<a href="#event-${fullName.toUrlKey()}" onclick="timeline.goToId('${fullName.toUrlKey()}');">$fullName</a>""" }.joinSurroundIfNotEmptyToString(prefix = """<br><p>Vertreter:</p><ul class="author">""", postfix = "</ul>", separator = "\n ") { "<li>$it</li>" } val description = phase.description.split('\n') .joinToString(prefix = "<p>Charakteristika:</p>\n<ul>", postfix = "</ul>", separator = "\n ") { "<li>$it</li>" } timeEvents.events.add(TimeEvent(id = phase.name.name.toUrlKey(), start = phase.period.start.toYearStartDate(), end = phase.period.end.toYearEndDate(), group = groupSchulen, markerBackground = background(phase.color), text = Text(headline = phase.name.link.isNotBlank().ifElse( { """<a href="${phase.name.link}" target="_blank">${phase.name.name}</a>""" }, { "${phase.name.name}" }), text = "$description$authors"), media = phase.name.link.startsWith("https://de.wikipedia.").ifElse({ Media(phase.name.link) }, { Media.EMPTY }))) phase.fillTimeEvents(timeEvents, this) } return timeEvents } private fun background(color: String) = Background(color = color) fun Author.fullName() = name.firstName.isBlank().ifElse({ name.lastName }, { "${name.firstName} ${name.lastName}" })
0
Kotlin
0
0
29998a205ff566569bd493981f57c142e474251c
4,853
ee-timeline
Apache License 2.0
app/src/main/java/com/theapplication/expensetracker/MainActivity.kt
SatyamkrJha85
782,367,309
false
{"Kotlin": 39821}
package com.theapplication.expensetracker import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.theapplication.expensetracker.Navigation.NavGraph import com.theapplication.expensetracker.Screens.AddExpense import com.theapplication.expensetracker.Screens.HomeScreen import com.theapplication.expensetracker.ui.theme.ExpenseTrackerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ExpenseTrackerTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { NavGraph() } } } } }
0
Kotlin
0
0
623ce3e984e13b03f1225f0153536a5c9dfa419c
1,245
Expense_Tracker
MIT License
app/src/main/java/com/tinaciousdesign/aboutapps/utils/DateUtils.kt
tinacious
857,833,882
false
{"Kotlin": 58486}
package com.tinaciousdesign.aboutapps.utils import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter fun formattedDateFromMillis( timestamp: Long, pattern: String = "MMM d, yyyy 'at' h:mm a", ): String { val instant = Instant.ofEpochMilli(timestamp) val zoneId = ZoneId.systemDefault() val zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId) val formatter = DateTimeFormatter.ofPattern(pattern) return formatter.format(zonedDateTime) }
1
Kotlin
0
0
c5f68cc4fe3308dec1b774780806e0693ebe478e
536
about-apps-android
MIT License
paris-processor/src/main/java/com/airbnb/paris/processor/framework/SkyExtensions.kt
iamsibasish
131,112,725
true
{"Kotlin": 308241, "Java": 96900, "Ruby": 3135}
package com.airbnb.paris.processor.framework import com.squareup.javapoet.ClassName import javax.lang.model.element.* import javax.lang.model.type.TypeMirror internal val filer get() = SkyProcessor.INSTANCE.filer internal val messager get() = SkyProcessor.INSTANCE.messager internal val elements get() = SkyProcessor.INSTANCE.elements internal val types get() = SkyProcessor.INSTANCE.types internal val kaptOutputPath get() = SkyProcessor.INSTANCE.kaptOutputPath internal fun erasure(type: TypeMirror): TypeMirror = types.erasure(type) internal fun isSameType(type1: TypeMirror, type2: TypeMirror) = types.isSameType(type1, type2) internal fun isSubtype(type1: TypeMirror, type2: TypeMirror) = types.isSubtype(type1, type2) // ClassName internal fun ClassName.toTypeElement(): TypeElement = elements.getTypeElement(reflectionName()) internal fun ClassName.toTypeMirror(): TypeMirror = toTypeElement().asType() // Element internal fun Element.getPackageElement(): PackageElement = elements.getPackageOf(this) internal fun Element.isPrivate(): Boolean = this.modifiers.contains(Modifier.PRIVATE) internal fun Element.isNotPrivate(): Boolean = !isPrivate() internal fun Element.isProtected(): Boolean = this.modifiers.contains(Modifier.PROTECTED) internal fun Element.isNotProtected(): Boolean = !isProtected() internal fun Element.isStatic(): Boolean = Modifier.STATIC in modifiers internal fun Element.isNotStatic(): Boolean = !isStatic() internal fun Element.isFinal(): Boolean = Modifier.FINAL in modifiers internal fun Element.isNotFinal(): Boolean = !isFinal() internal fun Element.isField(): Boolean = kind == ElementKind.FIELD internal fun Element.isNotField(): Boolean = !isField() internal fun Element.isMethod(): Boolean = kind == ElementKind.METHOD internal fun Element.isNotMethod(): Boolean = !isMethod() internal fun Element.hasAnnotation(simpleName: String): Boolean { return this.annotationMirrors .map { it.annotationType.asElement().simpleName.toString() } .contains(simpleName) } internal fun Element.hasAnyAnnotation(simpleNames: Set<String>): Boolean { return this.annotationMirrors .map { it.annotationType.asElement().simpleName.toString() } .any { simpleNames.contains(it) } } // String internal fun String.className(): ClassName = ClassName.get(this.substringBeforeLast("."), this.substringAfterLast(".")) // TypeElement internal val TypeElement.className: ClassName get() = ClassName.get(this) internal val TypeElement.packageName: String get() = className.packageName() // TypeMirror internal fun TypeMirror.asTypeElement(): TypeElement = types.asElement(this) as TypeElement // Android specific internal fun isView(type: TypeMirror): Boolean = isSubtype(type, AndroidClassNames.VIEW.toTypeMirror())
0
Kotlin
0
0
e922c35e8043249bcd76328acf2b05699bc07bab
2,801
paris
Apache License 2.0
combustion-android-ble/src/main/java/inc/combustion/framework/service/FoodSafeStatus.kt
combustion-inc
463,664,807
false
{"Kotlin": 607897}
/* * Project: Combustion Inc. Android Framework * File: FoodSafeStatus.kt * Author: <NAME> <<EMAIL>> * * MIT License * * Copyright (c) 2023. Combustion Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package inc.combustion.framework.service import inc.combustion.framework.ble.shl import inc.combustion.framework.ble.shr import kotlin.random.Random import kotlin.random.nextUInt /** * See BLE spec definition here: https://github.com/combustion-inc/combustion-documentation/blob/main/probe_ble_specification.rst#food-safe-status. */ data class FoodSafeStatus( val state: State, val logReduction: Double, val secondsAboveThreshold: UInt, val sequenceNumber: UInt, ) { enum class State { NotSafe, Safe, SafetyImpossible, ; override fun toString(): String { return when (this) { NotSafe -> "Not Safe" SafetyImpossible -> "Safety Impossible" else -> name } } companion object { internal fun fromRaw(raw: UInt): State { return when(raw) { 0u -> NotSafe 1u -> Safe 2u -> SafetyImpossible else -> throw IllegalArgumentException("Invalid state $raw") } } } } companion object { internal const val SIZE_BYTES = 8 internal fun fromRawData(data: UByteArray): FoodSafeStatus? { if (data.size < SIZE_BYTES) { throw IllegalArgumentException("Invalid buffer") } val rawState = (data[0].toUShort() and 0b0000_0111u) val rawLogReduction = ((data[0].toUShort() and 0b1111_1000u) shr 3) or ((data[1].toUShort() and 0b0000_0111u) shl 5) val secondsAboveThreshold = ((data[1].toUShort() and 0b1111_1000u) shr 3) or ((data[2].toUShort() and 0b1111_1111u) shl 5) or ((data[3].toUShort() and 0b0000_0111u) shl 13) val sequenceNumber = ((data[3].toUInt() and 0b1111_1000u) shr 3) or ((data[4].toUInt() and 0xFFu) shl 5) or ((data[5].toUInt() and 0xFFu) shl 13) or ((data[6].toUInt() and 0xFFu) shl 21) or ((data[7].toUInt() and 0b0000_0111u) shl 29) return try { FoodSafeStatus( state = State.fromRaw(rawState.toUInt()), logReduction = rawLogReduction.toDouble() * 0.1, secondsAboveThreshold = secondsAboveThreshold.toUInt(), sequenceNumber = sequenceNumber.toUInt(), ) } catch (e: Exception) { null } } val DEFAULT = FoodSafeStatus( state = State.NotSafe, logReduction = 0.0, secondsAboveThreshold = 0u, sequenceNumber = 0u, ) val RANDOM = FoodSafeStatus( state = State.fromRaw(Random.nextUInt(until = 3u)), logReduction = Random.nextDouble(until = 150.0), secondsAboveThreshold = Random.nextUInt(until = 7u * 60u * 60u), sequenceNumber = Random.nextUInt(), ) } }
0
Kotlin
0
4
7b30d50974076c4f8355b5a8acd6f52d7c98f0f2
4,362
combustion-android-ble
MIT License
ui/src/main/java/com/pyamsoft/tickertape/ui/icon/Today.kt
pyamsoft
371,196,339
false
null
package com.pyamsoft.tickertape.ui.icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.ui.graphics.vector.ImageVector // Copied from material-icons-extended @Suppress("unused") val Icons.Filled.Today: ImageVector get() { if (_today != null) { return _today!! } _today = materialIcon(name = "Filled.Today") { materialPath { moveTo(19.0f, 3.0f) horizontalLineToRelative(-1.0f) lineTo(18.0f, 1.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) lineTo(8.0f, 3.0f) lineTo(8.0f, 1.0f) lineTo(6.0f, 1.0f) verticalLineToRelative(2.0f) lineTo(5.0f, 3.0f) curveToRelative(-1.11f, 0.0f, -1.99f, 0.9f, -1.99f, 2.0f) lineTo(3.0f, 19.0f) curveToRelative(0.0f, 1.1f, 0.89f, 2.0f, 2.0f, 2.0f) horizontalLineToRelative(14.0f) curveToRelative(1.1f, 0.0f, 2.0f, -0.9f, 2.0f, -2.0f) lineTo(21.0f, 5.0f) curveToRelative(0.0f, -1.1f, -0.9f, -2.0f, -2.0f, -2.0f) close() moveTo(19.0f, 19.0f) lineTo(5.0f, 19.0f) lineTo(5.0f, 8.0f) horizontalLineToRelative(14.0f) verticalLineToRelative(11.0f) close() moveTo(7.0f, 10.0f) horizontalLineToRelative(5.0f) verticalLineToRelative(5.0f) lineTo(7.0f, 15.0f) close() } } return _today!! } @Suppress("ObjectPropertyName") private var _today: ImageVector? = null
1
Kotlin
0
6
c5309984f17de290ce2fb82120b4699cc8227b65
1,734
tickertape
Apache License 2.0
app/src/main/java/com/ultrawavergb/dashboard/MainActivity.kt
UltraWaveRGB
409,005,200
false
{"Kotlin": 7202}
package com.ultrawavergb.dashboard import android.os.Bundle import android.util.Log import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ValueEventListener import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase class MainActivity : AppCompatActivity() { private val database = Firebase.database private var doorIsOpen = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnPipoca = findViewById<Button>(R.id.btn_pipoca) val btnLasanha = findViewById<Button>(R.id.btn_lasanha) val btnBrigadeiro = findViewById<Button>(R.id.btn_brigadeiro) val btnVegetais = findViewById<Button>(R.id.btn_vegetais) val btnArroz = findViewById<Button>(R.id.btn_arroz) val btnCarne = findViewById<Button>(R.id.btn_carne) val btnStart = findViewById<Button>(R.id.btn_start) val btnStop = findViewById<Button>(R.id.btn_stop_cancel) val seekBar = findViewById<SeekBar>(R.id.skbar_potencia) database.getReference("power").get().addOnSuccessListener { val intValue = it.value.toString().toInt() seekBar.progress = intValue updateSeekBarPotencia(intValue) }.addOnFailureListener { Log.e("firebase", "Error getting data.", it) } addDoorIsOpenListener() addTimerListener() /* --- FUNCOES DOS WIDGETS --- */ btnPipoca.setOnClickListener { template(70, 300) } btnLasanha.setOnClickListener { template(100, 600) } btnBrigadeiro.setOnClickListener { template(50, 240) } btnVegetais.setOnClickListener { template(50, 240) } btnArroz.setOnClickListener { template(90, 540) } btnCarne.setOnClickListener { template(100, 720) } btnStart.setOnClickListener { if (doorIsOpen) { Toast.makeText(this, "Porta Aberta", Toast.LENGTH_LONG).show() } else { val editTextTempoMinutes = findViewById<EditText>(R.id.txtview_tempo_value_minutes) val editTextTempoSeconds = findViewById<EditText>(R.id.txtview_tempo_value_seconds) val minutes = editTextTempoMinutes.text.toString().toInt() val seconds = editTextTempoSeconds.text.toString().toInt() if (seconds > 60) { Toast.makeText(this, "Valor de tempo invalido", Toast.LENGTH_LONG).show() } else { database.getReference("start_button_was_pressed").setValue(1) database.getReference("timer").setValue(minutes * 60 + seconds) editTextTempoMinutes.isEnabled = false editTextTempoSeconds.isEnabled = false } } } btnStop.setOnClickListener { database.getReference("stop_button_was_pressed").setValue(1) } seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(p0: SeekBar?, value: Int, p2: Boolean) { updateSeekBarPotencia(value) } override fun onStartTrackingTouch(p0: SeekBar?) {} override fun onStopTrackingTouch(p0: SeekBar?) {} }) } private fun updateSeekBarPotencia(value: Int) { val txtViewPotencia = findViewById<TextView>(R.id.txtview_potencia_value) txtViewPotencia.text = "${value}%" database.getReference("power").setValue(value) } private fun template(newPower: Int, timer: Int) { updateSeekBarPotencia(newPower) findViewById<SeekBar>(R.id.skbar_potencia).progress = newPower database.getReference("timer").setValue(timer) database.getReference("start_button_was_pressed").setValue(1) } private fun addDoorIsOpenListener() { val doorListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val value = snapshot.value.toString() if (value == "1") { doorIsOpen = true } else if (value == "0") { doorIsOpen = false } } override fun onCancelled(error: DatabaseError) { Log.w("Firebase", "loadPost: Cancelled", error.toException()) } } database.getReference("door_is_open").addValueEventListener(doorListener) } private fun addTimerListener() { val editTextTempoMinutes = findViewById<TextView>(R.id.txtview_tempo_value_minutes) val editTextTempoSeconds = findViewById<TextView>(R.id.txtview_tempo_value_seconds) val timerListener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val value = snapshot.value.toString().toInt() if (value >= 60) { val minutes = value / 60 val seconds = value % 60 editTextTempoMinutes.text = if (minutes >= 10) "$minutes" else "0$minutes" editTextTempoSeconds.text = if (seconds >= 10) "$seconds" else "0$seconds" } else { editTextTempoMinutes.text = "00" editTextTempoSeconds.text = if (value >= 10) "$value" else "0$value" } if (value == 0) { editTextTempoMinutes.isEnabled = true editTextTempoSeconds.isEnabled = true } } override fun onCancelled(error: DatabaseError) { Log.w("Firebase", "loadPost: Cancelled", error.toException()) } } database.getReference("timer").addValueEventListener(timerListener) } }
0
Kotlin
0
0
8cbcb5a51a0b851d62844e95c93445f539d8a5b1
6,173
Dashboard
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/PhoneUpdateCheckmark.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.PhoneUpdateCheckmark: ImageVector get() { if (_phoneUpdateCheckmark != null) { return _phoneUpdateCheckmark!! } _phoneUpdateCheckmark = fluentIcon(name = "Filled.PhoneUpdateCheckmark") { fluentPath { moveTo(8.25f, 22.0f) horizontalLineToRelative(4.56f) arcToRelative(6.48f, 6.48f, 0.0f, false, true, -1.56f, -6.3f) lineTo(11.25f, 9.5f) lineToRelative(-0.96f, 0.97f) lineToRelative(-0.09f, 0.07f) arcTo(0.75f, 0.75f, 0.0f, false, true, 9.16f, 9.5f) lineToRelative(0.07f, -0.08f) lineToRelative(2.24f, -2.24f) lineToRelative(0.05f, -0.05f) lineToRelative(0.06f, -0.04f) lineToRelative(0.07f, -0.05f) lineToRelative(0.12f, -0.05f) lineToRelative(0.1f, -0.02f) lineToRelative(0.08f, -0.01f) horizontalLineToRelative(0.1f) lineToRelative(0.09f, 0.01f) lineToRelative(0.06f, 0.01f) lineToRelative(0.1f, 0.04f) lineToRelative(0.06f, 0.03f) lineToRelative(0.07f, 0.04f) lineToRelative(0.06f, 0.05f) lineToRelative(0.04f, 0.04f) lineToRelative(2.24f, 2.24f) lineToRelative(0.07f, 0.08f) curveToRelative(0.2f, 0.26f, 0.2f, 0.62f, 0.01f, 0.89f) lineToRelative(-0.08f, 0.09f) lineToRelative(-0.08f, 0.07f) curveToRelative(-0.26f, 0.2f, -0.62f, 0.2f, -0.88f, 0.0f) lineToRelative(-0.1f, -0.07f) lineToRelative(-0.96f, -0.96f) verticalLineToRelative(3.55f) arcTo(6.48f, 6.48f, 0.0f, false, true, 18.0f, 11.02f) lineTo(18.0f, 4.25f) curveTo(18.0f, 3.01f, 17.0f, 2.0f, 15.75f, 2.0f) horizontalLineToRelative(-7.5f) curveTo(7.01f, 2.0f, 6.0f, 3.0f, 6.0f, 4.25f) verticalLineToRelative(15.5f) curveTo(6.0f, 20.99f, 7.0f, 22.0f, 8.25f, 22.0f) close() moveTo(23.0f, 17.5f) arcToRelative(5.5f, 5.5f, 0.0f, true, true, -11.0f, 0.0f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, 11.0f, 0.0f) close() moveTo(20.85f, 15.15f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, 0.0f) lineToRelative(-3.65f, 3.64f) lineToRelative(-1.65f, -1.64f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.7f, 0.7f) lineToRelative(2.0f, 2.0f) curveToRelative(0.2f, 0.2f, 0.5f, 0.2f, 0.7f, 0.0f) lineToRelative(4.0f, -4.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -0.7f) close() } } return _phoneUpdateCheckmark!! } private var _phoneUpdateCheckmark: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
3,341
compose-fluent-ui
Apache License 2.0
src/main/kotlin/io/bootstage/testkit/gradle/rules/LocalProperties.kt
bootstage
305,858,887
false
null
package io.bootstage.testkit.gradle.rules import com.didiglobal.booster.build.AndroidSdk import org.junit.rules.TestWatcher import org.junit.runner.Description import java.io.File /** * The rule for `local.properties` generating * * @author johnsonlee */ open class LocalProperties(val projectDir: () -> File) : TestWatcher() { override fun starting(description: Description) { File(projectDir(), "local.properties").writeText("sdk.dir=${AndroidSdk.getLocation()}") } }
0
Kotlin
0
3
d9ae2d3904ad577058963a380b09b32a01261d33
493
testkit-gradle-plugin
Apache License 2.0
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/ClientPacketDecoderService.kt
blurite
822,339,098
false
{"Kotlin": 1453055}
package net.rsprox.protocol import net.rsprot.buffer.JagByteBuf import net.rsprot.compression.HuffmanCodec import net.rsprot.protocol.message.IncomingMessage import net.rsprox.protocol.game.incoming.decoder.prot.ClientMessageDecoderRepository import net.rsprox.protocol.session.Session public class ClientPacketDecoderService( huffmanCodec: HuffmanCodec, ) : ClientPacketDecoder { @OptIn(ExperimentalStdlibApi::class) private val repository = ClientMessageDecoderRepository.build(huffmanCodec) override fun decode( opcode: Int, payload: JagByteBuf, session: Session, ): IncomingMessage { return repository .getDecoder(opcode) .decode(payload, session) } }
2
Kotlin
4
9
41535908e6ccb633c8f2564e8961efa771abd6de
739
rsprox
MIT License
src/main/kotlin/org/pushingpixels/artemis/shaders/ShaderRenderEffectDemo2.kt
kirill-grouchnikov
455,667,291
false
null
/* * Copyright (c) 2021-24 Artemis, <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pushingpixels.artemis.shaders import androidx.compose.animation.core.* import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asComposeRenderEffect import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.WindowPlacement import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.rememberWindowState import kotlinx.coroutines.launch import org.jetbrains.skia.* import org.pushingpixels.aurora.component.model.BaseCommand import org.pushingpixels.aurora.component.model.Command import org.pushingpixels.aurora.component.model.CommandActionPreview import org.pushingpixels.aurora.component.projection.CommandButtonProjection import org.pushingpixels.aurora.theming.businessSkin import org.pushingpixels.aurora.window.AuroraWindow import org.pushingpixels.aurora.window.AuroraWindowTitlePaneConfigurations import org.pushingpixels.aurora.window.auroraApplication fun main() = auroraApplication { val state = rememberWindowState( placement = WindowPlacement.Floating, position = WindowPosition.Aligned(Alignment.Center), size = DpSize(300.dp, 120.dp) ) AuroraWindow( skin = businessSkin(), title = "Filter Demo", state = state, windowTitlePaneConfiguration = AuroraWindowTitlePaneConfigurations.AuroraPlain(), onCloseRequest = ::exitApplication, ) { val blurAmount = remember { Animatable(3.0f) } val blurFilter: ImageFilter = ImageFilter.makeBlur( sigmaX = blurAmount.value, sigmaY = blurAmount.value, mode = FilterTileMode.DECAL ) val blurEffect = blurFilter.asComposeRenderEffect() val coroutineScope = rememberCoroutineScope() Box(modifier = Modifier.fillMaxSize()) { CommandButtonProjection( contentModel = Command(text = "Click me!", action = { println("Clicked!") }, actionPreview = object : CommandActionPreview { override fun onCommandPreviewActivated(command: BaseCommand) { coroutineScope.launch { blurAmount.animateTo( targetValue = 0.1f, animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing) ) } } override fun onCommandPreviewCanceled(command: BaseCommand) { coroutineScope.launch { blurAmount.animateTo( targetValue = 3.0f, animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing) ) } } }) ).project( modifier = Modifier.graphicsLayer(renderEffect = blurEffect).align(Alignment.Center) ) } } }
0
null
7
141
8e57e17f7a1b8e35d3d620c10774f26f980b63cb
3,967
artemis
Apache License 2.0
src/main/kotlin/mashup/sideproject/orderpay/model/mapper/OrderMapper.kt
mash-up-kr
390,779,576
false
null
package mashup.sideproject.orderpay.model.mapper import mashup.sideproject.orderpay.model.dto.order.OrderResponseDto import mashup.sideproject.orderpay.model.dto.order.OrderSubmitRequestDto import mashup.sideproject.orderpay.model.entity.Order import org.mapstruct.Mapper import org.mapstruct.Mapping import org.mapstruct.Mappings @Mapper(componentModel = "spring") interface OrderMapper { @Mappings( Mapping(source = "orderSubmitRequestDto.merchantUid", target = "merchantUid"), Mapping(source = "orderSubmitRequestDto.buyerName", target = "buyerInfo.buyerName"), Mapping(source = "orderSubmitRequestDto.buyerEmail", target = "buyerInfo.buyerEmail"), Mapping(source = "orderSubmitRequestDto.buyerTel", target = "buyerInfo.buyerTel"), Mapping(source = "orderSubmitRequestDto.buyerAddr", target = "buyerInfo.buyerAddr"), Mapping(source = "orderSubmitRequestDto.buyerPostcode", target = "buyerInfo.buyerPostcode"), Mapping(source = "orderResponseDto.productIdList", target = "productIdList"), Mapping(source = "orderResponseDto.optionIdList", target = "optionIdList") ) fun toOrder(orderSubmitRequestDto: OrderSubmitRequestDto, orderResponseDto: OrderResponseDto): Order }
6
Kotlin
0
2
6dcfe2a5893fdfcd3210bdd74703efb04155a90b
1,248
Elegant_Spring_Family_Order_Pay
MIT License
kmm-data-loading-automation/src/commonMain/kotlin/com/kursor/kmmdataloadingautomation/load/Loadable.kt
kursor1337
597,718,576
false
null
package com.kursor.kmmdataloadingautomation.load interface Loadable<T> { val state: State val data: T? val error: LoadingError? enum class State { LOADING, SUCCESS, ERROR } }
0
Kotlin
0
0
de48e757f851c13e98c791d82478970c3e972d0e
210
KmmDataLoadingAutomation
MIT License
src/main/kotlin/net/drleelihr/bot/lib/httpRequest.kt
DrLee-lihr
449,958,078
false
{"Kotlin": 48817}
package net.drleelihr.bot.lib import okhttp3.OkHttpClient import okhttp3.Request fun httpRequest(host: String): String? { val client = OkHttpClient() val request = Request.Builder() .url(host) .get() .build() val call = client.newCall(request) val response = call.execute() if (response.isSuccessful) { val body = response.body //println(body?.string) return body?.string() } else throw(NullPointerException("Request failed,status code:${response.code}")) }
0
Kotlin
0
1
719707f0dd0d8e1a56b980a60c9e32cce2508fc8
531
bot
Apache License 2.0
app/src/main/java/com/example/simpletodo/EditActivity.kt
jessedellariley
439,712,265
false
null
package com.example.simpletodo import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText class EditActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit) val inputTextField = findViewById<EditText>(R.id.editTaskField) // Set the text in the update field to be the current to do value inputTextField.setText(intent.getStringExtra("todo")) // Set a reference to the edit button // And then set an onClickListener findViewById<Button>(R.id.editButton).setOnClickListener { // Grab the text the user has inputted into @id/editTaskField val updatedTask = inputTextField.text.toString() // Return to main screen onSubmit(updatedTask,intent.getIntExtra("position",0)) } } fun onSubmit(updatedTask: String, position: Int) { // Prepare data Intent val data = Intent() // Pass relevant data back as a result data.putExtra("todo", updatedTask) data.putExtra("position",position) // Activity finished okay, return the data setResult(RESULT_OK, data) // set result code and bundle data for response // closes the activity and returns to first screen finish() } }
1
Kotlin
0
0
c5999ec980ee75dda59eb46c0331a1a0c57a69d1
1,474
Simple-ToDo
Apache License 2.0
demo/demo_component_home/src/main/java/com/mars/component/home/event/Events.kt
baidu
504,447,693
false
{"Kotlin": 607049, "Java": 37304}
package com.mars.component.home.event import com.rubik.annotations.context.REvent import com.rubik.context.LifeCycleEvent class Events { @REvent(msg = LifeCycleEvent.INIT) fun myInit(){ println(" CT DBG init HOME begin !!!") } @REvent(msg = LifeCycleEvent.DESTROY) @REvent(msg = "MY") fun myDestory(){ println(" CT DBG destroy HOME begin !!!") } }
3
Kotlin
7
153
065ba8f4652b39ff558a5e3f18b9893e2cf9bd25
397
Rubik
Apache License 2.0
app/src/main/java/com/moegirlviewer/screen/recentChanges/util/recentChangesData.kt
koharubiyori
449,942,456
false
null
package com.moegirlviewer.screen.recentChanges.util import com.moegirlviewer.api.editingRecord.bean.RecentChangesBean import com.moegirlviewer.api.watchList.bean.RecentChangesOfWatchList // 这里的代码主要是为了统一“最近更改”和“监视列表下最近更改”的数据类型,以及合并同页面编辑,为数据添加编辑用户字段 fun processRecentChanges(list: List<RawRecentChanges>): List<RecentChanges> { // 收集同页面编辑,并放入details字段 val listWithDetails = list.fold(mutableListOf<RecentChanges>()) { result, item -> if (result.all { it.title != item.title }) { result.add(RecentChanges( rawRecentChanges = item, details = mutableListOf(item), )) } else { result.first { it.title == item.title }.details.add(item) } result } // 添加users和各自的编辑次数 for (item in listWithDetails) { for (detailItem in item.details) { val foundUserIndex = item.users.indexOfFirst { it.name == detailItem.user } if (foundUserIndex != -1) { item.users[foundUserIndex].total++ } else { item.users.add(EditUserOfChanges( name = detailItem.user, total = 1 )) } } } return listWithDetails } // 这个类的字段命名就按萌百接口返回数据的名字来命名了,方便查找 open class RawRecentChanges( val comment: String, val minor: String? = null, val newlen: Int, val ns: Int, val old_revid: Int, val oldlen: Int, val pageid: Int, val revid: Int, val timestamp: String, val title: String, val type: String, val user: String ) { constructor(data: RecentChangesBean.Query.Recentchange) : this( comment = data.comment, minor = data.minor, newlen = data.newlen, ns = data.ns, old_revid = data.old_revid, oldlen = data.oldlen, pageid = data.pageid, revid = data.revid, timestamp = data.timestamp, title = data.title, type = data.type, user = data.user, ) constructor(data: RecentChangesOfWatchList.Query.Watchlist) : this( comment = data.comment, minor = data.minor, newlen = data.newlen, ns = data.ns, old_revid = data.old_revid, oldlen = data.oldlen, pageid = data.pageid, revid = data.revid, timestamp = data.timestamp, title = data.title, type = data.type, user = data.user, ) } // 何箇所で処理しやすいためにMutableのを使っちゃった_(:з」∠)_,良い子はまねしないでね data class EditUserOfChanges( val name: String, var total: Int, ) class RecentChanges( rawRecentChanges: RawRecentChanges, val details: MutableList<RawRecentChanges> = mutableListOf(), val users: MutableList<EditUserOfChanges> = mutableListOf() ) : RawRecentChanges( comment = rawRecentChanges.comment, minor = rawRecentChanges.minor, newlen = rawRecentChanges.newlen, ns = rawRecentChanges.ns, old_revid = rawRecentChanges.old_revid, oldlen = rawRecentChanges.oldlen, pageid = rawRecentChanges.pageid, revid = rawRecentChanges.revid, timestamp = rawRecentChanges.timestamp, title = rawRecentChanges.title, type = rawRecentChanges.type, user = rawRecentChanges.user, )
1
Kotlin
2
16
e09753e76c11932d6f7344302d48f7a214cccf3a
2,952
Moegirl-plus-native
MIT License
src/main/kotlin/us/jwf/aoc2015/Day16AuntSue.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2015 import java.io.Reader import us.jwf.aoc.Day /** * AoC 2015 - Day 16 */ class Day16AuntSue : Day<Int, Int> { override suspend fun executePart1(input: Reader): Int { return input.readLines().map { SueStats.parse(it) }.find { it.isTarget() }!!.id } override suspend fun executePart2(input: Reader): Int { return input.readLines().map { SueStats.parse(it) }.find { it.isTarget2() }!!.id } data class SueStats( val id: Int, val children: Int?, val cats: Int?, val samoyeds: Int?, val pomeranians: Int?, val akitas: Int?, val vizslas: Int?, val goldfish: Int?, val trees: Int?, val cars: Int?, val perfumes: Int? ) { fun isTarget(): Boolean { return (children?.let { it == TARGET.children } ?: true) && (cats?.let { it == TARGET.cats } ?: true) && (samoyeds?.let { it == TARGET.samoyeds } ?: true) && (pomeranians?.let { it == TARGET.pomeranians } ?: true) && (akitas?.let { it == TARGET.akitas } ?: true) && (vizslas?.let { it == TARGET.vizslas } ?: true) && (goldfish?.let { it == TARGET.goldfish } ?: true) && (trees?.let { it == TARGET.trees } ?: true) && (cars?.let { it == TARGET.cars } ?: true) && (perfumes?.let { it == TARGET.perfumes } ?: true) } fun isTarget2(): Boolean { return (children?.let { it == TARGET.children } ?: true) && (cats?.let { it > TARGET.cats!! } ?: true) && (samoyeds?.let { it == TARGET.samoyeds } ?: true) && (pomeranians?.let { it < TARGET.pomeranians!! } ?: true) && (akitas?.let { it == TARGET.akitas } ?: true) && (vizslas?.let { it == TARGET.vizslas } ?: true) && (goldfish?.let { it < TARGET.goldfish!! } ?: true) && (trees?.let { it > TARGET.trees!! } ?: true) && (cars?.let { it == TARGET.cars } ?: true) && (perfumes?.let { it == TARGET.perfumes } ?: true) } companion object { val TARGET = SueStats( id = -1, children = 3, cats = 7, samoyeds = 2, pomeranians = 3, akitas = 0, vizslas = 0, goldfish = 5, trees = 3, cars = 2, perfumes = 1 ) val NAME_PATTERN = "Sue (\\d+)".toRegex() fun parse(line: String): SueStats { val (namePart, statsPart) = line.split(": ", limit = 2) val id = NAME_PATTERN.matchEntire(namePart)!!.groupValues[1].toInt() val rawStats = statsPart.split(", ") .map { it.split(": ") } .associate { it.first() to it.last().toInt() } return SueStats( id, rawStats["children"], rawStats["cats"], rawStats["samoyeds"], rawStats["pomeranians"], rawStats["akitas"], rawStats["vizslas"], rawStats["goldfish"], rawStats["trees"], rawStats["cars"], rawStats["perfumes"] ) } } } }
0
Kotlin
0
0
0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868
3,008
AdventOfCode-Kotlin
Apache License 2.0
app/src/main/java/com/tap/di/RemoteDataSourceModule.kt
alonsd
622,454,267
false
null
package com.tap.di import com.tap.data.source.remote.source.RemoteDataSource import com.tap.data.source.remote.source.RemoteDataSourceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class RemoteDataSourceModule { @Binds @Singleton abstract fun bindRemoteDataSource( remoteDataSourceImpl: RemoteDataSourceImpl ): RemoteDataSource }
0
Kotlin
0
0
f1d507c72d54e1d1ae70370fc8932bf694385df8
521
TapMobile
MIT License
client/slack-spring-test-api-client/src/main/kotlin/com/kreait/slack/api/test/group/conversation/MockConversationsInviteMethod.kt
raphaeldelio
342,576,196
true
{"Kotlin": 1216622, "Shell": 935}
package com.kreait.slack.api.test.group.conversation import com.kreait.slack.api.contract.jackson.group.conversations.ConversationsInviteRequest import com.kreait.slack.api.contract.jackson.group.conversations.ErrorConversationInviteResponse import com.kreait.slack.api.contract.jackson.group.conversations.SuccessfulConversationInviteResponse import com.kreait.slack.api.group.ApiCallResult import com.kreait.slack.api.group.conversations.ConversationsInviteMethod import com.kreait.slack.api.group.conversations.ConversationsMethodGroup import com.kreait.slack.api.test.MockMethod /** * Testable implementation of [ConversationsMethodGroup.invite] */ open class MockConversationsInviteMethod : ConversationsInviteMethod(), MockMethod<SuccessfulConversationInviteResponse, ErrorConversationInviteResponse, ConversationsInviteRequest> { override var successResponse: SuccessfulConversationInviteResponse? = null override var failureResponse: ErrorConversationInviteResponse? = null override fun request(): ApiCallResult<SuccessfulConversationInviteResponse, ErrorConversationInviteResponse> { this.successResponse?.let { this.onSuccess?.invoke(it) } this.failureResponse?.let { this.onFailure?.invoke(it) } return ApiCallResult(this.successResponse, this.failureResponse) } override fun params(): ConversationsInviteRequest = params }
0
null
0
0
d2eb88733f0513665b8a625351b599feba926b69
1,396
slack-spring-boot-starter
MIT License
camera/integration-tests/extensionstestapp/src/androidTest/java/androidx/camera/integration/extensions/util/CameraXExtensionsActivityTestExtensions.kt
mzgreen
282,427,468
true
{"Kotlin": 59956972, "Java": 54934052, "C++": 9030952, "Python": 274372, "AIDL": 247441, "Shell": 169779, "ANTLR": 19860, "HTML": 19215, "CMake": 12409, "TypeScript": 7599, "JavaScript": 4865, "C": 4764, "Objective-C++": 3190}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.extensions.util import androidx.camera.integration.extensions.CameraExtensionsActivity import androidx.camera.integration.extensions.R import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.ViewMatchers import androidx.testutils.withActivity /** * Waits until the initialization idling resource has become idle. */ internal fun ActivityScenario<CameraExtensionsActivity>.waitForInitializationIdle() { val idlingResource = withActivity { initializationIdlingResource } try { IdlingRegistry.getInstance().register(idlingResource) // Waits for the initializationIdlingResource becoming idle Espresso.onIdle() } finally { // Always releases the idling resource, in case of timeout exceptions. IdlingRegistry.getInstance().unregister(idlingResource) } } /** * Waits until the PreviewView has become STREAMING state and its idling resource has become idle. */ internal fun ActivityScenario<CameraExtensionsActivity>.waitForPreviewIdle() { val idlingResource = withActivity { resetPreviewViewStreamingStateIdlingResource() previewViewStreamingStateIdlingResource } try { IdlingRegistry.getInstance().register(idlingResource) // Waits for the previewViewStreamingStateIdlingResource becoming idle Espresso.onView(ViewMatchers.withId(R.id.viewFinder)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) } finally { // Always releases the idling resource, in case of timeout exceptions. IdlingRegistry.getInstance().unregister(idlingResource) } } /** * Waits until captured image has been saved and its idling resource has become idle. */ internal fun ActivityScenario<CameraExtensionsActivity>.takePictureAndWaitForImageSavedIdle() { val idlingResource = withActivity { takePictureIdlingResource } try { IdlingRegistry.getInstance().register(idlingResource) // Performs click action and waits for the takePictureIdlingResource becoming idle Espresso.onView(ViewMatchers.withId(R.id.Picture)).perform(ViewActions.click()) } finally { // Always releases the idling resource, in case of timeout exceptions. IdlingRegistry.getInstance().unregister(idlingResource) } }
0
Kotlin
1
0
bfc972c52435d9f46afb8b4bf46461b45945bcc2
3,143
androidx
Apache License 2.0
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/spec/dsl/UnfinishedTestDefinitionTest.kt
kotest
47,071,082
false
{"Gradle Kotlin DSL": 57, "JSON": 18, "Markdown": 1115, "Java Properties": 1, "Shell": 2, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 2, "EditorConfig": 1, "SVG": 4, "Kotlin": 1691, "TOML": 1, "INI": 4, "YAML": 18, "JavaScript": 4, "CSS": 3, "MDX": 22, "HTTP": 3, "Java": 1}
package com.sksamuel.kotest.engine.spec.dsl import com.sksamuel.kotest.engine.spec.multilinename.DescribeSpecMultiLineTestTest import io.kotest.core.spec.style.DescribeSpec import io.kotest.core.spec.style.ExpectSpec import io.kotest.core.spec.style.FeatureSpec import io.kotest.core.spec.style.FunSpec import io.kotest.core.spec.style.ShouldSpec import io.kotest.core.spec.style.scopes.TestDslState import io.kotest.engine.TestEngineLauncher import io.kotest.engine.listener.NoopTestEngineListener import io.kotest.inspectors.forAtLeastOne import io.kotest.matchers.string.shouldContain class UnfinishedTestDefinitionTest : FunSpec() { init { afterEach { TestDslState.reset() } test("fun spec") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(FunSpecUnfinishedTestDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished test") } } test("fun spec with override") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(FunSpecUnfinishedTestWithDuplicatedLeafNamesDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("abc") } } test("describe spec") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(DescribeSpecUnfinishedTestDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished it") } } test("should spec") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(ShouldSpecUnfinishedTestDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished should") } } test("feature spec") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(FeatureSpecUnfinishedTestDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished scenario") } } test("expect spec") { val result = TestEngineLauncher(NoopTestEngineListener) .withClasses(ExpectSpecUnfinishedTestDefinitionTest::class) .launch() result.errors.forAtLeastOne { it.message!!.shouldContain("unfinished expect") } } } } private class FunSpecUnfinishedTestDefinitionTest : FunSpec({ context("context") { test("unfinished test") } }) private class FunSpecUnfinishedTestWithDuplicatedLeafNamesDefinitionTest : FunSpec({ context("context1") { test("abc") } context("context2") { test("abc") { } } }) private class FeatureSpecUnfinishedTestDefinitionTest : FeatureSpec({ feature("feature") { scenario("unfinished scenario") } }) private class ShouldSpecUnfinishedTestDefinitionTest : ShouldSpec({ context("context") { should("unfinished should") } }) private class ExpectSpecUnfinishedTestDefinitionTest : ExpectSpec({ context("context") { expect("unfinished expect") } }) private class DescribeSpecUnfinishedTestDefinitionTest : DescribeSpec({ describe("describe") { it("unfinished it") } })
137
Kotlin
623
4,318
e7f7e52a732010fae899d1fcc4d074c055463e0b
3,305
kotest
Apache License 2.0
prl-compiler/src/main/kotlin/com/booleworks/prl/model/rules/FeatureRule.kt
booleworks
721,827,334
false
{"Kotlin": 1495826, "JavaScript": 835976, "Vue": 132739, "TypeScript": 50565, "Java": 32652, "ANTLR": 15836, "Lex": 3646, "CSS": 2243, "Shell": 1735, "Dockerfile": 681, "Scheme": 505}
// SPDX-License-Identifier: MIT // Copyright 2023 BooleWorks GmbH package com.booleworks.prl.model.rules import com.booleworks.prl.model.AnyProperty import com.booleworks.prl.model.Module import com.booleworks.prl.model.constraints.BooleanFeature import com.booleworks.prl.model.constraints.Constant import com.booleworks.prl.model.constraints.Constraint import com.booleworks.prl.model.constraints.EnumFeature import com.booleworks.prl.model.constraints.Feature import com.booleworks.prl.model.constraints.IntFeature import com.booleworks.prl.model.constraints.versionEq import com.booleworks.prl.model.datastructures.FeatureAssignment import com.booleworks.prl.model.datastructures.FeatureRenaming import com.booleworks.prl.parser.PragmaticRuleLanguage.KEYWORD_FEATURE import com.booleworks.prl.parser.PragmaticRuleLanguage.KEYWORD_FORBIDDEN import com.booleworks.prl.parser.PragmaticRuleLanguage.KEYWORD_MANDATORY import com.booleworks.prl.parser.PragmaticRuleLanguage.SYMBOL_EQ import com.booleworks.prl.parser.PragmaticRuleLanguage.quote sealed class FeatureRule<F : FeatureRule<F>>( open val feature: Feature, open val enumValue: String?, open val intValueOrVersion: Int?, module: Module, id: String, description: String, properties: Map<String, AnyProperty>, lineNumber: Int? = null ) : Rule<F>(module, id, description, properties, lineNumber) { val constraint by lazy { generateConstraint(feature, enumValue, intValueOrVersion) } val version by lazy { if (feature is BooleanFeature && (feature as BooleanFeature).versioned) intValueOrVersion else null } val intValue by lazy { if (feature is IntFeature) intValueOrVersion else null } override fun features() = setOf(feature) override fun booleanFeatures() = if (feature is BooleanFeature) setOf(feature as BooleanFeature) else setOf() override fun enumFeatures() = if (feature is EnumFeature) setOf(feature as EnumFeature) else setOf() override fun enumValues() = if (feature is EnumFeature) { val set: MutableSet<String> = mutableSetOf() enumValue?.let { set.add(it) } mapOf(feature as EnumFeature to set) } else { mapOf() } override fun intFeatures() = if (feature is IntFeature) setOf(feature as IntFeature) else setOf() override fun containsBooleanFeatures() = feature is BooleanFeature override fun containsEnumFeatures() = feature is EnumFeature override fun containsIntFeatures() = feature is IntFeature override fun evaluate(assignment: FeatureAssignment) = constraint.evaluate(assignment) override fun restrict(assignment: FeatureAssignment) = constraint.restrict(assignment).let { if (it is Constant) ConstraintRule(this, it) else this } override fun syntacticSimplify() = this protected fun renameFeature(renaming: FeatureRenaming) = when (feature) { is BooleanFeature -> renaming.rename(feature as BooleanFeature) is EnumFeature -> renaming.rename(feature as EnumFeature) is IntFeature -> renaming.rename(feature as IntFeature) } override fun headerLine(currentModule: Module): String { val keyword: String = if (this is ForbiddenFeatureRule) KEYWORD_FORBIDDEN else KEYWORD_MANDATORY val constraintString: String = when (feature) { is BooleanFeature -> if (!(feature as BooleanFeature).versioned) feature.toString(currentModule) else versionEq(feature as BooleanFeature, intValueOrVersion!!).toString(currentModule) is EnumFeature -> feature.toString(currentModule) + " " + SYMBOL_EQ + " " + quote(enumValue!!) is IntFeature -> "${feature.toString(currentModule)} $SYMBOL_EQ $intValueOrVersion" } return "$keyword $KEYWORD_FEATURE $constraintString" } protected abstract fun generateConstraint(feature: Feature, enumValue: String?, intValueOrVersion: Int?): Constraint }
1
Kotlin
0
1
5a7c0836dc1ccea8a30ccabe3a5f4671348da967
3,952
boolerules
MIT License
app/src/main/java/com/canque/listviewrecyclerview/MainActivity.kt
nyrG
786,681,504
false
{"Kotlin": 14061}
package com.canque.listviewrecyclerview import android.content.Intent import android.os.Bundle import android.widget.ArrayAdapter import android.widget.ListView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.canque.listviewrecyclerview.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { binding = ActivityMainBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } binding.button.setOnClickListener { val intent = Intent(this, SimpleListActivity::class.java) startActivity(intent) } binding.button2.setOnClickListener { val intent = Intent(this, CustomListActivity::class.java) startActivity(intent) } binding.button3.setOnClickListener { val intent = Intent(this, RecyclerActivity::class.java) startActivity(intent) } } }
0
Kotlin
0
0
4b3186512448835241c2ec809cc4a759a7e1e45e
1,512
ListViewRecyclerView
MIT License
ksp_processor/src/main/java/dev/vengateshm/ksp_samples/DecoratorProcessorProvider.kt
vengateshm
670,054,614
false
{"Kotlin": 1951190, "Java": 55066}
package dev.vengateshm.ksp_samples import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider class DecoratorProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { return DecoratorProcessor(environment.codeGenerator, environment.logger) } }
0
Kotlin
0
1
1b6a1284df7d294721c7e2890aa3e9e3f0f1e104
463
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
mobile/app/src/main/java/at/sunilson/tahomaraffstorecontroller/mobile/features/groups/presentation/overview/GroupListItem.kt
sunilson
524,687,319
false
{"Kotlin": 247961}
package at.sunilson.tahomaraffstorecontroller.mobile.features.groups.presentation.overview import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Stop import androidx.compose.material3.Divider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import at.sunilson.tahomaraffstorecontroller.mobile.entities.ExecutionActionGroup import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.toImmutableList @Composable fun GroupListItem( actionGroup: ExecutionActionGroup, favouriteGroups: ImmutableList<String> = emptyList<String>().toImmutableList(), executing: Boolean = false, showDivider: Boolean = false, onExecuteActionGroupClicked: (ExecutionActionGroup) -> Unit = {}, onStopExecutionClicked: (ExecutionActionGroup) -> Unit = {}, onDeleteActionGroupClicked: (ExecutionActionGroup) -> Unit = {}, onFavouriteClicked: (ExecutionActionGroup) -> Unit = {}, onItemClicked: (ExecutionActionGroup) -> Unit = {} ) { Column(modifier = Modifier .fillMaxWidth() .clickable { onItemClicked(actionGroup) }) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(12.dp) ) { Text(actionGroup.label, modifier = Modifier.weight(1f)) IconButton(onClick = { onFavouriteClicked(actionGroup) }) { if (favouriteGroups.contains(actionGroup.id)) { Icon(Icons.Default.Favorite, contentDescription = "Favorite") } else { Icon(Icons.Default.FavoriteBorder, contentDescription = "Favorite") } } Spacer(modifier = Modifier.width(6.dp)) IconButton( onClick = { onDeleteActionGroupClicked(actionGroup) } ) { Icon(Icons.Default.Delete, contentDescription = "Stop execution") } Spacer(modifier = Modifier.width(6.dp)) IconButton( onClick = { if (executing) { onStopExecutionClicked(actionGroup) } else { onExecuteActionGroupClicked(actionGroup) } } ) { if (executing) { Icon(Icons.Default.Stop, contentDescription = "Stop execution") } else { Icon(Icons.Default.PlayArrow, contentDescription = "Start execution") } } } if (showDivider) { Divider() } } }
0
Kotlin
0
0
1808f76814f433900204552584e38f4bfe832070
3,443
somfy-tahoma-raffstore-app
MIT License
feature/tag/src/commonMain/kotlin/com/taetae98/diary/feature/tag/detail/uistate/TagDetailTabUiState.kt
TaeTae98
670,251,079
false
{"Kotlin": 306928, "Swift": 1582, "HTML": 230}
package com.taetae98.diary.feature.tag.detail.uistate import androidx.compose.runtime.Composable import com.taetae98.diary.feature.tag.detail.model.TagDetailTab internal data class TagDetailTabUiState( val tab: TagDetailTab, val icon: @Composable () -> Unit, )
1
Kotlin
0
0
459b923b853a0af9b7aae85ba120b2a0e203d355
271
Diary
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1010004.kt
pointillion
428,683,199
true
{"Kotlin": 538588, "HTML": 47353, "CSS": 17418, "JavaScript": 79}
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position val dress1010004 = PartialDressBlueprint( id = 1010004, name = "アーサー", baseRarity = 4, character = Character.Karen, attribute = Attribute.Flower, damageType = DamageType.Normal, position = Position.Middle, positionValue = 22050, stats = StatData( hp = 1162, actPower = 152, normalDefense = 76, specialDefense = 79, agility = 154, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 38290, actPower = 2390, normalDefense = 836, specialDefense = 1251, agility = 3200, ), actParameters = mapOf( ActType.Act1 to listOf( ActParameters( values = listOf(88, 92, 96, 101, 105), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act2 to listOf( ActParameters( values = listOf(93, 98, 102, 107, 112), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(20, 20, 20, 20, 20), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.Act3 to listOf( ActParameters( values = listOf(118, 124, 130, 136, 142), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(2, 2, 2, 2, 2), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ActType.ClimaxAct to listOf( ActParameters( values = listOf(105, 110, 115, 121, 126), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(5, 6, 7, 8, 10), times = listOf(1, 1, 1, 1, 1), ), ActParameters( values = listOf(100, 180, 290, 480, 740), times = listOf(3, 3, 3, 3, 3), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ActParameters( values = listOf(0, 0, 0, 0, 0), times = listOf(0, 0, 0, 0, 0), ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = listOf( listOf( StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.SpecialDefense, 1), ), listOf( StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.Agility, 7), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.Hp, 3), StatBoost(StatBoostType.ActPower, 3), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 3), StatBoost(StatBoostType.NormalDefense, 7), StatBoost(StatBoostType.NormalDefense, 3), StatBoost(StatBoostType.Agility, 8), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Hp, 4), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 4), StatBoost(StatBoostType.Act1Level, 0), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.SpecialDefense, 8), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Hp, 5), ), listOf( StatBoost(StatBoostType.Hp, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.SpecialDefense, 5), StatBoost(StatBoostType.Agility, 9), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 5), StatBoost(StatBoostType.NormalDefense, 8), StatBoost(StatBoostType.NormalDefense, 4), ), listOf( StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.Act2Level, 0), StatBoost(StatBoostType.Agility, 11), StatBoost(StatBoostType.ClimaxActLevel, 0), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.Act3Level, 0), StatBoost(StatBoostType.Act1Level, 0), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.SpecialDefense, 6), ), listOf( StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.Hp, 6), StatBoost(StatBoostType.NormalDefense, 6), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.SpecialDefense, 6), StatBoost(StatBoostType.ActPower, 6), StatBoost(StatBoostType.NormalDefense, 6), ), ), friendshipPanels = listOf( StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 1), StatBoost(StatBoostType.Hp, 1), StatBoost(StatBoostType.NormalDefense, 1), StatBoost(StatBoostType.SpecialDefense, 1), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 1), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.None, 0), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), StatBoost(StatBoostType.ActPower, 2), StatBoost(StatBoostType.Hp, 2), StatBoost(StatBoostType.NormalDefense, 2), StatBoost(StatBoostType.SpecialDefense, 2), StatBoost(StatBoostType.Agility, 2), ), remakeParameters = listOf( StatData( hp = 9000, actPower = 420, normalDefense = 450, specialDefense = 150, agility = 180, ), StatData( hp = 15000, actPower = 700, normalDefense = 750, specialDefense = 250, agility = 300, ), StatData( hp = 24000, actPower = 1120, normalDefense = 1200, specialDefense = 400, agility = 480, ), StatData( hp = 30000, actPower = 1400, normalDefense = 1500, specialDefense = 500, agility = 600, ), ), )
0
null
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
10,041
relive-simulator
MIT License
src/main/kotlin/com/chriswk/aoc/advent2022/Day8.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2022 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day8: AdventDay(2022, 8) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day8() report { day.part1() } report { day.part2() } } } fun parseInput(lines: List<String>): Pair<List<List<Int>>, List<List<Int>>> { val rows = lines.map { line -> line.map { it.digitToInt() }} val columns = List(lines.size) { m -> rows.map { it[m] } } return columns to rows } fun findVisible(columns: List<List<Int>>, rows: List<List<Int>>): Int { val visible = List(rows.size) { MutableList(columns.size) { false } } for (i in rows.indices) { for (j in columns.indices) { visible[i][j] = rows[i].visible(j) || columns[j].visible(i) } } return visible.sumOf { it.count { it }} } fun findScenicScore(columns: List<List<Int>>, rows: List<List<Int>>): Int { var scenicScore = -1 rows.forEachIndexed { i, r -> columns.forEachIndexed { j, c -> scenicScore = maxOf(scenicScore, (i to j).scenicScore(r, c)) } } return scenicScore } fun part1(): Int { val (columns, rows) = parseInput(inputAsLines) return findVisible(columns, rows) } fun part2(): Int { val (columns, rows) = parseInput(inputAsLines) return findScenicScore(columns, rows) } fun Pair<Int, Int>.scenicScore(row: List<Int>, column: List<Int>): Int { val right = row.scenicScore(second) val left = row.reversed().scenicScore(row.size - 1 - second) val down = column.scenicScore(first) val up = column.reversed().scenicScore(column.size - 1 - first) return right*left*up*down } fun List<Int>.scenicScore(i: Int): Int { val rest = drop(i + 1) return if (rest.none { it >= get(i) }) rest.count() else 1 + rest.takeWhile { it < get(i) }.count() } fun List<Int>.visible(i: Int) = drop(i + 1).none { it >= get(i) } || reversed().drop(size - i).none { it >= get(i) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,284
adventofcode
MIT License
app/src/main/kotlin/com/dmdiaz/currency/ui/CurrencyApp.kt
dmdiaz4
338,934,852
false
{"Kotlin": 258525}
/* * MIT License * * Copyright (c) 2024 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdiaz.currency.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.navigation.NavDestination import androidx.navigation.NavDestination.Companion.hierarchy import com.dmdiaz.currency.libs.designsystem.components.CurrencyBackground import com.dmdiaz.currency.libs.designsystem.components.CurrencyNavigationBar import com.dmdiaz.currency.libs.designsystem.components.CurrencyNavigationBarItem import com.dmdiaz.currency.libs.designsystem.components.CurrencyNavigationRail import com.dmdiaz.currency.libs.designsystem.components.CurrencyNavigationRailItem import com.dmdiaz.currency.libs.designsystem.components.CurrencyTopAppBar import com.dmdiaz.currency.navigation.CurrencyNavHost import com.dmdiaz.currency.navigation.TopLevelDestination @OptIn( ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class, ) @Composable fun CurrencyApp( windowSizeClass: WindowSizeClass, appState: CurrencyAppState = rememberCurrencyAppState( windowSizeClass = windowSizeClass, ), ) { CurrencyBackground { val snackbarHostState = remember { SnackbarHostState() } Scaffold( modifier = Modifier.semantics { testTagsAsResourceId = true }, containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onSurface, contentWindowInsets = WindowInsets(0, 0, 0, 0), snackbarHost = { SnackbarHost(snackbarHostState) }, bottomBar = { if (appState.shouldShowBottomBar) { CurrencyBottomBar( destinations = appState.topLevelDestinations, onNavigateToDestination = appState::navigateToTopLevelDestination, currentDestination = appState.currentDestination, modifier = Modifier.testTag("CurrencyBottomBar"), ) } }, ) { padding -> Row( Modifier .fillMaxSize() .padding(padding) .consumeWindowInsets(padding) .windowInsetsPadding( WindowInsets.safeDrawing.only( WindowInsetsSides.Horizontal, ), ), ) { if (appState.shouldShowNavRail) { CurrencyNavRail( destinations = appState.topLevelDestinations, onNavigateToDestination = appState::navigateToTopLevelDestination, currentDestination = appState.currentDestination, modifier = Modifier .testTag("CurrencyNavRail") .safeDrawingPadding(), ) } Column(Modifier.fillMaxSize()) { // Show the top app bar on top level destinations. val destination = appState.currentTopLevelDestination if (destination != null) { CurrencyTopAppBar( titleRes = destination.titleTextId, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = Color.Transparent, ), ) } CurrencyNavHost(appState = appState) } } } } } @Composable private fun CurrencyNavRail( destinations: List<TopLevelDestination>, onNavigateToDestination: (TopLevelDestination) -> Unit, currentDestination: NavDestination?, modifier: Modifier = Modifier, ) { CurrencyNavigationRail(modifier = modifier) { Spacer(Modifier.weight(1f)) destinations.forEach { destination -> val selected = currentDestination.isTopLevelDestinationInHierarchy(destination) CurrencyNavigationRailItem( selected = selected, onClick = { onNavigateToDestination(destination) }, icon = { Icon( imageVector = destination.unselectedIcon, contentDescription = null, ) }, selectedIcon = { Icon( imageVector = destination.selectedIcon, contentDescription = null, ) }, label = { Text(stringResource(destination.iconTextId)) }, modifier = Modifier, ) } Spacer(Modifier.weight(1f)) } } @Composable private fun CurrencyBottomBar( destinations: List<TopLevelDestination>, onNavigateToDestination: (TopLevelDestination) -> Unit, currentDestination: NavDestination?, modifier: Modifier = Modifier, ) { CurrencyNavigationBar( modifier = modifier, ) { destinations.forEach { destination -> val selected = currentDestination.isTopLevelDestinationInHierarchy(destination) CurrencyNavigationBarItem( selected = selected, onClick = { onNavigateToDestination(destination) }, icon = { Icon( imageVector = destination.unselectedIcon, contentDescription = null, ) }, selectedIcon = { Icon( imageVector = destination.selectedIcon, contentDescription = null, ) }, label = { Text(stringResource(destination.iconTextId)) }, modifier = Modifier, ) } } } private fun NavDestination?.isTopLevelDestinationInHierarchy(destination: TopLevelDestination) = this?.hierarchy?.any { it.route?.contains(destination.name, true) ?: false } ?: false
0
Kotlin
0
1
4b62e68e15130737e98587c38b9dcc05e0a48b46
8,700
Currency
MIT License
domain/src/commonMain/kotlin/ireader/domain/usecases/preferences/reader_preferences/BackgroundColorUseCase.kt
kazemcodes
540,829,865
true
{"Kotlin": 2179459}
package ireader.domain.usecases.preferences.reader_preferences import androidx.compose.ui.graphics.Color import ireader.domain.models.prefs.PreferenceValues import ireader.domain.preferences.prefs.AppPreferences import ireader.domain.preferences.prefs.ReaderPreferences class BackgroundColorUseCase( private val prefs: AppPreferences, ) { fun save(value: androidx.compose.ui.graphics.Color) { prefs.backgroundColorReader().set(value) } suspend fun read(): androidx.compose.ui.graphics.Color { return prefs.backgroundColorReader().get() } } class TextColorUseCase( private val prefs: AppPreferences, ) { fun save(value: Color) { prefs.textColorReader().set(value) } suspend fun read(): Color { return prefs.textColorReader().get() } } class TextAlignmentUseCase( private val prefs: ReaderPreferences, ) { fun save(textAlign: PreferenceValues.PreferenceTextAlignment) { prefs.textAlign().set(textAlign) } suspend fun read(): PreferenceValues.PreferenceTextAlignment { return prefs.textAlign().get() } }
0
Kotlin
0
6
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
1,114
IReader
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/iotanalytics/CfnPipelineLambdaPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.iotanalytics import cloudshift.awscdk.common.CdkDslMarker import kotlin.Number import kotlin.String import software.amazon.awscdk.services.iotanalytics.CfnPipeline /** * An activity that runs a Lambda function to modify the message. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.iotanalytics.*; * LambdaProperty lambdaProperty = LambdaProperty.builder() * .batchSize(123) * .lambdaName("lambdaName") * .name("name") * // the properties below are optional * .next("next") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-lambda.html) */ @CdkDslMarker public class CfnPipelineLambdaPropertyDsl { private val cdkBuilder: CfnPipeline.LambdaProperty.Builder = CfnPipeline.LambdaProperty.builder() /** * @param batchSize The number of messages passed to the Lambda function for processing. The AWS * Lambda function must be able to process all of these messages within five minutes, which is * the maximum timeout duration for Lambda functions. */ public fun batchSize(batchSize: Number) { cdkBuilder.batchSize(batchSize) } /** @param lambdaName The name of the Lambda function that is run on the message. */ public fun lambdaName(lambdaName: String) { cdkBuilder.lambdaName(lambdaName) } /** @param name The name of the 'lambda' activity. */ public fun name(name: String) { cdkBuilder.name(name) } /** @param next The next activity in the pipeline. */ public fun next(next: String) { cdkBuilder.next(next) } public fun build(): CfnPipeline.LambdaProperty = cdkBuilder.build() }
4
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
2,099
awscdk-dsl-kotlin
Apache License 2.0
svverif/03-atm-switch/src/main/kotlin/AtmMonitor.kt
frwang96
416,809,961
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ @file:Verik @file:Suppress("DEPRECATED_IDENTITY_EQUALS") import io.verik.core.* class AtmMonitor( val rcv_mbx: Mailbox<AtmCell>, val stream_id: Int, val tx: TxInterface.TxTbModulePort ) : Class() { @Task fun run() { fork { tx.cb.clav = false wait(tx.cb) println("@${time()}: Monitor[$stream_id] start") forever { receiveCell() } } } @Task private fun receiveCell() { val ac = AtmCell() val bytes = ArrayList<Ubit<`8`>>() wait(tx.cb) tx.cb.clav = true while (inji("${tx.cb.soc} !== ${true}")) wait(tx.cb) // TODO replace operator for (i in 0 until ATM_CELL_SIZE) { while (tx.cb.en) wait(tx.cb) bytes.add(tx.cb.data) wait(tx.cb) tx.cb.clav = false } ac.byteUnpack(bytes) println("@${time()}: Monitor[$stream_id] received vci=${ac.vci}") rcv_mbx.put(ac) } }
0
Kotlin
1
5
9a0f5f79b824e69a33dc4f9717d3b9e3ed103180
1,066
verik-examples
Apache License 2.0
mobileapp/src/androidInstrumentedTest/kotlin/io/github/landrynorris/multifactor/mobileapp/test/TestUtils.kt
LandryNorris
499,945,866
false
{"Kotlin": 147567, "Swift": 9853, "Ruby": 2324, "Shell": 1049}
package io.github.landrynorris.multifactor.mobileapp.test import androidx.test.core.app.ActivityScenario import io.github.landrynorris.multifactor.MainActivity import io.github.landrynorris.multifactor.components.OtpLogic import io.github.landrynorris.multifactor.components.PasswordLogic import io.github.landrynorris.multifactor.components.RootComponent import io.github.landrynorris.multifactor.components.SettingsLogic fun ActivityScenario<MainActivity>.withRootComponent(block: RootComponent.() -> Unit) { onActivity { it.logic.block() } } fun ActivityScenario<MainActivity>.withCurrentLogic(block: Any.() -> Unit) { withRootComponent { val activeChild = routerState.value.active val component = activeChild.instance.component component.block() } } fun ActivityScenario<MainActivity>.withOtpLogic(block: OtpLogic.() -> Unit) { withCurrentLogic { if(this !is OtpLogic) error("Otp Logic is not active. Make sure to navigate") block() } } fun ActivityScenario<MainActivity>.withPasswordLogic(block: PasswordLogic.() -> Unit) { withCurrentLogic { if(this !is PasswordLogic) error("Password Logic is not active. Make sure to navigate") block() } } fun ActivityScenario<MainActivity>.withSettingsLogic(block: SettingsLogic.() -> Unit) { withCurrentLogic { if(this !is SettingsLogic) error("Settings Logic is not active. Make sure to navigate") block() } }
3
Kotlin
0
5
a5c9ed73e5935d300612047a6104f6c706c8f060
1,481
MultiFactor
Apache License 2.0
app/src/test/java/com/fevziomurtekin/deezer/viewmodel/AlbumDetailsViewModelTest.kt
gustavobite
331,638,803
true
{"Kotlin": 191832}
package com.fevziomurtekin.deezer.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.asLiveData import com.fevziomurtekin.deezer.core.MockUtil import com.fevziomurtekin.deezer.core.data.ApiResult import com.fevziomurtekin.deezer.data.AlbumData import com.fevziomurtekin.deezer.di.MainCoroutinesRule import com.fevziomurtekin.deezer.domain.local.DeezerDao import com.fevziomurtekin.deezer.domain.network.DeezerClient import com.fevziomurtekin.deezer.domain.network.DeezerService import com.fevziomurtekin.deezer.ui.album.AlbumDetailsViewModel import com.fevziomurtekin.deezer.ui.album.AlbumRepository import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class AlbumDetailsViewModelTest { private lateinit var viewModel: AlbumDetailsViewModel private lateinit var repository: AlbumRepository private val deezerService: DeezerService = mockk() private val deezerClient = DeezerClient(deezerService) private val deezerDao: DeezerDao = mockk() @ExperimentalCoroutinesApi @get:Rule var coroutineRule = MainCoroutinesRule() @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi @Before fun setup(){ repository = AlbumRepository(deezerClient,deezerDao) viewModel = AlbumDetailsViewModel(repository) } @Test fun fetchAlbumListTest() = runBlocking { val mockList = listOf(MockUtil.album) val observer : Observer<ApiResult<List<AlbumData>>> = mock() val fetchedData : LiveData<ApiResult<List<AlbumData>>> = repository.fetchAlbumTracks("302127").asLiveData() fetchedData.observeForever(observer) viewModel.fetchingAlbumDatas(MockUtil.albumID) delay(500L) verify(observer).onChanged(ApiResult.Success(mockList)) fetchedData.removeObserver(observer) } }
0
null
0
0
1ec7f41041162a651c6e9f98ad1cfe2a06cb3cef
2,226
DeezerClone
Apache License 2.0
kotlin/examples/src/main/kotlin/examples/utils/visualization/meshvis2d/viewport/DragBehavior.kt
facebookresearch
495,505,391
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package examples.utils.visualization.meshvis2d.viewport import examples.utils.visualization.meshvis2d.math.Vector2 import examples.utils.visualization.meshvis2d.mesh.Vertex interface DragEvent data class LookAt(val worldCenter: Vector2) : DragEvent interface VertexDragEvent : DragEvent { data class VertexDragBegin(val vertex: Vertex) : VertexDragEvent data class VertexDrag(val vertex: Vertex, val pos: Vector2) : VertexDragEvent data class VertexDragEnd(val vertex: Vertex) : VertexDragEvent } sealed interface DragState { fun cursorDown(ctx: TransitionContext, viewportPos: Vector2): TransitionResult fun cursorUp(ctx: TransitionContext, viewportPos: Vector2): TransitionResult fun cursorMove(ctx: TransitionContext, viewportPos: Vector2): TransitionResult data class TransitionContext(val viewport: Viewport, val scene: Scene) data class TransitionResult(val state: DragState, val events: List<DragEvent> = listOf()) { constructor(state: DragState, event: DragEvent): this(state, listOf(event)) } } class ActiveDragInfo( val beginWorldCenter: Vector2, val beginWorldPos: Vector2, val beginViewportPos: Vector2 ) class BackgroundDragState(val activeDragInfo: ActiveDragInfo) : DragState { override fun cursorDown(ctx: DragState.TransitionContext, viewportPos: Vector2) = DragState.TransitionResult(this) override fun cursorUp(ctx: DragState.TransitionContext, viewportPos: Vector2) = DragState.TransitionResult(NoDragState) override fun cursorMove(ctx: DragState.TransitionContext, viewportPos: Vector2): DragState.TransitionResult { val worldToViewportScale = ctx.viewport.camera.inferWorldToViewportScale() val dViewport = viewportPos - activeDragInfo.beginViewportPos val dWorld = Vector2( -dViewport.x * (1f / worldToViewportScale), dViewport.y * (1f / worldToViewportScale) ) val worldCenter = activeDragInfo.beginWorldCenter + dWorld return DragState.TransitionResult(this, LookAt(worldCenter)) } } class VertexDragState( val activeDragInfo: ActiveDragInfo, val hitVertex: Vertex, val hitVertexPos: Vector2 ): DragState { override fun cursorDown(ctx: DragState.TransitionContext, viewportPos: Vector2) = DragState.TransitionResult(this) override fun cursorUp(ctx: DragState.TransitionContext, viewportPos: Vector2) = DragState.TransitionResult(NoDragState, VertexDragEvent.VertexDragEnd(hitVertex)) override fun cursorMove(ctx: DragState.TransitionContext, viewportPos: Vector2): DragState.TransitionResult { val camera = ctx.viewport.camera val worldPos = camera.viewportToWorld(viewportPos) val dWorld = worldPos - activeDragInfo.beginWorldPos return DragState.TransitionResult( this, // TODO should we use hitVertex or hitVertex.id ? VertexDragEvent.VertexDrag(hitVertex, hitVertexPos + dWorld) ) } } object NoDragState : DragState { override fun cursorDown(ctx: DragState.TransitionContext, viewportPos: Vector2): DragState.TransitionResult { val cursorWorldPos = ctx.viewport.camera.viewportToWorld(viewportPos) val activeDragInfo = ActiveDragInfo(ctx.viewport.worldCenter, cursorWorldPos, viewportPos) val vertex: Vertex? = ctx.scene.hitTest(cursorWorldPos) return if (vertex != null) { DragState.TransitionResult( VertexDragState(activeDragInfo, vertex, cursorWorldPos), VertexDragEvent.VertexDragBegin(vertex) ) } else { DragState.TransitionResult(BackgroundDragState(activeDragInfo)) } } override fun cursorUp(ctx: DragState.TransitionContext, viewportPos: Vector2): DragState.TransitionResult = DragState.TransitionResult(this) override fun cursorMove(ctx: DragState.TransitionContext, viewportPos: Vector2): DragState.TransitionResult = DragState.TransitionResult(this) }
62
Jupyter Notebook
3
55
710f403719bb89e3bcf00d72e53313f8571d5230
4,210
diffkt
MIT License
src/main/kotlin/org/jglrxavpok/kameboy/processing/video/ColorPalettes.kt
jglrxavpok
123,712,183
false
null
package org.jglrxavpok.kameboy.processing.video abstract class ColorPalette { abstract fun color(index: Int): Long abstract val name: String operator fun invoke(index: Int) = color(index) override fun toString(): String { return name } } val DefaultPalette = object: ColorPalette() { override fun color(index: Int) = when(index) { 0 -> 0xFFFFFFFF 1 -> 0xFFAAAAAA 2 -> 0xFF555555 3 -> 0xFF000000 else -> error("Invalid color index: $index") } override val name = "Emulator default" } // https://lospec.com/palette-list/pokemon-sgb val PokemonSGB = object: ColorPalette() { override fun color(index: Int) = when(index) { 0 -> 0xFFFFEFFF 1 -> 0xFFF7B58C 2 -> 0xFF84739C 3 -> 0xFF181010 else -> error("Invalid color index: $index") } override val name = "Pokemon Super GameBoy" } // https://lospec.com/palette-list/2-bit-grayscale val GrayscalePalette = object: ColorPalette() { override fun color(index: Int) = when(index) { 0 -> 0xFFFFFFFF 1 -> 0xFFB6B6B6 2 -> 0xFF676767 3 -> 0xFF000000 else -> error("Invalid color index: $index") } override val name = "Grayscale" } // https://lospec.com/palette-list/kirokaze-gameboy val KirokazePalette = object: ColorPalette() { override fun color(index: Int) = when(index) { 0 -> 0xFFE2F3E4 1 -> 0xFF94E344 2 -> 0xFF46878F 3 -> 0xFF332C50 else -> error("Invalid color index: $index") } override val name = "Kirokaze's Palette" } // https://lospec.com/palette-list/links-awakening-sgb val LinksAwakeningPalette = object: ColorPalette() { override fun color(index: Int) = when(index) { 0 -> 0xFFFFFFB5 1 -> 0xFF7BC67B 2 -> 0xFF6B8C42 3 -> 0xFF5A3921 else -> error("Invalid color index: $index") } override val name = "Link's Awakening" } val Palettes = arrayOf(DefaultPalette, PokemonSGB, GrayscalePalette, KirokazePalette, LinksAwakeningPalette)
0
Kotlin
0
3
a07f8a8b402176cb00809377238c19a07039a177
2,086
KameBoy
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/managerecallsapi/db/UserDetails.kt
ministryofjustice
371,053,303
false
null
package uk.gov.justice.digital.hmpps.managerecallsapi.db import uk.gov.justice.digital.hmpps.managerecallsapi.documents.PersonName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.Email import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FirstName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FullName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.LastName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PhoneNumber import uk.gov.justice.digital.hmpps.managerecallsapi.domain.UserId import java.time.OffsetDateTime import java.util.UUID import javax.persistence.Column import javax.persistence.Convert import javax.persistence.Entity import javax.persistence.EnumType import javax.persistence.Enumerated import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "user_details") data class UserDetails( @Id val id: UUID, @Column(nullable = false) @Convert(converter = FirstNameJpaConverter::class) val firstName: FirstName, @Column(nullable = false) @Convert(converter = LastNameJpaConverter::class) val lastName: LastName, @Column(nullable = false) val signature: String, @Column(nullable = false) @Convert(converter = EmailJpaConverter::class) val email: Email, @Column(nullable = false) @Convert(converter = PhoneNumberJpaConverter::class) val phoneNumber: PhoneNumber, @Column(nullable = false) @Enumerated(EnumType.STRING) val caseworkerBand: CaseworkerBand, @Column(nullable = false) val createdDateTime: OffsetDateTime ) { constructor( userId: UserId, firstName: FirstName, lastName: LastName, signature: String, email: Email, phoneNumber: PhoneNumber, band: CaseworkerBand, createdDateTime: OffsetDateTime ) : this( userId.value, firstName, lastName, signature, email, phoneNumber, band, createdDateTime ) fun userId() = UserId(id) fun personName() = PersonName(this.firstName, lastName = this.lastName) fun fullName(): FullName = personName().firstAndLastName() } enum class CaseworkerBand { THREE, FOUR_PLUS }
2
Kotlin
0
1
708e801435483b0406197fdc61e85ab7c2d2cc82
2,131
manage-recalls-api
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/managerecallsapi/db/UserDetails.kt
ministryofjustice
371,053,303
false
null
package uk.gov.justice.digital.hmpps.managerecallsapi.db import uk.gov.justice.digital.hmpps.managerecallsapi.documents.PersonName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.Email import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FirstName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FullName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.LastName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PhoneNumber import uk.gov.justice.digital.hmpps.managerecallsapi.domain.UserId import java.time.OffsetDateTime import java.util.UUID import javax.persistence.Column import javax.persistence.Convert import javax.persistence.Entity import javax.persistence.EnumType import javax.persistence.Enumerated import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "user_details") data class UserDetails( @Id val id: UUID, @Column(nullable = false) @Convert(converter = FirstNameJpaConverter::class) val firstName: FirstName, @Column(nullable = false) @Convert(converter = LastNameJpaConverter::class) val lastName: LastName, @Column(nullable = false) val signature: String, @Column(nullable = false) @Convert(converter = EmailJpaConverter::class) val email: Email, @Column(nullable = false) @Convert(converter = PhoneNumberJpaConverter::class) val phoneNumber: PhoneNumber, @Column(nullable = false) @Enumerated(EnumType.STRING) val caseworkerBand: CaseworkerBand, @Column(nullable = false) val createdDateTime: OffsetDateTime ) { constructor( userId: UserId, firstName: FirstName, lastName: LastName, signature: String, email: Email, phoneNumber: PhoneNumber, band: CaseworkerBand, createdDateTime: OffsetDateTime ) : this( userId.value, firstName, lastName, signature, email, phoneNumber, band, createdDateTime ) fun userId() = UserId(id) fun personName() = PersonName(this.firstName, lastName = this.lastName) fun fullName(): FullName = personName().firstAndLastName() } enum class CaseworkerBand { THREE, FOUR_PLUS }
2
Kotlin
0
1
708e801435483b0406197fdc61e85ab7c2d2cc82
2,131
manage-recalls-api
MIT License
app/src/main/java/ru/dimon6018/metrolauncher/content/settings/activities/FeedbackSettingsActivity.kt
queuejw
659,118,377
false
null
package ru.dimon6018.metrolauncher.content.settings.activities import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import androidx.lifecycle.lifecycleScope import com.google.android.material.button.MaterialButton import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import ru.dimon6018.metrolauncher.Application.Companion.PREFS import ru.dimon6018.metrolauncher.R import ru.dimon6018.metrolauncher.content.data.Prefs import ru.dimon6018.metrolauncher.content.data.bsod.BSOD import ru.dimon6018.metrolauncher.databinding.LauncherSettingsFeedbackBinding import ru.dimon6018.metrolauncher.helpers.utils.Utils.Companion.applyWindowInsets class FeedbackSettingsActivity: AppCompatActivity() { private lateinit var binding: LauncherSettingsFeedbackBinding override fun onCreate(savedInstanceState: Bundle?) { binding = LauncherSettingsFeedbackBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(binding.root) WindowCompat.setDecorFitsSystemWindows(window, false) initViews() updateMaxLogsSize(binding.settingsInclude.save1bsod,0) updateMaxLogsSize(binding.settingsInclude.save5bsod,1) updateMaxLogsSize(binding.settingsInclude.save10bsod,2) updateMaxLogsSize(binding.settingsInclude.saveallbsods,3) applyWindowInsets(binding.root) } private fun initViews() { binding.settingsInclude.showBsodInfo.setOnClickListener { startActivity(Intent(this, FeedbackBsodListActivity::class.java)) } binding.settingsInclude.deleteBsodInfo.setOnClickListener { lifecycleScope.launch(Dispatchers.IO) { BSOD.getData(this@FeedbackSettingsActivity).clearAllTables() }.start() } binding.settingsInclude.sendFeedbackSwitch.apply { isChecked = PREFS.isFeedbackEnabled text = if(PREFS.isFeedbackEnabled) getString(R.string.on) else getString(R.string.off) setOnCheckedChangeListener { _, isChecked -> PREFS.isFeedbackEnabled = isChecked text = if(isChecked) getString(R.string.on) else getString(R.string.off) } } binding.settingsInclude.setCrashLogLimitBtn.apply { setButtonText(PREFS, this) setOnClickListener { binding.settingsInclude.chooseBsodInfoLimit.visibility = View.VISIBLE visibility = View.GONE } } binding.settingsInclude.showErrorDetailsOnBsodSwitch.apply { isChecked = PREFS.bsodOutputEnabled text = if(PREFS.bsodOutputEnabled) getString(R.string.on) else getString(R.string.off) setOnCheckedChangeListener { _, isChecked -> PREFS.bsodOutputEnabled = isChecked text = if(isChecked) getString(R.string.on) else getString(R.string.off) } } } private fun updateMaxLogsSize(view: View, value: Int) { view.setOnClickListener { PREFS.maxCrashLogs = value binding.settingsInclude.chooseBsodInfoLimit.visibility = View.GONE binding.settingsInclude.setCrashLogLimitBtn.visibility = View.VISIBLE setButtonText(PREFS, binding.settingsInclude.setCrashLogLimitBtn) } } private fun setButtonText(prefs: Prefs, button: MaterialButton) { button.text = when(prefs.maxCrashLogs) { 0 -> getString(R.string.feedback_limit_0) 1 -> getString(R.string.feedback_limit_1) 2 -> getString(R.string.feedback_limit_2) 3 -> getString(R.string.feedback_limit_3) else -> getString(R.string.feedback_limit_0) } } private fun enterAnimation(exit: Boolean) { if (!PREFS.isTransitionAnimEnabled) { return } val main = binding.root val animatorSet = AnimatorSet().apply { playTogether( createObjectAnimator(main, "translationX", if (exit) 0f else -300f, if (exit) -300f else 0f), createObjectAnimator(main, "rotationY", if (exit) 0f else 90f, if (exit) 90f else 0f), createObjectAnimator(main, "alpha", if (exit) 1f else 0f, if (exit) 0f else 1f), createObjectAnimator(main, "scaleX", if (exit) 1f else 0.5f, if (exit) 0.5f else 1f), createObjectAnimator(main, "scaleY", if (exit) 1f else 0.5f, if (exit) 0.5f else 1f) ) duration = 400 } animatorSet.start() } private fun createObjectAnimator(target: Any, property: String, startValue: Float, endValue: Float): ObjectAnimator { return ObjectAnimator.ofFloat(target, property, startValue, endValue) } override fun onResume() { enterAnimation(false) super.onResume() } override fun onPause() { enterAnimation(true) super.onPause() } }
3
null
2
49
205fa08e183c60986f99c093142101801cd6c912
5,143
MetroPhoneLauncher
MIT License
app/src/main/java/com/mbobiosio/rickandmorty/presentation/MainActivity.kt
mbobiosio
490,827,613
false
null
package com.mbobiosio.rickandmorty.presentation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.NavigationUI.setupActionBarWithNavController import com.mbobiosio.rickandmorty.R import com.mbobiosio.rickandmorty.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var navigationController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) navigationController = findNavController(R.id.fragment) setupActionBarWithNavController(this, navigationController) } override fun onSupportNavigateUp(): Boolean { return navigationController.navigateUp() } }
0
Kotlin
1
2
d88c43ecb806ddff4a914f9a8e365b4b2f256a18
1,102
RickAndMorty-GraphQL
Apache License 2.0
app/src/main/java/com/mertyazi/footballapp/shared/business/mapper/MatcheEntityToMatcheMapper.kt
MertYazi
611,202,935
false
null
package com.mertyazi.footballapp.shared.business.mapper import com.mertyazi.footballapp.shared.business.entities.* import com.mertyazi.footballapp.shared.data.entities.MatcheEntity import javax.inject.Inject class MatcheEntityToMatcheMapper @Inject constructor( ): Function1<MatcheEntity, Matche> { override fun invoke(matcheEntity: MatcheEntity): Matche { return Matche( AwayTeam( matcheEntity.awayTeam.crest, matcheEntity.awayTeam.id, matcheEntity.awayTeam.name, matcheEntity.awayTeam.shortName, matcheEntity.awayTeam.tla ), Competition( matcheEntity.competition.code, matcheEntity.competition.emblem, matcheEntity.competition.id, matcheEntity.competition.name, matcheEntity.competition.type ), HomeTeam( matcheEntity.homeTeam.crest, matcheEntity.homeTeam.id, matcheEntity.homeTeam.name, matcheEntity.homeTeam.shortName, matcheEntity.homeTeam.tla ), matcheEntity.id, matcheEntity.minute, ScoreX( matcheEntity.score.duration, FullTime( matcheEntity.score.fullTime.away, matcheEntity.score.fullTime.home ), HalfTime( matcheEntity.score.halfTime.away, matcheEntity.score.halfTime.home ), matcheEntity.score.winner ), matcheEntity.status, matcheEntity.utcDate ) } }
0
Kotlin
1
2
fea929e882684ba5760555d1cc125a5e175583d7
1,750
FootballApp
Apache License 2.0
common/sdk/auth/impl/src/commonMain/kotlin/io/chefbook/sdk/auth/impl/domain/usecases/ActivateProfileUseCaseImpl.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.sdk.auth.impl.domain.usecases import io.chefbook.sdk.auth.api.external.domain.usecases.ActivateProfileUseCase import io.chefbook.sdk.auth.api.internal.data.repositories.AuthRepository internal class ActivateProfileUseCaseImpl( private val authRepository: AuthRepository, ) : ActivateProfileUseCase { override suspend operator fun invoke(userId: String, code: String) = authRepository.activateProfile(userId, code) }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
447
chefbook-mobile
Apache License 2.0
core/src/main/kotlin/com/legacycode/cardbox/ClassFilesLocationUseCase.kt
LegacyCodeHQ
381,005,632
false
{"Kotlin": 39663, "Java": 116, "Shell": 94}
package com.legacycode.cardbox import com.legacycode.cardbox.model.ClassFilesLocation import com.legacycode.cardbox.model.Project import com.legacycode.cardbox.model.RelativePath /** * Given a directory that contains compiled .class files, the use case returns the original directory and the package * name of the classes present inside the directory. */ class ClassFilesLocationUseCase { companion object { private const val CLASS_FILE_EXTENSION = "class" } private val packageNameFromClassUseCase = PackageNameFromClassUseCase() fun invoke(project: Project, classFilesPath: RelativePath): ClassFilesLocation { val firstClassFile = project.resolve(classFilesPath).listFiles()!! .first { it.isFile && it.extension == CLASS_FILE_EXTENSION } return ClassFilesLocation( classFilesPath, packageNameFromClassUseCase.invoke(firstClassFile.inputStream()) ) } }
0
Kotlin
0
3
523268fc6ca9a8155b8c1071fb8a24432a34117e
905
cardbox
Apache License 2.0
foundation-generator/src/main/kotlin/net/ntworld/foundation/generator/main/ContractExtensionMainGenerator.kt
nhat-phan
201,625,092
false
null
package net.ntworld.foundation.generator.main import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import net.ntworld.foundation.generator.setting.ContractSetting import net.ntworld.foundation.generator.type.ClassInfo import net.ntworld.foundation.generator.type.Property internal object ContractExtensionMainGenerator { fun generate( setting: ContractSetting, properties: Map<String, Property>, implementation: ClassInfo, file: FileSpec.Builder ) { val make = FunSpec.builder("make") make .receiver(setting.contract.toCompanionClassName()) .returns(setting.contract.toClassName()) val notImplementedProperties = properties.filter { !it.value.hasBody } notImplementedProperties.forEach { (name, property) -> make.addParameter(name, property.type) } val code = CodeBlock.builder() code.add("return %T(\n", implementation.toClassName()) code.indent() val lastIndex = notImplementedProperties.values.size - 1 notImplementedProperties.values.forEachIndexed { index, property -> code.add("%L = %L", property.name, property.name) if (index != lastIndex) { code.add(",") } code.add("\n") } code.unindent() code.add(")\n") make.addCode(code.build()) file.addFunction(make.build()) } }
0
Kotlin
3
3
2fd4b0f0a4966e3aa687f7108d3b0a1cb800c6be
1,515
foundation
MIT License
rubik/rubik_publish/src/main/java/com/rubik/publish/task/component/ComponentTaskGraphic.kt
baidu
504,447,693
false
{"Kotlin": 607049, "Java": 37304}
package com.rubik.publish.task.component import com.ktnail.gradle.task.TaskGraphic import com.rubik.publish.task.PublishContextTask /** * Task graphic of business code of contexts, * graph publish tasks. * * @since 1.9 */ class ComponentTaskGraphic( componentTask: ComponentTask ) : TaskGraphic() { init { whenGraph { componentTask.variantTasks.fold<PublishContextTask,PublishContextTask>(componentTask) { acc, task -> task.apply { acc.linkExecuteDependsOn(this) } } } } }
1
Kotlin
7
153
065ba8f4652b39ff558a5e3f18b9893e2cf9bd25
583
Rubik
Apache License 2.0
common/src/iosMain/kotlin/dev/zwander/common/util/BugsnagUtils.kt
zacharee
641,202,797
false
{"Kotlin": 486543, "Swift": 10893, "Ruby": 2889, "Objective-C": 1853, "Shell": 470}
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package dev.zwander.common.util import com.rickclephas.kmp.nsexceptionkt.bugsnag.cinterop.Bugsnag import com.rickclephas.kmp.nsexceptionkt.core.InternalNSExceptionKtApi import com.rickclephas.kmp.nsexceptionkt.core.asNSException import dev.zwander.bugsnag.cinterop.BSGBreadcrumbType actual object BugsnagUtils { @OptIn(InternalNSExceptionKtApi::class) actual fun notify(e: Throwable) { Bugsnag.notify(e.asNSException(true)) { true } } actual fun addBreadcrumb( message: String, data: Map<String?, Any?>, ) { dev.zwander.bugsnag.cinterop.Bugsnag.leaveBreadcrumbWithMessage( message, data.mapKeys { it.key }, BSGBreadcrumbType.BSGBreadcrumbTypeRequest, ) } }
16
Kotlin
6
128
9831b251107deea7aaee1a709750b0754d5075c3
820
ArcadyanKVD21Control
MIT License
locationpicker/src/main/java/com/nmssalman/locationpicker/geocoder/adapters/DefaultSuggestionAdapter.kt
nmssalman
853,192,031
false
{"Kotlin": 123342}
package com.nmssalman.locationpicker.geocoder.adapters import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import com.nmssalman.locationpicker.LekuViewHolder import com.nmssalman.locationpicker.R import com.nmssalman.locationpicker.geocoder.adapters.type.AddressSearchAdapter import com.nmssalman.locationpicker.getFullAddressString class SearchViewHolder( val textView: TextView, ) : LekuViewHolder(textView) class DefaultAddressAdapter( val context: Context, ) : AddressSearchAdapter<SearchViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): SearchViewHolder { val view = LayoutInflater .from(parent.context) .inflate( R.layout.leku_search_list_item, parent, false ) as TextView return SearchViewHolder(view) } override fun onBindViewHolder(holder: SearchViewHolder, position: Int) { super.onBindViewHolder(holder, position) if (items.isNotEmpty()) { holder.textView.text = items[position].getFullAddressString(context) } } }
0
Kotlin
0
0
c4dacf87c31419d79e7170d2569ad71e09ec0b22
1,221
LocationPicker
Apache License 2.0
app/src/main/java/lab/maxb/dark/presentation/components/LoadingComponent.kt
MaxBQb
408,174,279
false
null
package lab.maxb.dark.presentation.components import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import lab.maxb.dark.presentation.extra.Result import lab.maxb.dark.presentation.extra.asString import lab.maxb.dark.presentation.extra.uiTextOf import lab.maxb.dark.ui.theme.DarkAppTheme import lab.maxb.dark.ui.theme.spacing @Composable fun <T> LoadingComponent( result: Result<T>, onLoading: @Composable () -> Unit = { LoadingScreen(true) }, onError: @Composable (Result.Error) -> Unit = { DefaultOnLoadingError(it) }, content: @Composable (T) -> Unit = {}, ) = when(result) { is Result.Loading -> onLoading() is Result.Error -> AnimateAppearance { onError(result) } is Result.Success<T> -> AnimateAppearance( enter = fadeIn(), exit = fadeOut(), ) { content(result.value) } } @Composable fun DefaultOnLoadingError(result: Result.Error) { Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { LoadingError( Modifier .fillMaxSize(0.5f) .padding(MaterialTheme.spacing.extraSmall) ) Text(text = result.message.asString()) } } @Preview @Composable private fun Success() = DarkAppTheme { Surface { LoadingComponent(result = Result.Success("Hello")) { Text(it) } } } @Preview @Composable private fun Loading() = DarkAppTheme { Surface { LoadingComponent<String>(result = Result.Loading) { Text(it) } } } @Preview @Composable private fun Error() = DarkAppTheme { Surface { LoadingComponent<String>( result = Result.Error( null, uiTextOf("Some error occurred") ) ) { Text(it) } } }
0
Kotlin
0
3
15885b8ec13bc58d78c14a69e1c2f06f84ca4380
2,422
TheDarkApp.Client
MIT License
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/protocol/mycelium/TcrRewardsProvider.kt
decentri-fi
426,174,152
false
{"Kotlin": 1193627, "Java": 1948, "Dockerfile": 909}
package io.defitrack.protocol.mycelium import arrow.core.nonEmptyListOf import io.defitrack.claimable.domain.ClaimableRewardFetcher import io.defitrack.claimable.domain.Reward import io.defitrack.common.network.Network import io.defitrack.conditional.ConditionalOnCompany import io.defitrack.evm.contract.ERC20Contract import io.defitrack.exit.ExitPositionCommand import io.defitrack.exit.ExitPositionPreparer import io.defitrack.market.farming.FarmingMarketProvider import io.defitrack.market.farming.domain.FarmingMarket import io.defitrack.market.position.PositionFetcher import io.defitrack.protocol.Company import io.defitrack.protocol.Protocol import io.defitrack.transaction.PreparedTransaction import io.defitrack.transaction.PreparedTransaction.Companion.selfExecutingTransaction import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import org.springframework.stereotype.Component @Component @ConditionalOnCompany(Company.MYCELIUM) class TcrRewardsProvider : FarmingMarketProvider() { override suspend fun produceMarkets(): Flow<FarmingMarket> = channelFlow { val contract = TcrStakingRewards( getBlockchainGateway(), "0xa18413dc5506a91138e0604c283e36b021b8849b" ) val stakingToken = getToken(contract.stakingToken.await()) val rewardToken = getToken(contract.rewardsToken.await()) send( create( "Tcr Staking Rewards", identifier = "tcr staking rewards", stakedToken = stakingToken, rewardTokens = nonEmptyListOf(rewardToken), positionFetcher = defaultPositionFetcher(contract.address), exitPositionPreparer = object : ExitPositionPreparer() { override suspend fun getExitPositionCommand(exitPositionCommand: ExitPositionCommand): Deferred<PreparedTransaction> = coroutineScope { async { selfExecutingTransaction(contract::exitFn).invoke(exitPositionCommand.user) } } override fun getNetwork(): Network { return Network.ARBITRUM } } ) ) } override fun getProtocol(): Protocol { return Protocol.MYCELIUM } override fun getNetwork(): Network { return Network.ARBITRUM } }
53
Kotlin
6
10
bff3e341dc55b4b1cc88d5b1e813779fe1303187
2,577
defi-hub
MIT License
app/src/main/java/com/ihsanproject/client/application/viewmodels/LaunchViewModel.kt
ihsan-project
184,511,711
false
null
package com.ihsanproject.client.application.viewmodels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.ihsanproject.client.domain.interactors.StateInteractor import com.ihsanproject.client.domain.models.SettingsModel import com.ihsanproject.client.domain.repositories.ProfileRepository import com.ihsanproject.client.domain.repositories.SettingsRepository class LaunchViewModelFactory( val activity: AppCompatActivity, val settingsRepository: SettingsRepository, val profileRepository: ProfileRepository ): ViewModelProvider.Factory { override fun <T: ViewModel> create(modelClass:Class<T>): T = modelClass.getConstructor( AppCompatActivity::class.java, SettingsRepository::class.java, ProfileRepository::class.java ).newInstance(activity, settingsRepository, profileRepository) } interface LaunchViewModelDelegate { suspend fun setAuthToken(token: String?) } class LaunchViewModel(val activity: AppCompatActivity, val settingsRepository: SettingsRepository, val profileRepository: ProfileRepository) : ViewModelBase() { var delegate: LaunchViewModelDelegate? = null private val stateInteractor = StateInteractor(settingsRepository, profileRepository) suspend fun syncSettings() : SettingsModel? { return stateInteractor.syncSettingsAsync().await() } suspend fun isLoggedIn() : Boolean { return stateInteractor.loginState.await() } suspend fun syncLoggedInAuth() { stateInteractor.loggedInUser.await()?.let { delegate?.setAuthToken(it.access) } } }
12
Kotlin
1
0
554cefd67c3e6e9d6a19282c48869b447861db69
1,739
ihsan-android
Apache License 2.0
backend/src/main/kotlin/com/planetsf/clubhouse/controller/UsersController.kt
mrmaandi
322,327,619
false
{"TypeScript": 91813, "Kotlin": 15024, "SCSS": 5468, "JavaScript": 3595, "Less": 893, "HTML": 687, "Dockerfile": 172}
package com.planetsf.clubhouse.controller import com.planetsf.clubhouse.dto.UserDto import com.planetsf.clubhouse.service.UsersService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("users") class UsersController(private val usersService: UsersService) { @GetMapping fun getUsers(): List<UserDto> { return usersService.getUsers() } }
0
TypeScript
0
1
efa9045dfaf12c3752d19bfea3a18693cdaef2aa
524
clubhouse
MIT License
src/es/tenkaiscan/src/eu/kanade/tachiyomi/extension/es/tenkaiscan/TenkaiScan.kt
komikku-app
720,497,299
false
{"Kotlin": 6775539, "JavaScript": 2160}
package eu.kanade.tachiyomi.extension.es.tenkaiscan import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.interceptor.rateLimitHost import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.select.Elements import java.text.SimpleDateFormat import java.util.Locale class TenkaiScan : ParsedHttpSource() { // Site change theme from Madara to custom theme override val versionId = 3 override val name = "TenkaiScan" override val baseUrl = "https://tenkaiscan.net" override val lang = "es" override val supportsLatest = true private val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale("es")) override val client = network.cloudflareClient.newBuilder() .rateLimitHost(baseUrl.toHttpUrl(), 3) .build() override fun headersBuilder() = super.headersBuilder() .add("Referer", "$baseUrl/") override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/ranking", headers) override fun popularMangaNextPageSelector(): String? = null override fun popularMangaSelector(): String = "section.trending div.row div.card" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { setUrlWithoutDomain( element.attr("onclick") .substringAfter("window.location.href='") .substringBefore("'"), ) title = element.selectFirst("div.name > h4.color-white")!!.text() thumbnail_url = element.select("img").imgAttr() } override fun latestUpdatesRequest(page: Int): Request = GET(baseUrl, headers) override fun latestUpdatesNextPageSelector(): String? = null override fun latestUpdatesSelector(): String = "section.trending div.row a" override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply { setUrlWithoutDomain(element.attr("href")) title = element.selectFirst("div.content > h4.color-white")!!.text() thumbnail_url = element.select("img").imgAttr() } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val urlBuilder = "$baseUrl/comics".toHttpUrl().newBuilder() if (query.isNotBlank()) { urlBuilder.addQueryParameter("search", query) return GET(urlBuilder.build(), headers) } else { for (filter in filters) { when (filter) { is AlphabeticFilter -> { if (filter.state != 0) { urlBuilder.addQueryParameter("filter", filter.toUriPart()) break } } is GenreFilter -> { if (filter.state != 0) { urlBuilder.addQueryParameter("gen", filter.toUriPart()) break } } is StatusFilter -> { if (filter.state != 0) { urlBuilder.addQueryParameter("status", filter.toUriPart()) break } } else -> {} } } } return GET(urlBuilder.build(), headers) } override fun searchMangaNextPageSelector(): String? = null override fun searchMangaSelector(): String = "section.trending div.row > div.col-xxl-9 > div.row > div > a" override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { setUrlWithoutDomain(element.attr("href")) title = element.selectFirst("div.content > h4.color-white")!!.text() thumbnail_url = element.select("img").imgAttr() } override fun getFilterList(): FilterList = FilterList( Filter.Header("NOTA: Los filtros serán ignorados si se realiza una búsqueda por texto."), Filter.Header("Solo se puede aplicar un filtro a la vez."), AlphabeticFilter(), GenreFilter(), StatusFilter(), ) override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { document.selectFirst("div.page-content div.text-details")!!.let { element -> title = element.selectFirst("div.name-rating")!!.text() description = element.select("p.sec:not(div.soft-details p)").text() thumbnail_url = element.selectFirst("img.img-details")!!.imgAttr() element.selectFirst("div.soft-details")?.let { details -> author = details.selectFirst("p:has(span:contains(Autor))")!!.ownText() artist = details.selectFirst("p:has(span:contains(Artista))")!!.ownText() status = details.selectFirst("p:has(span:contains(Status))")!!.ownText().parseStatus() genre = details.selectFirst("p:has(span:contains(Generos))")!!.ownText() } } } override fun chapterListSelector(): String = "div.page-content div.card-caps" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { setUrlWithoutDomain( element.attr("onclick") .substringAfter("window.location.href='") .substringBefore("'"), ) name = element.selectFirst("div.text-cap span.color-white")!!.text() date_upload = try { element.selectFirst("div.text-cap span.color-medium-gray")?.text()?.let { dateFormat.parse(it)?.time ?: 0 } ?: 0 } catch (_: Exception) { 0 } } override fun pageListParse(document: Document): List<Page> { return document.select("div.page-content div.img-blade img").mapIndexed { i, element -> Page(i, imageUrl = element.imgAttr()) } } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException() private class AlphabeticFilter : UriPartFilter( "Ordenar por", arrayOf( Pair("<Seleccionar>", ""), Pair("A", "a"), Pair("B", "b"), Pair("C", "c"), Pair("D", "d"), Pair("E", "e"), Pair("F", "f"), Pair("G", "g"), Pair("H", "h"), Pair("I", "i"), Pair("J", "j"), Pair("K", "k"), Pair("L", "l"), Pair("M", "m"), Pair("N", "n"), Pair("O", "o"), Pair("P", "p"), Pair("Q", "q"), Pair("R", "r"), Pair("S", "s"), Pair("T", "t"), Pair("U", "u"), Pair("V", "v"), Pair("W", "w"), Pair("X", "x"), Pair("Y", "y"), Pair("Z", "z"), ), ) private class GenreFilter : UriPartFilter( "Género", arrayOf( Pair("<Seleccionar>", ""), Pair("Adaptación de Novela", "Adaptación de Novela"), Pair("Aventuras", "Aventuras"), Pair("Bondage", "Bondage"), Pair("Comedia", "Comedia"), Pair("Drama", "Drama"), Pair("Ecchi", "Ecchi"), Pair("Escolar", "Escolar"), Pair("Fantasía", "Fantasía"), Pair("Hardcore", "Hardcore"), Pair("Harem", "Harem"), Pair("Isekai", "Isekai"), Pair("MILF", "MILF"), Pair("Netorare", "Netorare"), Pair("Novela", "Novela"), Pair("Recuentos de la vida", "Recuentos de la vida"), Pair("Romance", "Romance"), Pair("Seinen", "Seinen"), Pair("Sistemas", "Sistemas"), Pair("Venganza", "Venganza"), ), ) private class StatusFilter : UriPartFilter( "Status", arrayOf( Pair("Completed", "Completed"), Pair("En Libertad", "En Libertad"), Pair("Canceled", "Canceled"), ), ) private fun Elements.imgAttr(): String = this.first()!!.imgAttr() private fun Element.imgAttr(): String = when { this.hasAttr("data-src") -> this.absUrl("data-src") else -> this.absUrl("src") } private fun String.parseStatus() = when (this.lowercase()) { "en emisión" -> SManga.ONGOING "finalizado" -> SManga.COMPLETED "cancelado" -> SManga.CANCELLED "en espera" -> SManga.ON_HIATUS else -> SManga.UNKNOWN } private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
22
Kotlin
8
97
7fc1d11ee314376fe0daa87755a7590a03bc11c0
9,131
komikku-extensions
Apache License 2.0
device/src/main/java/CoroutinesGattDevice.kt
jessecollier
238,049,769
true
{"Kotlin": 90026, "Shell": 1030}
/* * Copyright 2018 JUUL Labs, Inc. */ package com.juul.able.experimental.device import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService import android.bluetooth.BluetoothProfile import android.content.Context import com.juul.able.experimental.Able import com.juul.able.experimental.ConnectGattResult import com.juul.able.experimental.Gatt import com.juul.able.experimental.GattState import com.juul.able.experimental.GattStatus import com.juul.able.experimental.WriteType import com.juul.able.experimental.android.connectGatt import com.juul.able.experimental.messenger.GattCallbackConfig import com.juul.able.experimental.messenger.OnCharacteristicChanged import com.juul.able.experimental.messenger.OnCharacteristicRead import com.juul.able.experimental.messenger.OnCharacteristicWrite import com.juul.able.experimental.messenger.OnConnectionStateChange import com.juul.able.experimental.messenger.OnDescriptorWrite import com.juul.able.experimental.messenger.OnMtuChanged import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.util.UUID import java.util.concurrent.atomic.AtomicInteger import kotlin.coroutines.CoroutineContext class GattUnavailable(message: String) : IllegalStateException(message) class CoroutinesGattDevice internal constructor( private val bluetoothDevice: BluetoothDevice ) : Gatt, CoroutineScope { /* * Constructor must **not** have side-effects as we're relying on `ConcurrentMap<K, V>.getOrPut` * in `DeviceManager.wrapped` which uses `putIfAbsent` as an alternative to `computeIfAbsent` * (`computeIfAbsent` is only available on API >= 24). * * As stated in [Equivalent of ComputeIfAbsent in Java 7](https://stackoverflow.com/a/40665232): * * > This is pretty much functionally equivalent the `computeIfAbsent` call in Java 8, with the * > only difference being that sometimes you construct a `Value` object that never makes it * > into the map - because another thread put it in first. It never results in returning the * > wrong object or anything like that - the function consistently returns the right `Value` no * > matter what, but _if the construction of `Value` has side-effects*_, this may not be * > acceptable. */ private val job = Job() override val coroutineContext: CoroutineContext get() = job private val connectMutex = Mutex() private var connectDeferred: Deferred<ConnectGattResult>? = null private var _gatt: Gatt? = null private val gatt: Gatt get() = _gatt ?: throw GattUnavailable("Gatt unavailable for bluetooth device $bluetoothDevice") private val _connectionState = AtomicInteger() fun getConnectionState(): GattState = _connectionState.get() private var eventJob = Job(job) set(value) { // Prevent runaways: cancel the previous Job that we are loosing a reference to. field.cancel() field = value } /** * Scopes forwarding events to (i.e. the following `Channel`s are consumed under this scope): * * - [onConnectionStateChange] * - [onCharacteristicChanged] * * @see createConnection */ private val eventCoroutineScope get() = CoroutineScope(eventJob) override val onConnectionStateChange = BroadcastChannel<OnConnectionStateChange>(CONFLATED) override val onCharacteristicChanged = BroadcastChannel<OnCharacteristicChanged>(1) fun isConnected(): Boolean = _gatt != null && getConnectionState() == BluetoothProfile.STATE_CONNECTED suspend fun connect( context: Context, autoConnect: Boolean, callbackConfig: GattCallbackConfig ): ConnectGattResult { Able.verbose { "Connection requested to bluetooth device $bluetoothDevice" } val result = connectMutex.withLock { connectDeferred ?: createConnection(context, autoConnect, callbackConfig).also { connectDeferred = it } }.await() Able.info { "connect ← result=$result" } return result } private suspend fun cancelConnect() = connectMutex.withLock { connectDeferred?.cancel() ?: Able.verbose { "No connection to cancel for bluetooth device $bluetoothDevice" } connectDeferred = null } private fun createConnection( context: Context, autoConnect: Boolean, callbackConfig: GattCallbackConfig ): Deferred<ConnectGattResult> = async { Able.info { "Creating connection for bluetooth device $bluetoothDevice" } val result = bluetoothDevice.connectGatt(context, autoConnect, callbackConfig) if (result is ConnectGattResult.Success) { val newGatt = result.gatt _gatt = newGatt eventJob = Job(job) // Prepare event Coroutine scope. eventCoroutineScope.launch { Able.verbose { "onConnectionStateChange → $bluetoothDevice → Begin" } newGatt.onConnectionStateChange.consumeEach { if (it.status == BluetoothGatt.GATT_SUCCESS) { _connectionState.set(it.newState) } Able.verbose { "Forwarding $it for $bluetoothDevice" } onConnectionStateChange.send(it) } Able.verbose { "onConnectionStateChange ← $bluetoothDevice ← End" } }.invokeOnCompletion { Able.verbose { "onConnectionStateChange for $bluetoothDevice completed, cause=$it" } } eventCoroutineScope.launch { Able.verbose { "onCharacteristicChanged → $bluetoothDevice → Begin" } newGatt.onCharacteristicChanged.consumeEach { Able.verbose { "Forwarding $it for $bluetoothDevice" } onCharacteristicChanged.send(it) } Able.verbose { "onCharacteristicChanged ← $bluetoothDevice ← End" } }.invokeOnCompletion { Able.verbose { "onCharacteristicChanged for $bluetoothDevice completed, cause=$it" } } ConnectGattResult.Success(this@CoroutinesGattDevice) } else { result } } override val services: List<BluetoothGattService> get() = gatt.services override fun requestConnect(): Boolean = gatt.requestConnect() override fun requestDisconnect(): Unit = gatt.requestDisconnect() override fun getService(uuid: UUID): BluetoothGattService? = gatt.getService(uuid) override suspend fun connect(): Boolean = gatt.connect() override suspend fun disconnect() { cancelConnect() Able.verbose { "Disconnecting from bluetooth device $bluetoothDevice" } _gatt?.disconnect() ?: Able.warn { "Unable to disconnect from bluetooth device $bluetoothDevice" } eventJob.cancel() } override fun close() { Able.verbose { "close → Begin" } runBlocking { cancelConnect() } eventJob.cancel() Able.debug { "close → Closing bluetooth device $bluetoothDevice" } _gatt?.close() _gatt = null Able.verbose { "close ← End" } } internal fun dispose() { Able.verbose { "dispose → Begin" } job.cancel() _gatt?.close() Able.verbose { "dispose ← End" } } override suspend fun discoverServices(): GattStatus = gatt.discoverServices() override suspend fun readCharacteristic( characteristic: BluetoothGattCharacteristic ): OnCharacteristicRead = gatt.readCharacteristic(characteristic) override suspend fun writeCharacteristic( characteristic: BluetoothGattCharacteristic, value: ByteArray, writeType: WriteType ): OnCharacteristicWrite = gatt.writeCharacteristic(characteristic, value, writeType) override suspend fun writeDescriptor( descriptor: BluetoothGattDescriptor, value: ByteArray ): OnDescriptorWrite = gatt.writeDescriptor(descriptor, value) override suspend fun requestMtu(mtu: Int): OnMtuChanged = gatt.requestMtu(mtu) override fun setCharacteristicNotification( characteristic: BluetoothGattCharacteristic, enable: Boolean ): Boolean = gatt.setCharacteristicNotification(characteristic, enable) override fun toString(): String = "CoroutinesGattDevice(bluetoothDevice=$bluetoothDevice, state=${getConnectionState()})" }
0
null
0
0
2b16c54d6aaa5a93cc9890c41e36264bbc0323a1
9,094
able
Apache License 2.0
app/src/main/java/com/javernaut/whatthecodec/home/data/model/AudioStreamFeature.kt
Javernaut
174,843,727
false
{"Kotlin": 132393, "Ruby": 1066, "Shell": 852}
package com.javernaut.whatthecodec.home.data.model import androidx.annotation.Keep @Keep enum class AudioStreamFeature { Codec, Bitrate, Channels, ChannelLayout, SampleFormat, SampleRate, Language, Disposition }
4
Kotlin
15
70
e468e02bb7cc5cf0f947a851442026c212697aec
246
WhatTheCodec
MIT License
backend/data/src/main/kotlin/io/tolgee/socketio/ITranslationsSocketIoModule.kt
tolgee
303,766,501
false
null
package io.tolgee.socketio import io.tolgee.model.key.Key import io.tolgee.model.translation.Translation interface ITranslationsSocketIoModule { fun onKeyCreated(key: Key) fun onKeyModified(key: Key, oldName: String) fun onKeyDeleted(key: Key) fun onKeyChange(key: Key, event: io.tolgee.socketio.TranslationEvent) fun onTranslationsCreated(translations: Collection<Translation>) fun onTranslationsModified(translations: Collection<Translation>) fun onTranslationsDeleted(translations: Collection<Translation>) fun onTranslationsChange(translations: Collection<Translation>, event: io.tolgee.socketio.TranslationEvent) }
50
Kotlin
15
292
9896609f260b1ff073134e672303ff8810afc5a1
638
server
Apache License 2.0
app/src/main/java/com/example/android/architecture/blueprints/randomuser/di/UserListModule.kt
viktor1190
263,158,056
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.randomuser.di import androidx.lifecycle.ViewModel import com.example.android.architecture.blueprints.randomuser.users.UserListFragment import com.example.android.architecture.blueprints.randomuser.users.UserListViewModel import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap /** * Dagger module for the users list feature. */ @Module abstract class UserListModule { @ContributesAndroidInjector(modules = [ ViewModelBuilder::class ]) internal abstract fun userListFragment(): UserListFragment @Binds @IntoMap @ViewModelKey(UserListViewModel::class) abstract fun bindViewModel(viewModel: UserListViewModel): ViewModel }
0
Kotlin
0
0
f7041bb348a5e55d47f744a9949b6086eb94e411
1,409
random_users_android
Apache License 2.0
app/src/main/java/cc/bear3/osbear/data/NoticeResponse.kt
ttzt777
267,602,924
false
null
package cc.bear3.osbear.data import cc.bear3.osbear.http.BaseResponse /** * Description: * Author: TT * Since: 2020-03-21 */ open class NoticeResponse : BaseResponse() { val notice: NoticeData? = null }
0
Kotlin
0
0
643f03b8c9c8db4214cdca2862a12aff90087235
212
Android-OpenSourceBear
Apache License 2.0
metis-lang/src/main/kotlin/io/github/seggan/metis/parsing/CodeSource.kt
Seggan
688,714,099
false
{"Kotlin": 167269}
package io.github.seggan.metis.parsing import java.lang.ref.WeakReference import java.nio.file.Path import kotlin.io.path.readText /** * Represents a place where source code can be retrieved from. * * @property name The name of the source. * @property textGetter A function that retrieves the source code from the name. */ class CodeSource(val name: String, private val textGetter: (String) -> String) { private var textRef: WeakReference<String> = WeakReference(null) /** * The source code. It is backed by a [WeakReference] so it does not take up memory if it is not used. */ val text: String get() = textRef.get() ?: textGetter(name).also { textRef = WeakReference(it) } override fun equals(other: Any?) = other is CodeSource && other.name == name override fun hashCode() = name.hashCode() override fun toString() = "FileInfo($name)" fun mapText(transform: (String) -> String) = CodeSource(name) { transform(textGetter(it)) } companion object { /** * Creates a [CodeSource] from a string. * * @param name The name of the source. * @param text The source code. * @return The created [CodeSource]. */ fun constant(name: String, text: String) = CodeSource(name) { text } /** * Creates a [CodeSource] from a [Path]. Will use the base filename as the name. * * @param path The path to the source. * @return The created [CodeSource]. */ fun fromPath(path: Path) = CodeSource(path.fileName.toString()) { path.readText() } } }
2
Kotlin
1
8
ccded7309a27caf0fa1f0097018ce9c82af7fe2f
1,622
metis
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/MpOutlined.kt
karakum-team
387,062,541
false
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/MpOutlined") package mui.icons.material @JsName("default") external val MpOutlined: SvgIconComponent
1
Kotlin
5
35
eb68a042133a7d025aef8450151ee0150cbc9b1b
184
mui-kotlin
Apache License 2.0
app/src/main/java/com/sunit/news/network/di/NetworkModule.kt
sunit1999
700,788,216
false
{"Kotlin": 99427}
package com.sunit.news.network.di import android.content.Context import com.google.gson.Gson import com.sunit.news.BuildConfig import com.sunit.news.network.NetworkMonitor import com.sunit.news.network.NetworkMonitorImpl import com.sunit.news.network.RetrofitApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.Call import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideGsonConverterFactory(): GsonConverterFactory { return GsonConverterFactory.create() } @Provides @Singleton fun provideGson() = Gson() @Provides @Singleton fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().apply { if (BuildConfig.DEBUG) { setLevel(HttpLoggingInterceptor.Level.BODY) } } } @Provides @Singleton fun provideOkHttpCallFactory( httpLoggingInterceptor: HttpLoggingInterceptor ): Call.Factory { return OkHttpClient.Builder() .addInterceptor { chain -> val request = chain.request() .newBuilder() .addHeader("X-Api-Key", BuildConfig.API_KEY) .build() chain.proceed(request) } .addInterceptor(httpLoggingInterceptor) .build() } @Provides @Singleton fun provideNetworkApi( gsonConverterFactory: GsonConverterFactory, okHttpCallFactory: Call.Factory ): RetrofitApi { return Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL) .addConverterFactory(gsonConverterFactory) .callFactory(okHttpCallFactory) .build() .create(RetrofitApi::class.java) } @Provides @Singleton fun provideNetworkMonitor( @ApplicationContext context: Context ): NetworkMonitor { return NetworkMonitorImpl(context) } }
0
Kotlin
0
0
82c365dfd5598883de7730e03fa774481a37a12d
2,315
News
Apache License 2.0
hex-rules/src/main/kotlin/hex/HexPlayer.kt
krasnoludkolo
265,339,358
false
null
package hex sealed class HexPlayer { fun nextPlayer() = if (this is RedHexPlayer) BlueHexPlayer else RedHexPlayer fun getPiece() = if (this is RedHexPlayer) RedPiece else BluePiece } object RedHexPlayer : HexPlayer() { override fun toString(): String { return "RED" } } object BlueHexPlayer : HexPlayer() { override fun toString(): String { return "BLUE" } }
0
Kotlin
0
0
97e136262f79c78aea0aabf4c7132b18da6f70bf
401
hex
MIT License
local/src/test/java/com/nimbusframework/nimbuslocal/exampleHandlers/ExampleQueueHandler.kt
ihsmarkitoss
230,110,781
true
{"Kotlin": 258342, "JavaScript": 71112, "CSS": 28446, "HTML": 3721, "Java": 2673}
package com.nimbusframework.nimbuslocal.exampleHandlers import com.nimbusframework.nimbuscore.annotations.function.QueueServerlessFunction import com.nimbusframework.nimbuscore.eventabstractions.QueueEvent import com.nimbusframework.nimbuslocal.exampleModels.KeyValue class ExampleQueueHandler { @QueueServerlessFunction(batchSize = 1, id = "BatchSize1") fun handle(house: KeyValue, queueEvent: QueueEvent): Boolean { return true } @QueueServerlessFunction(batchSize = 2, id = "BatchSize2Batch") fun handleBatchSize2Batched(house: List<KeyValue>, queueEvent: List<QueueEvent>): Boolean { if (queueEvent.isNotEmpty()) { val firstId = queueEvent.first().requestId queueEvent.forEach { assert(it.requestId == firstId) } } return true } @QueueServerlessFunction(batchSize = 2, id = "BatchSize2Individual") fun handleBatchSize2Individual(house: KeyValue, queueEvent: QueueEvent): Boolean { return true } }
0
null
0
0
9f54c7a04c3d71a417c4c5677d299be5e9dec7a0
1,033
nimbus-local
Apache License 2.0
core/src/main/kotlin/com/richodemus/syncheror/core/GcsToKafkaSyncer.kt
RichoDemus
107,732,630
false
null
package com.richodemus.syncheror.core import org.slf4j.LoggerFactory internal class GcsToKafkaSyncer { private val logger = LoggerFactory.getLogger(javaClass) private val googleCloudStoragePersistence = GoogleCloudStoragePersistence() internal fun syncGcsEventsToKafka(): Int { try { logger.info("Time to sync!") // todo use fancy coroutines to do these two in parallel! :D val eventsInKafka = topicToList() val eventsInGcs = googleCloudStoragePersistence.readEvents().asSequence().toList() logger.info("Got ${eventsInKafka.size} events from Kafka and ${eventsInGcs.size} events from GCS") Producer().use { producer -> IntRange(0, Math.max(eventsInKafka.size, eventsInGcs.size) - 1).forEach { i -> val kafkaEvent = eventsInKafka.getOrNull(i) val gcsEvent = eventsInGcs.getOrNull(i) // event is in gcs but not in kafka if (kafkaEvent == null) { logger.info("Adding missing event to kafka: $gcsEvent") producer.send(gcsEvent!!) } // event is in kafka but not in gcs if (gcsEvent == null) { logger.info("${kafkaEvent!!} missing from GCS") } // event is in both kafka and gcs if (gcsEvent != null && kafkaEvent != null) { if (gcsEvent != kafkaEvent) { val msg = "Event mismatch: $kafkaEvent, $gcsEvent" logger.warn(msg) throw IllegalStateException(msg) } } } } logger.info("Sync done") return eventsInGcs.size } catch (e: Exception) { throw IllegalStateException("Sync run failed", e) } } }
0
Kotlin
0
1
33572c30ef4b4e42b6e621e11cc481adf35efa4b
2,009
syncheror
Apache License 2.0
src/Day21.kt
sabercon
648,989,596
false
null
fun main() { fun buildIngredientAllergenMap(allergenIngredientMap: Map<String, Set<String>>): Map<String, String> { if (allergenIngredientMap.isEmpty()) return emptyMap() val (allergen, ingredients) = allergenIngredientMap.entries.first { it.value.size == 1 } val ingredient = ingredients.single() return allergenIngredientMap .minus(allergen) .mapValues { it.value - ingredient } .let { buildIngredientAllergenMap(it) } .plus(ingredient to allergen) } fun buildIngredientAllergenMap(input: List<Pair<List<String>, List<String>>>): Map<String, String> { return input.flatMap { (ingredients, allergens) -> allergens.map { it to ingredients.toSet() } } .groupBy({ it.first }, { it.second }) .mapValues { it.value.reduce { acc, set -> acc intersect set } } .let { buildIngredientAllergenMap(it) } } val input = readLines("Day21").map { val (ingredients, allergens) = it.split(" (contains ") ingredients.split(" ") to allergens.dropLast(1).split(", ") } val ingredientAllergenMap = buildIngredientAllergenMap(input) input.flatMap { it.first }.count { it !in ingredientAllergenMap }.println() ingredientAllergenMap.entries.sortedBy { it.value }.joinToString(",") { it.key }.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,362
advent-of-code-2020
MIT License
app/src/main/java/com/android/pokemon/view/MainActivity.kt
sahmanuela
731,364,455
false
{"Kotlin": 10553, "Java": 3356}
package com.android.pokemon.view import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.pokemon.R import com.android.pokemon.domain.Pokemon import com.android.pokemon.domain.PokemonType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.rvPokemons) val layoutManager = LinearLayoutManager(this) val charmander = Pokemon( "https://img.pokemondb.net/artwork/charmander.jpg", 1, "Charmander", listOf(PokemonType("Fire")) ) val togepi = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/175.png", 2, "Togepi", listOf(PokemonType("Fairy"), PokemonType("Flying")) ) val squirtle = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/007.png", 3, "Squirtle", listOf(PokemonType("Water")) ) val eevee = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/133.png", 4, "Eevee", listOf(PokemonType("Normal")) ) val vulpix = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/037.png", 5, "Vulpix", listOf(PokemonType("Fire"), PokemonType("Ice")) ) val jigglypuff = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/039.png", 6, "Jigglypuff", listOf(PokemonType("Fairy")) ) val snorlax = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png", 7, "Snorlax", listOf(PokemonType("Normal"), PokemonType("Fighting")) ) val meowth = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/052.png", 8, "Meowth", listOf(PokemonType("Normal")) ) val pikachu = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/025.png", 9, "Pikachu", listOf(PokemonType("Electric")) ) val mareep = Pokemon( "https://assets.pokemon.com/assets/cms2/img/pokedex/full/179.png", 3, "Mareep", listOf(PokemonType("Electric")) ) val pokemons = listOf(charmander, togepi, squirtle, eevee, vulpix, jigglypuff, snorlax, meowth, pikachu, mareep) // val pokemonsApi = PokemonRepository.listPokemons() // Log.d("POKEMON_API", pokemonsApi.toString()) //Funcionalidade botões recyclerView.layoutManager = layoutManager recyclerView.adapter = PokemonAdapter(pokemons) val presentationButton = findViewById<Button>(R.id.presentationButton) val preferences = getSharedPreferences(Constantes.PREFERENCES, 0) val retrievedNome = preferences.getString("nome", "") if (retrievedNome.isNullOrEmpty()) { presentationButton.text = "Cadastrar Usuário"; } else { presentationButton.text = "Hello $retrievedNome" } // Button: Redirect to profile page presentationButton.setOnClickListener { Log.d("MainActivity", "Botão clicado") val i = Intent(this, PerfilActivity::class.java) startActivity(i) } } }
0
Kotlin
0
1
0854f781a39e383c1c510c48e89230197233bca4
3,822
PokemonAndroid
MIT License
core/ui/src/main/java/com/anna/greeneats/core/ui/forms/button/CustomButtonColor.kt
AnnaL001
780,077,258
false
{"Kotlin": 144537}
package com.anna.greeneats.core.ui.forms.button import androidx.compose.ui.graphics.Color data class CustomButtonColor( val bgColor: Color ?= null, val contentColor: Color ?= null)
0
Kotlin
0
0
26bc175b6a1166c3b1f27d2f80f8ae9a4e00c3c1
187
greeneats
MIT License
common/src/main/kotlin/org/valkyrienskies/tournament/ship/SpinnerShipControl.kt
SuperCraftAlex
648,266,124
false
null
package org.valkyrienskies.tournament.ship import com.fasterxml.jackson.annotation.JsonAutoDetect import org.joml.Vector3d import org.joml.Vector3i import org.valkyrienskies.core.api.ships.PhysShip import org.valkyrienskies.core.api.ships.ServerShip import org.valkyrienskies.core.api.ships.getAttachment import org.valkyrienskies.core.api.ships.saveAttachment import org.valkyrienskies.core.impl.api.ShipForcesInducer import org.valkyrienskies.core.impl.game.ships.PhysShipImpl import org.valkyrienskies.tournament.TournamentConfig import java.util.concurrent.CopyOnWriteArrayList @JsonAutoDetect( fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE ) class SpinnerShipControl : ShipForcesInducer { private val spinners = CopyOnWriteArrayList<Pair<Vector3i, Vector3d>>() override fun applyForces(physShip: PhysShip) { physShip as PhysShipImpl spinners.forEach { val (_, torque) = it val torqueGlobal = physShip.transform.shipToWorldRotation.transform(torque, Vector3d()) physShip.applyInvariantTorque(torqueGlobal.mul(TournamentConfig.SERVER.spinnerSpeed)) } } fun addSpinner(pos: Vector3i, torque: Vector3d) { spinners.add(pos to torque) } fun removeSpinner(pos: Vector3i, torque: Vector3d) { spinners.remove(pos to torque) } companion object { fun getOrCreate(ship: ServerShip): SpinnerShipControl { return ship.getAttachment<SpinnerShipControl>() ?: SpinnerShipControl().also { ship.saveAttachment(it) } } } }
1
Kotlin
0
1
3ad78c29fd9667df807e8f9e3d9d63cb5a3be355
1,747
VS_tournament_continued
Apache License 2.0
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/PhotoSize.kt
ivan-osipov
92,181,671
false
null
package com.github.ivan_osipov.clabo.api.model import com.google.gson.annotations.SerializedName class PhotoSize : Identifiable() { @SerializedName("file_id") override lateinit var id: String @SerializedName("width") private var _width : Int? = null @SerializedName("height") private var _height : Int? = null val width: Int get() = _width!! val height: Int get() = _height!! @SerializedName("file_size") val fileSize : Long? = null }
31
Kotlin
3
6
943583bce73aad8479c1be8d7e6f6fe74807058e
498
Clabo
Apache License 2.0