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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
økonomi/presentation/src/test/kotlin/økonomi/presentation/api/ØkonomiRoutesKtTest.kt | navikt | 227,366,088 | false | {"Kotlin": 10069757, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209} | package økonomi.presentation.api
import arrow.core.left
import arrow.core.right
import io.kotest.matchers.shouldBe
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.testApplication
import no.nav.su.se.bakover.common.UUID30
import no.nav.su.se.bakover.common.brukerrolle.Brukerrolle
import no.nav.su.se.bakover.test.application.defaultRequest
import no.nav.su.se.bakover.test.application.runApplicationWithMocks
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.skyscreamer.jsonassert.JSONAssert
import økonomi.application.utbetaling.KunneIkkeSendeUtbetalingPåNytt
import økonomi.application.utbetaling.ResendUtbetalingService
class ØkonomiRoutesKtTest {
@Test
fun `aksepterer, validerer, og responderer uten feil for sending av ny utbetaling`() {
val failedUtbetaling = UUID30.randomUUID()
val successUtbetaling = UUID30.randomUUID()
val resendUtbetalingService = mock<ResendUtbetalingService> {
on { this.resendUtbetalinger(any()) } doReturn listOf(
KunneIkkeSendeUtbetalingPåNytt.FantIkkeUtbetalingPåSak(failedUtbetaling).left(),
successUtbetaling.right(),
)
}
val expectedJsonResponse = """
{
"success": [{"utbetalingId": "$successUtbetaling"}],
"failed": [{"utbetalingId": "$failedUtbetaling", "feilmelding": "$failedUtbetaling - Fant ikke utbetaling på sak"}]
}
""".trimIndent()
testApplication {
application {
runApplicationWithMocks(
resendUtbetalingService = resendUtbetalingService,
)
}
defaultRequest(
method = HttpMethod.Post,
uri = "/okonomi/utbetalingslinjer",
roller = listOf(Brukerrolle.Drift),
client = this.client,
) {
setBody(
"""{"utbetalingslinjer": "$successUtbetaling, $failedUtbetaling"}""",
)
}.apply {
status shouldBe HttpStatusCode.OK
JSONAssert.assertEquals(
expectedJsonResponse,
bodyAsText(),
true,
)
}
}
}
}
| 9 | Kotlin | 1 | 1 | 9e72c3086109f9c58472b169f86b213f929a91f1 | 2,492 | su-se-bakover | MIT License |
lib/api/src/main/kotlin/com/daniily/preview/DynamicPreview.kt | daniily000 | 770,977,246 | false | {"Kotlin": 57579} | package com.daniily.preview
import kotlin.reflect.KClass
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
annotation class DynamicPreview {
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
annotation class Wrapper(val wrapperClass: KClass<out Any>)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
annotation class PreviewClass(val annotationClass: KClass<out Annotation>)
}
| 0 | Kotlin | 0 | 2 | 48bdd6f2550ae2b776519f302fe7f8a429b4c672 | 497 | compose-dynamic-preview | Apache License 2.0 |
app/src/main/java/com/iflytek/cyber/iot/show/core/message/MessageSocket.kt | iFLYOS-OPEN | 209,758,318 | false | null | package com.iflytek.cyber.iot.show.core.message
import android.content.Context
import android.util.Log
import com.iflytek.cyber.evs.sdk.auth.AuthDelegate
import okhttp3.*
import okio.ByteString
class MessageSocket private constructor() {
companion object {
private const val TAG = "MessageSocket"
private var instance: MessageSocket? = null
fun get(): MessageSocket {
instance?.let {
return it
} ?: run {
val newInstance = MessageSocket()
this.instance = newInstance
return newInstance
}
}
}
private val okHttpClient = OkHttpClient.Builder().build()
private val webSocketListener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
super.onOpen(webSocket, response)
Log.d(TAG, "Socket connected")
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
super.onMessage(webSocket, bytes)
Log.d(TAG, "Socket onMessage: $bytes")
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
Log.d(TAG, "Socket onMessage: $text")
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
super.onClosed(webSocket, code, reason)
Log.d(TAG, "Socket disconnected")
}
}
fun connect(context: Context) {
val authResponse = AuthDelegate.getAuthResponseFromPref(context)
val request = Request.Builder()
.url("wss://staging-api.iflyos.cn/web/push?command=connect&token=${authResponse?.accessToken}&deviceId=42&fromType=message")
.build()
okHttpClient.newWebSocket(request, webSocketListener)
}
} | 1 | C | 11 | 21 | 4739e2450dcda545fb1361469a9172f82ce28c66 | 1,872 | ShowCore-Open | Apache License 2.0 |
app/src/main/java/com/nemesisprotocol/cryptocraze/domain/cryptoinfo/usecase/GetCoinUseCase.kt | qfdox | 615,859,896 | false | null | package com.nemesisprotocol.cryptocraze.domain.cryptoinfo.usecase
import com.nemesisprotocol.cryptocraze.common.Resource
import com.nemesisprotocol.cryptocraze.data.cryptoinfo.remote.dto.toCoinDetail
import com.nemesisprotocol.cryptocraze.domain.cryptoinfo.CoinDetail
import com.nemesisprotocol.cryptocraze.domain.cryptoinfo.CoinRepo
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
class GetCoinUseCase @Inject constructor(
private val repository: CoinRepo
) {
operator fun invoke(coinId: String): Flow<Resource<CoinDetail>> = flow {
try {
emit(Resource.Loading<CoinDetail>())
val coin = repository.getCoinById(coinId).toCoinDetail()
emit(Resource.Success<CoinDetail>(coin))
} catch (e: HttpException) {
emit(Resource.Error<CoinDetail>(e.localizedMessage ?: "An error has occurred"))
} catch (e: IOException) {
emit(Resource.Error<CoinDetail>("Error has occurred check your internet connection."))
}
}
}
| 0 | Kotlin | 0 | 0 | 4ddc36912423f2e619b0d933224190f71b92d907 | 1,119 | book_js_3 | MIT License |
Decorator/src/test/kotlin/net/milosvasic/decorator/MainTestAssertions.kt | milos85vasic | 82,683,078 | false | null | package net.milosvasic.decorator
object MainTestAssertions {
private val tags = DecoratorTags()
val positiveAssertions = listOf(
"""!-- Template system: Decorator, https://github.com/milos85vasic/Decorator -->
<!-- Template system version: 1.0.0 Alpha 1 DEV 1495451759151 -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Main Decorator test</title>
</head>
<body>
<h1>Umbrella Corporation</h1>""",
"""</body>
</html>""",
"""<p>If 1 ok.</p>""",
"""<p>If 2 ok.</p>""",
"""If 4 not ok.""",
"""<p>If 6 not ok.</p>""",
"""<p>If 7 ok.</p>""",
"""<p>If 8 ok.</p>""",
"""<p>If 1a ok.</p>""",
"""<p>If 2a ok.</p>""",
"""If 4a not ok.""",
"""<p>If 6a not ok.</p>""",
"""<p>If 7a ok.</p>""",
"""<p>If 8a ok.</p>""",
""" <p>If 1b ok.</p>""",
""" <p>If 2 ok.</p>""",
""" <p>If 2k ok.</p>""",
""" <p>If 2l ok.</p>""",
""" <p>If 2b2 not ok.</p>""",
""" <p>If 2c2 ok.</p>""",
""" <p>If 2d2 ok.</p>""",
""" <p>If 2e2 not ok.</p>""",
""" <p>If 2f2 not ok.</p>""",
""" <p>If 2g2 not ok.</p>""",
""" <p>If 2h not ok.</p>""",
""" <p>If 2i ok.</p>""",
""" <p>If 2j not ok.</p>""",
"""<p>If 7b ok.</p>""",
""" <p>If 8b not ok.</p>""",
""" We have company!
And the rest of text...""",
"""x1""",
"""x2""",
""" We have company! B
And the rest of text... B""",
"""a-1""",
"""a2- else""",
"""a-3""",
"""a-4""",
"""a-5""",
"""a-6""",
"""a7- else""",
"""a-8""",
""" <p>@@@ If 1b ok.</p>""",
""" <p>@@@ If 2 ok.</p>""",
""" <p>@@@ If 2k ok.</p>""",
""" <p>@@@ If 2l ok.</p>""",
""" <p>@@@ If 2b2 not ok.</p>""",
""" <p>@@@ If 2c2 ok.</p>""",
""" <p>@@@ If 2d2 ok.</p>""",
""" <p>@@@ If 2e2 not ok.</p>""",
""" <p>@@@ If 2f2 not ok.</p>""",
""" <p>@@@ If 2g2 not ok.</p>""",
""" <p>@@@ If 2h not ok.</p>""",
""" <p>@@@ If 2i ok.</p>""",
""" <p>@@@ If 2j not ok.</p>""",
"""<p>@@@ If 7b ok.</p>""",
""" <p>@@@ If 8b not ok.</p>""",
""" @@@ We have company!
@@@ And the rest of text...""",
"""x1""",
"""x2""",
""" @@@ We have company! B
@@@ And the rest of text... B""",
"""@@@ a-1""",
"""@@@ a2- else""",
"""@@@ a-3""",
"""@@@ a-4""",
"""@@@ a-5""",
"""@@@ a-6""",
"""@@@ a7- else""",
"""@@@ a-8"""
)
val negativeAssertions = listOf(
"""If 2 not ok.""",
"""<p>If 3 ok.</p>""",
"""<p>If 4 ok.</p>""",
"""<p>If 5 ok.</p>""",
"""<p>If 6 ok.</p>""",
"""<p>If 8 not ok.</p>""",
"""If 2a not ok.""",
"""<p>If 3a ok.</p>""",
"""<p>If 4a ok.</p>""",
"""<p>If 5a ok.</p>""",
"""<p>If 6a ok.</p>""",
"""<p>If 8a not ok.</p>""",
""" <p>If 1b2 ok.</p>""",
""" <p>If 1b3 ok.</p>""",
""" <p>If 2 not ok.</p>""",
""" <p>If 2 not not ok.</p>""",
""" <p>If 2k2 ok.</p>""",
""" <p>If 2k not ok.</p>""",
""" <p>If 2l not ok.</p>""",
""" <p>If 2l2 ok.</p>""",
""" <p>If 2l2 not ok.</p>""",
""" <p>If 2b ok.</p>""",
""" <p>If 2b not ok.</p>""",
""" <p>If 2c ok.</p>""",
""" <p>If 2c not ok.</p>""",
""" <p>If 2d ok.</p>""",
""" <p>If 2d not ok.</p>""",
""" <p>If 2d2 not ok.</p>""",
""" <p>If 2e ok.</p>""",
""" <p>If 2e not ok.</p>""",
""" <p>If 2f ok.</p>""",
""" <p>If 2f2 ok.</p>""",
""" <p>If 2g ok.</p>""",
""" <p>If 2g not ok.</p>""",
""" <p>If 2g2 ok.</p>""",
""" <p>If 2h ok.</p>""",
""" <p>If 2h2 not ok.</p>""",
""" <p>If 2i2 ok.</p>""",
""" <p>If 2i not ok.</p>""",
""" <p>If 2j ok.</p>""",
""" <p>If 2j2 ok.</p>""",
""" <p>If 2j2 not ok.</p>""",
""" <p>If 3b ok.</p>""",
""" <p>If 3b2 ok.</p>""",
""" <p>If 5b ok.</p>""",
""" <p>If 6b ok.</p>""",
""" <p>If 6b not ok.</p>""",
""" <p>If 7b2 ok.</p>""",
""" <p>If 7b3 ok.</p>""",
"""<p>If 8b ok.</p>""",
""" Never happen""",
""" Never happen 2""",
""" Never happen 3""",
""" Never happen 4""",
"""x1 else""",
"""x2 else""",
""" Never happen B""",
""" We have company! B""",
""" Never happen 4 B""",
""" And the rest of text... Bs""",
""" Never happen 3 B""",
""" Never happen 4 B""",
""" Never happen 3 B""",
""" We have company! B2s""",
""" Never happen 4 B2s""",
""" And the rest of text... B2s""",
""" Never happen 3 B2s""",
"""a1- else""",
"""a-2""",
"""a3- else""",
"""a4- else""",
"""a5- else""",
"""a6- else""",
"""a-7""",
"""a8- else""",
""" <p>@@@ If 1b2 ok.</p>""",
""" <p>@@@ If 1b3 ok.</p>""",
""" <p>@@@ If 2 not ok.</p>""",
""" <p>@@@ If 2 not not ok.</p>""",
""" <p>@@@ If 2k2 ok.</p>""",
""" <p>@@@ If 2k not ok.</p>""",
""" <p>@@@ If 2l not ok.</p>""",
""" <p>@@@ If 2l2 ok.</p>""",
""" <p>@@@ If 2l2 not ok.</p>""",
""" <p>@@@ If 2b ok.</p>""",
""" <p>@@@ If 2b not ok.</p>""",
""" <p>@@@ If 2c ok.</p>""",
""" <p>@@@ If 2c not ok.</p>""",
""" <p>@@@ If 2d ok.</p>""",
""" <p>If 2d not ok.</p>""",
""" <p>@@@ If 2d2 not ok.</p>""",
""" <p>@@@ If 2e ok.</p>""",
""" <p>@@@ If 2e not ok.</p>""",
""" <p>@@@ If 2f ok.</p>""",
""" <p>@@@ If 2f2 ok.</p>""",
""" <p>@@@ If 2g ok.</p>""",
""" <p>@@@ If 2g not ok.</p>""",
""" <p>@@@ If 2g2 ok.</p>""",
""" <p>@@@ If 2h ok.</p>""",
""" <p>@@@ If 2h2 not ok.</p>""",
""" <p>@@@ If 2i2 ok.</p>""",
""" <p>@@@ If 2i not ok.</p>""",
""" <p>@@@ If 2j ok.</p>""",
""" <p>@@@ If 2j2 ok.</p>""",
""" <p>@@@ If 2j2 not ok.</p>""",
""" <p>@@@ If 3b ok.</p>""",
""" <p>@@@ If 3b2 ok.</p>""",
""" <p>@@@ If 5b ok.</p>""",
""" <p>@@@ If 6b ok.</p>""",
""" <p>@@@ If 6b not ok.</p>""",
""" <p>@@@ If 7b2 ok.</p>""",
""" <p>@@@ If 7b3 ok.</p>""",
"""<p>@@@ If 8b ok.</p>""",
""" @@@ Never happen""",
""" @@@ Never happen 2""",
""" @@@ Never happen 3""",
""" @@@ Never happen 4""",
"""@@@ x1 else""",
"""@@@ x2 else""",
""" @@@ Never happen B""",
""" @@@ We have company! B""",
""" @@@ Never happen 4 B""",
""" @@@ And the rest of text... Bs""",
""" @@@ Never happen 3 B""",
""" @@@ Never happen 4 B""",
""" @@@ Never happen 3 B""",
""" @@@ We have company! B2s""",
""" @@@ Never happen 4 B2s""",
""" @@@ And the rest of text... B2s""",
""" @@@ Never happen 3 B2s""",
"""@@@ a1- else""",
"""@@@ a-2""",
"""@@@ a3- else""",
"""@@@ a4- else""",
"""@@@ a5- else""",
"""@@@ a6- else""",
"""@@@ a-7""",
"""@@@ a8- else""",
tags.ifOpen, tags.ifClose, tags.foreachOpen, tags.foreachClose, tags.open, tags.close, tags.endIf, tags.endFor, tags.tabPlaceholder
)
} | 0 | Kotlin | 0 | 4 | 4a4d99a71955aa1c64af627c544cdd7134cb7bfd | 7,614 | Decorator | Apache License 2.0 |
Demo/src/main/java/com/paypal/android/api/model/OrderIntent.kt | paypal | 390,097,712 | false | {"Kotlin": 299789} | package com.paypal.android.api.model
/**
* The intent to either capture payment immediately or authorize a payment for an order after order creation
*/
enum class OrderIntent {
/**
* The merchant intends to capture payment immediately after the customer makes a payment.
*/
CAPTURE,
/**
* The merchant intends to authorize a payment and place funds on hold after the customer makes
* a payment. Authorized payments are best captured within three days of authorization but are
* available to capture for up to 29 days. After the three-day honor period, the original authorized
* payment expires and you must re-authorize the payment. You must make a separate request to
* capture payments on demand. This intent is not supported when you have more than one
* `purchase_unit` within your order.
*/
AUTHORIZE
}
| 22 | Kotlin | 41 | 74 | dcc46f92771196e979f7863b9b8d3fa3d6dc1a7d | 872 | paypal-android | Apache License 2.0 |
server/src/main/kotlin/net/eiradir/server/exception/LoggingExceptionHandler.kt | Eiradir | 635,460,745 | false | {"Kotlin": 646160, "Dockerfile": 470} | package net.eiradir.server.exception
import net.eiradir.server.extensions.logger
import kotlin.system.exitProcess
class LoggingExceptionHandler : ExceptionHandler {
private val log = logger()
override fun handle(e: Throwable) {
log.error("Unhandled exception", e)
exitProcess(1)
}
} | 11 | Kotlin | 0 | 0 | edca8986ef06fd5a75fd2a4dc53dfe75dbfbbaae | 313 | eiradir-server | MIT License |
mapkit-samples/map-objects/src/main/kotlin/com/yandex/mapkitdemo/ClusterView.kt | yandex | 124,944,765 | false | null | package com.yandex.mapkitdemo
import android.content.Context
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
class ClusterView(context: Context) : LinearLayout(context) {
private val greenText by lazy { findViewById<TextView>(R.id.text_green_pins) }
private val yellowText by lazy { findViewById<TextView>(R.id.text_yello_pins) }
private val redText by lazy { findViewById<TextView>(R.id.text_red_pins) }
private val greenLayout by lazy { findViewById<View>(R.id.layout_green_group) }
private val yellowLayout by lazy { findViewById<View>(R.id.layout_yellow_group) }
private val redLayout by lazy { findViewById<View>(R.id.layout_red_group) }
init {
inflate(context, R.layout.cluster_view, this)
layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
orientation = HORIZONTAL
setBackgroundResource(R.drawable.cluster_view_background)
}
fun setData(placemarkTypes: List<PlacemarkType>) {
PlacemarkType.values().forEach {
updateViews(placemarkTypes, it)
}
}
private fun updateViews(
placemarkTypes: List<PlacemarkType>,
type: PlacemarkType
) {
val (textView, layoutView) = when (type) {
PlacemarkType.GREEN -> greenText to greenLayout
PlacemarkType.YELLOW -> yellowText to yellowLayout
PlacemarkType.RED -> redText to redLayout
}
val value = placemarkTypes.countTypes(type)
textView.text = value.toString()
layoutView.isVisible = value != 0
}
private fun List<PlacemarkType>.countTypes(type: PlacemarkType) = count { it == type }
}
| 26 | null | 60 | 99 | ba44088f205760464055ef2c6db96b2ae1a9b9cd | 1,753 | mapkit-android-demo | Apache License 2.0 |
altchain-pop-miner/miner/src/main/kotlin/org/veriblock/miners/pop/securityinheriting/SecurityInheritingAutoMiner.kt | xagau | 257,342,239 | true | {"Gradle": 15, "INI": 3, "Markdown": 6, "Shell": 1, "Text": 8, "Ignore List": 3, "Batchfile": 1, "Java": 424, "Kotlin": 178, "Dockerfile": 4, "Java Properties": 1, "XML": 3, "Protocol Buffer": 4, "Groovy": 2} | // VeriBlock Blockchain Project
// Copyright 2017-2018 VeriBlock, Inc
// Copyright 2018-2019 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package org.veriblock.miners.pop.securityinheriting
import com.google.common.util.concurrent.SettableFuture
import org.veriblock.lite.util.Threading
import org.veriblock.miners.pop.Miner
import org.veriblock.sdk.alt.SecurityInheritingChain
import org.veriblock.sdk.checkSuccess
import org.veriblock.core.utilities.createLogger
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
private val logger = createLogger {}
class SecurityInheritingAutoMiner(
private val miner: Miner,
private val chainId: String,
private val chain: SecurityInheritingChain
) {
private val healthy = AtomicBoolean(false)
private val connected = SettableFuture.create<Boolean>()
private var bestBlockHeight: Int = -1
private var pollSchedule: ScheduledFuture<*>? = null
fun start() {
pollSchedule = Threading.SI_POLL_THREAD.scheduleWithFixedDelay({
this.poll()
}, 1L, 1L, TimeUnit.SECONDS)
logger.info("Connecting to SI Chain ($chainId)...")
connected.addListener(Runnable {
logger.info("Connected to SI Chain ($chainId)!")
}, Threading.SI_POLL_THREAD)
}
fun stop() {
pollSchedule?.cancel(false)
pollSchedule = null
}
private fun poll() {
try {
if (healthy.get()) {
val bestBlockHeight: Int = try {
chain.getBestBlockHeight()
} catch (e: Exception) {
logger.error("$chainId Chain Error", e)
healthy.set(false)
return
}
if (this.bestBlockHeight == -1 || bestBlockHeight != this.bestBlockHeight) {
logger.debug { "New chain head detected!" }
if (chain.shouldAutoMine(bestBlockHeight)) {
miner.mine(chainId, bestBlockHeight)
}
this.bestBlockHeight = bestBlockHeight
}
} else {
val pinged = checkSuccess { chain.getBestBlockHeight() }
if (pinged) {
healthy.set(true)
connected.set(true)
}
}
} catch (e: Exception) {
logger.error(e) { "Error when polling SI Chain ($chainId)" }
}
}
}
| 1 | null | 0 | 0 | 5df4ac5f48a598dde94d57d5810882a548d4d23d | 2,690 | nodecore | MIT License |
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/newTests/testFeatures/OrderEntriesFilteringTestFeature.kt | errandir | 27,763,579 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.gradle.newTests.testFeatures
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.gradle.newTests.TestConfigurationDslScope
import org.jetbrains.kotlin.gradle.newTests.TestFeature
import org.jetbrains.kotlin.gradle.newTests.writeAccess
object OrderEntriesFilteringTestFeature : TestFeature<OrderEntriesFilteringConfiguration> {
override fun renderConfiguration(configuration: OrderEntriesFilteringConfiguration): List<String> {
val hiddenStandardDependencies = buildList<String> {
if (configuration.hideStdlib) add("stdlib")
if (configuration.hideKotlinTest) add("kotlin-test")
if (configuration.hideKonanDist) add("Kotlin/Native distribution")
if (configuration.hideSdkDependency) add("sdk")
if (configuration.hideSelfDependency) add ("self")
}
return buildList {
if (hiddenStandardDependencies.isNotEmpty())
add("hiding following standard dependencies: ${hiddenStandardDependencies.joinToString()}")
if (configuration.excludeDependenciesRegex != null) {
add("hiding dependencies matching ${configuration.excludeDependenciesRegex.toString()}")
}
}
}
override fun createDefaultConfiguration(): OrderEntriesFilteringConfiguration = OrderEntriesFilteringConfiguration()
}
class OrderEntriesFilteringConfiguration {
var excludeDependenciesRegex: Regex? = null
var hideStdlib: Boolean = false
var hideKotlinTest: Boolean = false
var hideKonanDist: Boolean = false
// Always hidden for now
val hideSelfDependency: Boolean = true
val hideSdkDependency: Boolean = true
}
private val TestConfigurationDslScope.config: OrderEntriesFilteringConfiguration
get() = writeAccess.getConfiguration(OrderEntriesFilteringTestFeature)
interface OrderEntriesFilteringSupport {
var TestConfigurationDslScope.hideStdlib: Boolean
get() = config.hideStdlib
set(value) { config.hideStdlib = value }
var TestConfigurationDslScope.hideKotlinTest
get() = config.hideKotlinTest
set(value) { config.hideKotlinTest = value }
var TestConfigurationDslScope.hideKotlinNativeDistribution
get() = config.hideKonanDist
set(value) { config.hideKonanDist = value }
fun TestConfigurationDslScope.excludeDependenciesRegex(@Language("Regex") regex: String) {
config.excludeDependenciesRegex = regex.toRegex()
}
}
| 1 | null | 1 | 1 | 1d359da14d759f924f64811b84c8aeccb1d1188c | 2,635 | intellij-community | Apache License 2.0 |
module/data/src/main/kotlin/com/github/jameshnsears/chance/data/repository/roll/RepositoryRollInterface.kt | jameshnsears | 725,514,594 | false | {"Kotlin": 348231, "Shell": 678} | package com.github.jameshnsears.chance.data.repository.roll
import com.github.jameshnsears.chance.data.domain.proto.RollHistoryProtocolBuffer
import com.github.jameshnsears.chance.data.domain.proto.RollListProtocolBuffer
import com.github.jameshnsears.chance.data.domain.proto.RollProtocolBuffer
import com.github.jameshnsears.chance.data.domain.proto.SideProtocolBuffer
import com.github.jameshnsears.chance.data.domain.state.RollHistory
import com.github.jameshnsears.chance.data.repository.RepositoryImportExportInterface
import kotlinx.coroutines.flow.Flow
interface RepositoryRollInterface : RepositoryImportExportInterface {
suspend fun fetch(): Flow<RollHistory>
suspend fun store(newRollHistory: RollHistory)
fun mapBagIntoBagProtocolBufferBuilder(
rollHistory: RollHistory,
rollHistoryProtocolBufferBuilder: RollHistoryProtocolBuffer.Builder,
) {
for ((keyEpoch, valueRolls) in rollHistory) {
val rollListProtocolBuffer = RollListProtocolBuffer.newBuilder()
for (roll in valueRolls) {
val rollProtocolBuffer = RollProtocolBuffer.newBuilder()
rollProtocolBuffer.setDiceEpoch(roll.diceEpoch)
val sideProtocolBuffer = SideProtocolBuffer.newBuilder()
sideProtocolBuffer.setNumber(roll.side.number)
sideProtocolBuffer.setNumberColour(roll.side.numberColour)
sideProtocolBuffer.setImageDrawableId(roll.side.imageDrawableId)
sideProtocolBuffer.setImageBase64(roll.side.imageBase64)
sideProtocolBuffer.setDescription(roll.side.description)
sideProtocolBuffer.setDescriptionColour(roll.side.descriptionColour)
sideProtocolBuffer.build()
rollProtocolBuffer.setSide(sideProtocolBuffer)
rollProtocolBuffer.setMultiplierIndex(roll.multiplierIndex)
rollProtocolBuffer.setExplodeIndex(roll.explodeIndex)
rollProtocolBuffer.setScoreAdjustment(roll.scoreAdjustment)
rollProtocolBuffer.setScore(roll.score)
rollListProtocolBuffer.addRoll(rollProtocolBuffer.build())
}
rollHistoryProtocolBufferBuilder.putValues(keyEpoch, rollListProtocolBuffer.build())
}
}
}
| 1 | Kotlin | 0 | 0 | a3ceaa3329de9f329ced7b2e02a8177890a8cc73 | 2,314 | Chance | Apache License 2.0 |
src/commonMain/kotlin/app/revolt/model/RevoltFileUploadApiResponse.kt | ted3x | 695,442,173 | false | {"Kotlin": 75036} | package app.revolt.model
import kotlinx.serialization.Serializable
@Serializable
data class RevoltFileUploadApiResponse(val id: String) | 0 | Kotlin | 0 | 0 | e079efe153464c08d60c34169f8bcf9f1067aa54 | 137 | revolt-kotlin-api | MIT License |
app/src/main/java/org/abuhuraira/app/scenes/home/HomePresenter.kt | YusufSaad | 428,501,733 | false | {"Java": 3686476, "Kotlin": 315094, "HTML": 4986, "Assembly": 6} | package org.abuhuraira.app.scenes.home
import com.example.ahcstores.sources.enums.PrayerName
import com.example.coreandroid.sources.errors.DataError
import com.example.coreandroid.sources.extensions.add
import org.abuhuraira.app.R
import org.abuhuraira.app.common.cleanBase.AppModels
import org.abuhuraira.app.common.extensions.getString
import org.abuhuraira.app.scenes.home.common.HomeDisplayable
import org.abuhuraira.app.scenes.home.common.HomeModels
import org.abuhuraira.app.scenes.home.common.HomePresentable
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by ahmedsaad on 2017-10-27.
* Copyright © 2017. All rights reserved.
*/
class HomePresenter(private val fragment: WeakReference<HomeDisplayable?>) : HomePresentable {
private val dateFormatter = SimpleDateFormat("MMMM d yyyy", Locale.US)
private val prayerTimeFormatter = SimpleDateFormat("hh:mm a", Locale.US)
override fun presentFetchedPrayerTimes(response: HomeModels.PrayerTimesResponse) {
val viewModel = HomeModels.PrayerTimesViewModel(
currentDate = dateFormatter.format(Date()),
prayerTimes = response.prayerTimes.fold(arrayListOf()) { acc, prayerTimeType ->
val prayerTime = HomeModels.PrayerTimeViewModel(
name = prayerTimeType.name.displayName,
athan = if (prayerTimeType.athan == Date(0))
"" else prayerTimeFormatter.format(prayerTimeType.athan),
iqama = if (prayerTimeType.iqama == Date(0)) {
when {
prayerTimeType.name == PrayerName.Fajar -> prayerTimeFormatter
.format(prayerTimeType.athan.add(Calendar.MINUTE, 20))
prayerTimeType.name == PrayerName.Maghrib -> prayerTimeFormatter
.format(prayerTimeType.athan.add(Calendar.MINUTE, 5))
else -> ""
}
} else prayerTimeFormatter.format(prayerTimeType.iqama)
)
acc.add(prayerTime)
acc
}
)
fragment.get()?.displayFetchedPrayerTimes(viewModel)
}
override fun presentFetchedPrayerTimes(error: DataError) {
// Handle and parse error
val viewModel = AppModels.Error(
title = getString(R.string.generic_error_title),
message = getString(R.string.generic_error_message)
)
fragment.get()?.displaySupport(viewModel)
}
override fun presentFetchedEvents(response: HomeModels.EventsResponse) {
val viewModel = HomeModels.EventsViewModel(
events = response.events.fold(arrayListOf()) { acc, eventType ->
val event = HomeModels.EventViewModel(
name = eventType.name,
imageURL = eventType.imageURL,
detailURL = eventType.detailURL
)
acc.add(event)
acc
}
)
fragment.get()?.displayFetchedEvents(viewModel)
}
override fun presentFetchedEvents(error: DataError) {
// Handle and parse error
val viewModel = AppModels.Error(
title = getString(R.string.generic_error_title),
message = getString(R.string.generic_error_message)
)
fragment.get()?.displaySupport(viewModel)
}
} | 1 | Java | 1 | 2 | 02f84a27796eed4683dc7bab88b07446a6fe2315 | 3,690 | Ahc-app | MIT License |
tabby-core/src/jvmTest/kotlin/com/sksamuel/tabby/effects/MapTest.kt | xeruf | 339,163,399 | true | {"Kotlin": 122680} | package com.sksamuel.tabby.effects
import com.sksamuel.tabby.`try`.success
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class MapTest : FunSpec() {
init {
test("map should invoke combinator on success") {
IO { "foo" }.map { it.length }.run() shouldBe 3.success()
IO { "foo" }.map { it.length }.map { it + 3 }.run() shouldBe 6.success()
}
}
}
| 0 | null | 0 | 0 | 38a33811953aeb31dcc215bde370465010f24f31 | 411 | tabby | Apache License 2.0 |
app/src/main/java/com/replica/replicaisland/LauncherComponent.kt | jimandreas | 290,957,495 | false | null | /*
* Copyright (C) 2010 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.replica.replicaisland
import com.replica.replicaisland.GameObject.ActionType
import com.replica.replicaisland.GameObjectFactory.GameObjectType
import com.replica.replicaisland.SoundSystem.Sound
import kotlin.math.cos
import kotlin.math.sin
class LauncherComponent : GameComponent() {
private var mShot: GameObject? = null
private var mLaunchTime = 0f
private var mAngle = 0f
private var mLaunchDelay = 0f
private val mLaunchDirection: Vector2 = Vector2()
private var mLaunchMagnitude = 0f
private var mPostLaunchDelay = 0f
private var mDriveActions = false
private var mLaunchEffect: GameObjectType? = null
private var mLaunchEffectOffsetX = 0f
private var mLaunchEffectOffsetY = 0f
private var mLaunchSound: Sound? = null
override fun reset() {
mShot = null
mLaunchTime = 0.0f
mAngle = 0.0f
mLaunchDelay = DEFAULT_LAUNCH_DELAY
mLaunchMagnitude = DEFAULT_LAUNCH_MAGNITUDE
mPostLaunchDelay = DEFAULT_POST_LAUNCH_DELAY
mDriveActions = true
mLaunchEffect = GameObjectType.INVALID
mLaunchEffectOffsetX = 0.0f
mLaunchEffectOffsetY = 0.0f
mLaunchSound = null
}
override fun update(timeDelta: Float, parent: BaseObject?) {
val time = sSystemRegistry.timeSystem
val gameTime = time!!.gameTime
val parentObject = parent as GameObject?
if (mShot != null) {
if (mShot!!.life <= 0) {
// Looks like the shot is dead. Let's forget about it.
// TODO: this is unreliable. We should have a "notify on death" event or something.
mShot = null
} else {
if (gameTime > mLaunchTime) {
fire(mShot!!, parentObject, mAngle)
mShot = null
if (mDriveActions) {
parentObject!!.currentAction = ActionType.ATTACK
}
} else {
mShot!!.position = parentObject!!.position
}
}
} else if (gameTime > mLaunchTime + mPostLaunchDelay) {
if (mDriveActions) {
parentObject!!.currentAction = ActionType.IDLE
}
}
}
fun prepareToLaunch(thing: GameObject, parentObject: GameObject?) {
if (mShot != thing) {
if (mShot != null) {
// We already have a shot loaded and we are asked to shoot something else.
// Shoot the current shot off and then load the new one.
fire(mShot!!, parentObject, mAngle)
}
val time = sSystemRegistry.timeSystem
val gameTime = time!!.gameTime
mShot = thing
mLaunchTime = gameTime + mLaunchDelay
}
}
private fun fire(thing: GameObject, parentObject: GameObject?, mAngle: Float) {
if (mDriveActions) {
thing.currentAction = ActionType.MOVE
}
mLaunchDirection[sin(mAngle.toDouble()).toFloat()] = cos(mAngle.toDouble()).toFloat()
mLaunchDirection.multiply(parentObject!!.facingDirection)
mLaunchDirection.multiply(mLaunchMagnitude)
thing.velocity = mLaunchDirection
if (mLaunchSound != null) {
val sound = sSystemRegistry.soundSystem
sound?.play(mLaunchSound!!, false, SoundSystem.PRIORITY_NORMAL)
}
if (mLaunchEffect !== GameObjectType.INVALID) {
val factory = sSystemRegistry.gameObjectFactory
val manager = sSystemRegistry.gameObjectManager
if (factory != null && manager != null) {
val position = parentObject.position
val effect = factory.spawn(mLaunchEffect!!,
position.x + mLaunchEffectOffsetX * parentObject.facingDirection.x,
position.y + mLaunchEffectOffsetY * parentObject.facingDirection.y,
false)
if (effect != null) {
manager.add(effect)
}
}
}
}
fun setup(angle: Float, magnitude: Float, launchDelay: Float, postLaunchDelay: Float, driveActions: Boolean) {
mAngle = angle
mLaunchMagnitude = magnitude
mLaunchDelay = launchDelay
mPostLaunchDelay = postLaunchDelay
mDriveActions = driveActions
}
fun setLaunchEffect(effectType: GameObjectType?, offsetX: Float, offsetY: Float) {
mLaunchEffect = effectType
mLaunchEffectOffsetX = offsetX
mLaunchEffectOffsetY = offsetY
}
fun setLaunchSound(sound: Sound?) {
mLaunchSound = sound
}
companion object {
private const val DEFAULT_LAUNCH_DELAY = 2.0f
private const val DEFAULT_LAUNCH_MAGNITUDE = 2000.0f
private const val DEFAULT_POST_LAUNCH_DELAY = 1.0f
}
init {
reset()
setPhaseToThis(ComponentPhases.THINK.ordinal)
}
} | 0 | Kotlin | 0 | 3 | 387aa71c94b87be4d8cab704241e49f6018a7821 | 5,613 | ReplicaIslandKotlin | Apache License 2.0 |
stickyheaders/src/main/java/com/a21buttons/stickyheaders/StickyHeaderAdapter.kt | BraisGabin | 93,491,692 | false | null | package com.a21buttons.stickyheaders
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
abstract class StickyHeaderAdapter<VH : StickyHeaderViewHolder> : RecyclerView.Adapter<VH>(), StickyHeaderLayoutManager.HeaderLookup {
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
val holder = onCreateViewHolder2(parent, viewType)
holder.itemView.setTag(R.id.com_a21buttons_stickyheaders_holder, holder)
return holder
}
abstract fun onCreateViewHolder2(parent: ViewGroup, viewType: Int): VH
final override fun onBindViewHolder(holder: VH, position: Int) {
val sectionId = getSectionId(position)
onBindViewHolder(holder, position, sectionId)
holder.sectionId = sectionId
}
abstract fun onBindViewHolder(holder: VH, position: Int, sectionId: Long)
abstract fun getSectionId(position: Int): Long
}
| 1 | Kotlin | 1 | 1 | e979e13c98005efc8c6a10afc4dcfe8cda236675 | 886 | sticky-headers | Apache License 2.0 |
domain/src/main/java/com/hxl/domain/usecase/database/game_history/InsertGameHistory.kt | hexley21 | 507,946,022 | false | {"Kotlin": 87163} | package com.hxl.domain.usecase.database.game_history
import com.hxl.domain.models.GameResult
import com.hxl.domain.repository.GameHistoryRepository
import io.reactivex.rxjava3.core.Completable
/**
* Game-History use-case that provides Game-Result insertion method.
*/
class InsertGameHistory(private val gameHistoryRepository: GameHistoryRepository) {
operator fun invoke(gameHistory: GameResult): Completable {
return gameHistoryRepository.insertGameResult(gameHistory)
}
} | 0 | Kotlin | 0 | 1 | d0f9a19c28e3646966d0c66d192109a20fc0a293 | 494 | ArithMathics | Apache License 2.0 |
app/src/main/java/com/example/swiftbargain/ui/addresses/composable/AddressesAddAddress.kt | ahmedfikry24 | 814,676,783 | false | {"Kotlin": 484263} | package com.example.swiftbargain.ui.addresses.composable
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.example.swiftbargain.ui.add_address.AddAddressContent
import com.example.swiftbargain.ui.addresses.view_model.AddressesInteractions
import com.example.swiftbargain.ui.composable.PrimaryFab
import com.example.swiftbargain.ui.theme.colors
import com.example.swiftbargain.ui.theme.spacing
import com.example.swiftbargain.ui.utils.shared_ui_state.AddressUiState
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun AddressesAddAddress(
modifier: Modifier = Modifier,
isAddAddressVisible: Boolean,
addAddress: AddressUiState,
interactions: AddressesInteractions
) {
SharedTransitionLayout {
AnimatedContent(
modifier = modifier,
targetState = isAddAddressVisible,
label = "transition"
) { isVisible ->
if (isVisible) {
AddAddressContent(
modifier = Modifier
.background(MaterialTheme.colors.background)
.sharedBounds(
rememberSharedContentState(key = "bounds"),
animatedVisibilityScope = this@AnimatedContent,
resizeMode = SharedTransitionScope.ResizeMode.ScaleToBounds()
),
state = addAddress,
interactions = interactions,
onCancel = interactions::controlAddAddressVisibility
)
} else {
PrimaryFab(
modifier = Modifier
.padding(MaterialTheme.spacing.space16)
.sharedBounds(
rememberSharedContentState(key = "bounds"),
animatedVisibilityScope = this@AnimatedContent,
resizeMode = SharedTransitionScope.ResizeMode.ScaleToBounds()
),
onClick = interactions::controlAddAddressVisibility
)
}
}
}
} | 0 | Kotlin | 0 | 0 | daee363e13ed78c20da30c54a45dfb9309338b33 | 2,536 | SwiftBargain | MIT License |
infrastructure/src/main/kotlin/com/lukinhasssss/catalogo/infrastructure/configuration/usecases/CategoryUseCasesConfig.kt | Lukinhasssss | 643,341,523 | false | {"Kotlin": 179428, "Shell": 669} | package com.lukinhasssss.catalogo.infrastructure.configuration.usecases
import com.lukinhasssss.catalogo.application.category.delete.DeleteCategoryUseCase
import com.lukinhasssss.catalogo.application.category.get.GetAllCategoriesByIdUseCase
import com.lukinhasssss.catalogo.application.category.list.ListCategoryUseCase
import com.lukinhasssss.catalogo.application.category.save.SaveCategoryUseCase
import com.lukinhasssss.catalogo.domain.category.CategoryGateway
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)
class CategoryUseCasesConfig(
private val categoryGateway: CategoryGateway
) {
@Bean
fun deleteCategoryUseCase() = DeleteCategoryUseCase(categoryGateway)
@Bean
fun listCategoryUseCase() = ListCategoryUseCase(categoryGateway)
@Bean
fun saveCategoryUseCase() = SaveCategoryUseCase(categoryGateway)
@Bean
fun getAllCategoriesByIdUseCase() = GetAllCategoriesByIdUseCase(categoryGateway)
}
| 1 | Kotlin | 0 | 0 | fef7c7701656298a857cbd157ce0090b6da0106e | 1,043 | catalogo-de-videos | MIT License |
entity/src/main/java/com/eslam/entity/Review.kt | zerox321 | 240,343,192 | false | null |
package com.mustafa.movieguideapp.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Review(
val id: String,
val author: String,
val content: String,
val url: String
) : Parcelable
| 0 | null | 0 | 2 | d2a80591efe0bbff353b1a20aeb6c959cbe595cb | 239 | GoldKreaz | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/TachometerAltSolid.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.TachometerAltSolid: ImageVector
get() {
if (_tachometerAltSolid != null) {
return _tachometerAltSolid!!
}
_tachometerAltSolid = Builder(name = "TachometerAltSolid", defaultWidth = 32.0.dp,
defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.0f, 6.0f)
curveTo(9.3828f, 6.0f, 4.0f, 11.3828f, 4.0f, 18.0f)
curveTo(4.0f, 20.8945f, 5.0352f, 23.5508f, 6.75f, 25.625f)
lineTo(7.0313f, 26.0f)
lineTo(24.9688f, 26.0f)
lineTo(25.25f, 25.625f)
curveTo(26.9648f, 23.5508f, 28.0f, 20.8945f, 28.0f, 18.0f)
curveTo(28.0f, 11.3828f, 22.6172f, 6.0f, 16.0f, 6.0f)
close()
moveTo(16.0f, 8.0f)
curveTo(21.5352f, 8.0f, 26.0f, 12.4648f, 26.0f, 18.0f)
curveTo(26.0f, 20.2656f, 25.207f, 22.3242f, 23.9375f, 24.0f)
lineTo(8.0625f, 24.0f)
curveTo(6.793f, 22.3242f, 6.0f, 20.2656f, 6.0f, 18.0f)
curveTo(6.0f, 12.4648f, 10.4648f, 8.0f, 16.0f, 8.0f)
close()
moveTo(16.0f, 9.0f)
curveTo(15.4492f, 9.0f, 15.0f, 9.4492f, 15.0f, 10.0f)
curveTo(15.0f, 10.5508f, 15.4492f, 11.0f, 16.0f, 11.0f)
curveTo(16.5508f, 11.0f, 17.0f, 10.5508f, 17.0f, 10.0f)
curveTo(17.0f, 9.4492f, 16.5508f, 9.0f, 16.0f, 9.0f)
close()
moveTo(12.0f, 10.0625f)
curveTo(11.4492f, 10.0625f, 11.0f, 10.5117f, 11.0f, 11.0625f)
curveTo(11.0f, 11.6133f, 11.4492f, 12.0625f, 12.0f, 12.0625f)
curveTo(12.5508f, 12.0625f, 13.0f, 11.6133f, 13.0f, 11.0625f)
curveTo(13.0f, 10.5117f, 12.5508f, 10.0625f, 12.0f, 10.0625f)
close()
moveTo(20.0f, 10.0625f)
curveTo(19.4492f, 10.0625f, 19.0f, 10.5117f, 19.0f, 11.0625f)
curveTo(19.0f, 11.6133f, 19.4492f, 12.0625f, 20.0f, 12.0625f)
curveTo(20.5508f, 12.0625f, 21.0f, 11.6133f, 21.0f, 11.0625f)
curveTo(21.0f, 10.5117f, 20.5508f, 10.0625f, 20.0f, 10.0625f)
close()
moveTo(9.0625f, 13.0f)
curveTo(8.5117f, 13.0f, 8.0625f, 13.4492f, 8.0625f, 14.0f)
curveTo(8.0625f, 14.5508f, 8.5117f, 15.0f, 9.0625f, 15.0f)
curveTo(9.6133f, 15.0f, 10.0625f, 14.5508f, 10.0625f, 14.0f)
curveTo(10.0625f, 13.4492f, 9.6133f, 13.0f, 9.0625f, 13.0f)
close()
moveTo(22.6563f, 13.0313f)
lineTo(17.0f, 16.2813f)
curveTo(16.707f, 16.1094f, 16.3633f, 16.0f, 16.0f, 16.0f)
curveTo(14.8945f, 16.0f, 14.0f, 16.8945f, 14.0f, 18.0f)
curveTo(14.0f, 19.1055f, 14.8945f, 20.0f, 16.0f, 20.0f)
curveTo(17.0938f, 20.0f, 17.9844f, 19.1211f, 18.0f, 18.0313f)
curveTo(18.0f, 18.0195f, 18.0f, 18.0117f, 18.0f, 18.0f)
lineTo(23.6563f, 14.7813f)
close()
moveTo(8.0f, 17.0f)
curveTo(7.4492f, 17.0f, 7.0f, 17.4492f, 7.0f, 18.0f)
curveTo(7.0f, 18.5508f, 7.4492f, 19.0f, 8.0f, 19.0f)
curveTo(8.5508f, 19.0f, 9.0f, 18.5508f, 9.0f, 18.0f)
curveTo(9.0f, 17.4492f, 8.5508f, 17.0f, 8.0f, 17.0f)
close()
moveTo(24.0f, 17.0f)
curveTo(23.4492f, 17.0f, 23.0f, 17.4492f, 23.0f, 18.0f)
curveTo(23.0f, 18.5508f, 23.4492f, 19.0f, 24.0f, 19.0f)
curveTo(24.5508f, 19.0f, 25.0f, 18.5508f, 25.0f, 18.0f)
curveTo(25.0f, 17.4492f, 24.5508f, 17.0f, 24.0f, 17.0f)
close()
moveTo(9.0625f, 21.0f)
curveTo(8.5117f, 21.0f, 8.0625f, 21.4492f, 8.0625f, 22.0f)
curveTo(8.0625f, 22.5508f, 8.5117f, 23.0f, 9.0625f, 23.0f)
curveTo(9.6133f, 23.0f, 10.0625f, 22.5508f, 10.0625f, 22.0f)
curveTo(10.0625f, 21.4492f, 9.6133f, 21.0f, 9.0625f, 21.0f)
close()
moveTo(22.9375f, 21.0f)
curveTo(22.3867f, 21.0f, 21.9375f, 21.4492f, 21.9375f, 22.0f)
curveTo(21.9375f, 22.5508f, 22.3867f, 23.0f, 22.9375f, 23.0f)
curveTo(23.4883f, 23.0f, 23.9375f, 22.5508f, 23.9375f, 22.0f)
curveTo(23.9375f, 21.4492f, 23.4883f, 21.0f, 22.9375f, 21.0f)
close()
}
}
.build()
return _tachometerAltSolid!!
}
private var _tachometerAltSolid: ImageVector? = null
| 15 | null | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 5,541 | compose-icons | MIT License |
graphql-dgs/src/main/kotlin/com/netflix/graphql/dgs/internal/DefaultDgsQueryExecutor.kt | Netflix | 317,375,887 | false | null | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.graphql.dgs.internal
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.TypeRef
import com.jayway.jsonpath.spi.mapper.MappingException
import com.netflix.graphql.dgs.DgsQueryExecutor
import com.netflix.graphql.dgs.exceptions.DgsQueryExecutionDataExtractionException
import com.netflix.graphql.dgs.exceptions.QueryException
import com.netflix.graphql.dgs.internal.BaseDgsQueryExecutor.parseContext
import com.netflix.graphql.dgs.internal.DefaultDgsQueryExecutor.ReloadSchemaIndicator
import graphql.ExecutionResult
import graphql.execution.ExecutionIdProvider
import graphql.execution.ExecutionStrategy
import graphql.execution.NonNullableFieldWasNullError
import graphql.execution.instrumentation.Instrumentation
import graphql.execution.preparsed.PreparsedDocumentProvider
import graphql.schema.GraphQLSchema
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.web.context.request.ServletWebRequest
import org.springframework.web.context.request.WebRequest
import java.util.*
import java.util.concurrent.atomic.AtomicReference
/**
* Main Query executing functionality. This should be reused between different transport protocols and the testing framework.
*/
class DefaultDgsQueryExecutor(
defaultSchema: GraphQLSchema,
private val schemaProvider: DgsSchemaProvider,
private val dataLoaderProvider: DgsDataLoaderProvider,
private val contextBuilder: DefaultDgsGraphQLContextBuilder,
private val instrumentation: Instrumentation?,
private val queryExecutionStrategy: ExecutionStrategy,
private val mutationExecutionStrategy: ExecutionStrategy,
private val idProvider: Optional<ExecutionIdProvider>,
private val reloadIndicator: ReloadSchemaIndicator = ReloadSchemaIndicator { false },
private val preparsedDocumentProvider: PreparsedDocumentProvider? = null,
private val queryValueCustomizer: QueryValueCustomizer = QueryValueCustomizer { query -> query }
) : DgsQueryExecutor {
val schema = AtomicReference(defaultSchema)
override fun execute(
query: String?,
variables: Map<String, Any>,
extensions: Map<String, Any>?,
headers: HttpHeaders?,
operationName: String?,
webRequest: WebRequest?
): ExecutionResult {
val graphQLSchema: GraphQLSchema =
if (reloadIndicator.reloadSchema())
schema.updateAndGet { schemaProvider.schema() }
else
schema.get()
val dgsContext = contextBuilder.build(DgsWebMvcRequestData(extensions, headers, webRequest))
val executionResult =
BaseDgsQueryExecutor.baseExecute(
query = queryValueCustomizer.apply(query),
variables = variables,
extensions = extensions,
operationName = operationName,
dgsContext = dgsContext,
graphQLSchema = graphQLSchema,
dataLoaderProvider = dataLoaderProvider,
instrumentation = instrumentation,
queryExecutionStrategy = queryExecutionStrategy,
mutationExecutionStrategy = mutationExecutionStrategy,
idProvider = idProvider,
preparsedDocumentProvider = preparsedDocumentProvider,
)
// Check for NonNullableFieldWasNull errors, and log them explicitly because they don't run through the exception handlers.
val result = executionResult.get()
if (result.errors.size > 0) {
val nullValueError = result.errors.find { it is NonNullableFieldWasNullError }
if (nullValueError != null) {
logger.error(nullValueError.message)
}
}
return result
}
override fun <T> executeAndExtractJsonPath(query: String, jsonPath: String, variables: Map<String, Any>): T {
return JsonPath.read(getJsonResult(query, variables), jsonPath)
}
override fun <T : Any?> executeAndExtractJsonPath(query: String, jsonPath: String, headers: HttpHeaders): T {
return JsonPath.read(getJsonResult(query, emptyMap(), headers), jsonPath)
}
override fun <T : Any?> executeAndExtractJsonPath(query: String, jsonPath: String, servletWebRequest: ServletWebRequest): T {
val httpHeaders = HttpHeaders()
servletWebRequest.headerNames.forEach { name ->
httpHeaders.addAll(name, servletWebRequest.getHeaderValues(name).orEmpty().toList())
}
return JsonPath.read(getJsonResult(query, emptyMap(), httpHeaders, servletWebRequest), jsonPath)
}
override fun <T> executeAndExtractJsonPathAsObject(
query: String,
jsonPath: String,
variables: Map<String, Any>,
clazz: Class<T>,
headers: HttpHeaders?
): T {
val jsonResult = getJsonResult(query, variables, headers)
return try {
parseContext.parse(jsonResult).read(jsonPath, clazz)
} catch (ex: MappingException) {
throw DgsQueryExecutionDataExtractionException(ex, jsonResult, jsonPath, clazz)
}
}
override fun <T> executeAndExtractJsonPathAsObject(
query: String,
jsonPath: String,
variables: Map<String, Any>,
typeRef: TypeRef<T>,
headers: HttpHeaders?
): T {
val jsonResult = getJsonResult(query, variables, headers)
return try {
parseContext.parse(jsonResult).read(jsonPath, typeRef)
} catch (ex: MappingException) {
throw DgsQueryExecutionDataExtractionException(ex, jsonResult, jsonPath, typeRef)
}
}
override fun executeAndGetDocumentContext(query: String, variables: Map<String, Any>): DocumentContext {
return parseContext.parse(getJsonResult(query, variables))
}
override fun executeAndGetDocumentContext(
query: String,
variables: MutableMap<String, Any>,
headers: HttpHeaders?
): DocumentContext {
return parseContext.parse(getJsonResult(query, variables, headers))
}
private fun getJsonResult(query: String, variables: Map<String, Any>, headers: HttpHeaders? = null, servletWebRequest: ServletWebRequest? = null): String {
val executionResult = execute(query, variables, null, headers, null, servletWebRequest)
if (executionResult.errors.size > 0) {
throw QueryException(executionResult.errors)
}
return BaseDgsQueryExecutor.objectMapper.writeValueAsString(executionResult.toSpecification())
}
/**
* Provides the means to identify if executor should reload the [GraphQLSchema] from the given [DgsSchemaProvider].
* If `true` the schema will be reloaded, else the default schema, provided in the cunstructor of the [DefaultDgsQueryExecutor],
* will be used.
*
* @implSpec The implementation should be thread-safe.
*/
@FunctionalInterface
fun interface ReloadSchemaIndicator {
fun reloadSchema(): Boolean
}
companion object {
private val logger: Logger = LoggerFactory.getLogger(DefaultDgsQueryExecutor::class.java)
}
}
| 94 | null | 275 | 2,958 | 8fb490c5b4f0aa012c998dd2855abc2301af6ee4 | 7,827 | dgs-framework | Apache License 2.0 |
fluentui_icons/src/main/java/com/microsoft/fluentui/icons/avataricons/presence/offline/__Medium.kt | anthonysidesap | 454,785,267 | true | {"Kotlin": 2243120, "Shell": 8996} | package com.microsoft.fluentui.icons.avataricons.presence.dnd
import androidx.compose.ui.graphics.vector.ImageVector
import com.microsoft.fluentui.icons.avataricons.presence.DndGroup
import com.microsoft.fluentui.icons.avataricons.presence.dnd.medium.Dark
import com.microsoft.fluentui.icons.avataricons.presence.dnd.medium.Light
import kotlin.collections.List as ____KtList
object MediumGroup
val DndGroup.Medium: MediumGroup
get() = MediumGroup
private var __AllIcons: ____KtList<ImageVector>? = null
val MediumGroup.AllIcons: ____KtList<ImageVector>
get() {
if (__AllIcons != null) {
return __AllIcons!!
}
__AllIcons = listOf(Dark, Light)
return __AllIcons!!
}
| 1 | Kotlin | 2 | 7 | 2b0d10f7b754c189fea210d279487617e5661eaa | 725 | fluentui-android | MIT License |
features/preferences/impl/src/main/kotlin/io/element/android/features/preferences/impl/analytics/AnalyticsSettingsView.kt | element-hq | 546,522,002 | false | null | /*
* Copyright (c) 2023 New Vector Ltd
*
* 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 io.element.android.features.preferences.impl.analytics
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import io.element.android.features.analytics.api.preferences.AnalyticsPreferencesView
import io.element.android.libraries.designsystem.components.preferences.PreferenceView
import io.element.android.libraries.designsystem.preview.ElementPreviewDark
import io.element.android.libraries.designsystem.preview.ElementPreviewLight
import io.element.android.libraries.ui.strings.CommonStrings
@Composable
fun AnalyticsSettingsView(
state: AnalyticsSettingsState,
onBackPressed: () -> Unit,
modifier: Modifier = Modifier,
) {
PreferenceView(
modifier = modifier,
onBackPressed = onBackPressed,
title = stringResource(id = CommonStrings.common_analytics)
) {
AnalyticsPreferencesView(
state = state.analyticsState,
)
}
}
@Preview
@Composable
internal fun AnalyticsSettingsViewLightPreview(@PreviewParameter(AnalyticsSettingsStateProvider::class) state: AnalyticsSettingsState) =
ElementPreviewLight { ContentToPreview(state) }
@Preview
@Composable
internal fun AnalyticsSettingsViewDarkPreview(@PreviewParameter(AnalyticsSettingsStateProvider::class) state: AnalyticsSettingsState) =
ElementPreviewDark { ContentToPreview(state) }
@Composable
private fun ContentToPreview(state: AnalyticsSettingsState) {
AnalyticsSettingsView(
state = state,
onBackPressed = {},
)
}
| 91 | null | 48 | 955 | 31d0621fa15fe153bfd36104e560c9703eabe917 | 2,274 | element-x-android | Apache License 2.0 |
domain/src/main/java/me/androidbox/domain/authorization/usecases/imp/ResetPasswordUseCaseImp.kt | steve1rm | 804,664,997 | false | {"Kotlin": 152478} | package me.androidbox.domain.authorization.usecases.imp
import me.androidbox.domain.authorization.models.ResetPasswordModel
import me.androidbox.domain.authorization.usecases.ResetPasswordUseCase
import me.androidbox.domain.repository.APIResponse
import me.androidbox.domain.repository.AuthorizationRepository
class ResetPasswordUseCaseImp(
private val authorizationRepository: AuthorizationRepository
) : ResetPasswordUseCase {
override suspend fun execute(email: String): APIResponse<ResetPasswordModel> {
return authorizationRepository.resetPassword(email)
}
} | 0 | Kotlin | 0 | 0 | 5b80ada6d22093fc66d36debe028eaa15cc4886e | 585 | BusbyNimbleSurvey | MIT License |
domain/src/main/java/me/androidbox/domain/authorization/usecases/imp/ResetPasswordUseCaseImp.kt | steve1rm | 804,664,997 | false | {"Kotlin": 152478} | package me.androidbox.domain.authorization.usecases.imp
import me.androidbox.domain.authorization.models.ResetPasswordModel
import me.androidbox.domain.authorization.usecases.ResetPasswordUseCase
import me.androidbox.domain.repository.APIResponse
import me.androidbox.domain.repository.AuthorizationRepository
class ResetPasswordUseCaseImp(
private val authorizationRepository: AuthorizationRepository
) : ResetPasswordUseCase {
override suspend fun execute(email: String): APIResponse<ResetPasswordModel> {
return authorizationRepository.resetPassword(email)
}
} | 0 | Kotlin | 0 | 0 | 5b80ada6d22093fc66d36debe028eaa15cc4886e | 585 | BusbyNimbleSurvey | MIT License |
kgl/src/jvmMain/kotlin/com/danielgergely/kgl/Buffer.kt | gergelydaniel | 204,889,044 | false | {"Kotlin": 128967} | package com.danielgergely.kgl
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.IntBuffer
public actual abstract class Buffer internal constructor(
@JvmField @PublishedApi internal val javaBuffer: java.nio.Buffer
) {
public inline fun withJavaBuffer(block: (java.nio.Buffer) -> Unit) {
val positionBefore = javaBuffer.position()
block(javaBuffer)
javaBuffer.position(positionBefore)
}
}
public actual class FloatBuffer(buffer: FloatBuffer) : Buffer(buffer) {
public actual constructor(buffer: Array<Float>) : this(buffer.toFloatArray())
public actual constructor(buffer: FloatArray) : this(alloc(buffer.size).apply { put(buffer) })
public actual constructor(size: Int) : this(alloc(size))
private companion object {
private fun alloc(size: Int) =
ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asFloatBuffer()
}
public actual var position: Int
get() = floatBuffer.position()
set(value) {
floatBuffer.position(value)
}
private val floatBuffer: FloatBuffer = buffer
public actual fun put(f: Float) {
floatBuffer.put(f)
}
public actual fun put(floatArray: FloatArray): Unit = put(floatArray, 0, floatArray.size)
public actual fun put(floatArray: FloatArray, offset: Int, length: Int) {
floatBuffer.put(floatArray, offset, length)
}
public actual operator fun set(pos: Int, f: Float) {
floatBuffer.put(pos, f)
}
public actual fun get(): Float = floatBuffer.get()
public actual fun get(floatArray: FloatArray) {
get(floatArray, 0, floatArray.size)
}
public actual fun get(floatArray: FloatArray, offset: Int, length: Int) {
floatBuffer.get(floatArray, offset, length)
}
public actual operator fun get(pos: Int): Float = floatBuffer.get(pos)
}
public actual class ByteBuffer(buffer: ByteBuffer) : Buffer(buffer) {
public actual constructor(buffer: Array<Byte>) : this(buffer.toByteArray())
public actual constructor(buffer: ByteArray) : this(alloc(buffer.size).apply { put(buffer) })
public actual constructor(size: Int) : this(alloc(size))
private companion object {
private fun alloc(size: Int) = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
}
public actual var position: Int
get() = byteBuffer.position()
set(value) {
byteBuffer.position(value)
}
private val byteBuffer: ByteBuffer = buffer
public actual fun put(b: Byte) {
byteBuffer.put(b)
}
public actual fun put(byteArray: ByteArray): Unit = put(byteArray, 0, byteArray.size)
public actual fun put(byteArray: ByteArray, offset: Int, length: Int) {
byteBuffer.put(byteArray, offset, length)
}
public actual operator fun set(pos: Int, b: Byte) {
byteBuffer.put(pos, b)
}
public actual fun get(): Byte = byteBuffer.get()
public actual fun get(byteArray: ByteArray) {
get(byteArray, 0, byteArray.size)
}
public actual fun get(byteArray: ByteArray, offset: Int, length: Int) {
byteBuffer.get(byteArray, offset, length)
}
public actual operator fun get(pos: Int): Byte = byteBuffer.get(pos)
}
public actual class IntBuffer(private val buffer: IntBuffer) : Buffer(buffer) {
public actual constructor(buffer: Array<Int>) : this(buffer.toIntArray())
public actual constructor(buffer: IntArray) : this(alloc(buffer.size).apply { put(buffer) })
public actual constructor(size: Int) : this(alloc(size))
private companion object {
private fun alloc(size: Int) =
ByteBuffer.allocateDirect(size * 4).order(ByteOrder.nativeOrder()).asIntBuffer()
}
public actual var position: Int
get() = buffer.position()
set(value) {
buffer.position(value)
}
public actual fun put(i: Int) {
buffer.put(i)
}
public actual fun put(intArray: IntArray): Unit = put(intArray, 0, intArray.size)
public actual fun put(intArray: IntArray, offset: Int, length: Int) {
buffer.put(intArray, offset, length)
}
public actual operator fun set(pos: Int, i: Int) {
buffer.put(pos, i)
}
public actual fun get(): Int = buffer.get()
public actual fun get(intArray: IntArray) {
get(intArray, 0, intArray.size)
}
public actual fun get(intArray: IntArray, offset: Int, length: Int) {
buffer.get(intArray, offset, length)
}
public actual operator fun get(pos: Int): Int = buffer.get(pos)
}
| 10 | Kotlin | 7 | 30 | f5311eb0350ec0aaaf6c60e7ab7132073eb07d61 | 4,661 | kgl | MIT License |
mobile_app1/module950/src/main/java/module950packageKt0/Foo10.kt | uber-common | 294,831,672 | false | null | package module950packageKt0;
annotation class Foo10Fancy
@Foo10Fancy
class Foo10 {
fun foo0(){
module950packageKt0.Foo9().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 232 | android-build-eval | Apache License 2.0 |
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/enchantment/PuncturingEnchantment.kt | fzzyhmstrs | 461,338,617 | false | null | package me.fzzyhmstrs.amethyst_imbuement.enchantment
import me.fzzyhmstrs.amethyst_imbuement.config.AiConfig
import net.minecraft.enchantment.Enchantment
import net.minecraft.enchantment.EnchantmentTarget
import net.minecraft.enchantment.Enchantments
import net.minecraft.entity.Entity
import net.minecraft.entity.EquipmentSlot
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.damage.DamageSource
import net.minecraft.item.CrossbowItem
import net.minecraft.item.ItemStack
import net.minecraft.item.TridentItem
class PuncturingEnchantment(weight: Rarity, vararg slot: EquipmentSlot): ConfigDisableEnchantment(weight, EnchantmentTarget.CROSSBOW,*slot) {
override fun getMinPower(level: Int): Int {
return 20 + level * 10
}
override fun getMaxPower(level: Int): Int {
return getMinPower(level) + 50
}
override fun getMaxLevel(): Int {
return AiConfig.enchants.getAiMaxLevel(id.toString(),6)
}
override fun canAccept(other: Enchantment): Boolean {
return super.canAccept(other) && other !== Enchantments.PIERCING && other !== Enchantments.MULTISHOT && other !== Enchantments.IMPALING
}
override fun isAcceptableItem(stack: ItemStack): Boolean {
return ((stack.item is CrossbowItem) || (stack.item is TridentItem)) && checkEnabled()
}
override fun onTargetDamaged(user: LivingEntity, target: Entity, level: Int) {
if (user.world.isClient || !checkEnabled()) return
if (target is LivingEntity) {
if(!target.isDead){
target.setInvulnerable(false) //these two lines take away damage invulnerability
target.timeUntilRegen = 0
target.damage(user.damageSources.generic(), 0.5f * level) //GENERIC damage bypasses armor
}
}
}
} | 9 | null | 8 | 4 | 7e51e5528c9495d818a3ae1c586d7cb6d5f5ece0 | 1,827 | ai | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/HorseshoeBroken.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.HorseshoeBroken: ImageVector
get() {
if (_horseshoeBroken != null) {
return _horseshoeBroken!!
}
_horseshoeBroken = Builder(name = "HorseshoeBroken", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 8.0f)
curveToRelative(0.737f, 0.0f, 1.445f, 0.273f, 1.993f, 0.771f)
curveToRelative(0.318f, 0.288f, 0.74f, 0.427f, 1.168f, 0.379f)
lineToRelative(2.885f, -0.312f)
curveToRelative(0.476f, -0.052f, 0.898f, -0.327f, 1.138f, -0.742f)
lineToRelative(1.404f, -2.435f)
curveToRelative(0.314f, -0.545f, 0.255f, -1.229f, -0.148f, -1.711f)
curveTo(18.341f, 1.439f, 15.265f, 0.0f, 12.0f, 0.0f)
curveTo(5.935f, 0.0f, 1.0f, 4.935f, 1.0f, 11.0f)
curveToRelative(0.0f, 3.634f, 1.103f, 7.64f, 1.875f, 10.0f)
horizontalLineToRelative(-0.375f)
curveToRelative(-0.829f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.671f, 1.5f, 1.5f, 1.5f)
horizontalLineToRelative(5.999f)
curveToRelative(0.769f, 0.0f, 1.483f, -0.345f, 1.96f, -0.947f)
curveToRelative(0.477f, -0.601f, 0.649f, -1.373f, 0.474f, -2.118f)
curveToRelative(-0.095f, -0.409f, -0.216f, -0.9f, -0.35f, -1.449f)
curveToRelative(-0.592f, -2.417f, -1.583f, -6.463f, -1.583f, -8.485f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
close()
moveTo(4.792f, 7.552f)
lineToRelative(1.655f, 1.182f)
curveToRelative(-0.286f, 0.7f, -0.447f, 1.464f, -0.447f, 2.265f)
horizontalLineToRelative(-2.0f)
curveToRelative(0.0f, -1.236f, 0.29f, -2.402f, 0.792f, -3.448f)
close()
moveTo(8.242f, 6.329f)
lineToRelative(-1.668f, -1.191f)
curveToRelative(1.078f, -0.998f, 2.426f, -1.706f, 3.926f, -1.992f)
verticalLineToRelative(2.051f)
curveToRelative(-0.837f, 0.216f, -1.604f, 0.605f, -2.258f, 1.132f)
close()
moveTo(16.966f, 5.936f)
lineToRelative(-1.514f, 0.164f)
curveToRelative(-0.591f, -0.42f, -1.255f, -0.711f, -1.952f, -0.893f)
lineTo(13.5f, 3.141f)
curveToRelative(1.468f, 0.279f, 2.828f, 0.966f, 3.932f, 1.988f)
lineToRelative(-0.466f, 0.808f)
close()
moveTo(6.045f, 21.0f)
curveToRelative(-0.49f, -1.395f, -1.371f, -4.15f, -1.799f, -7.0f)
horizontalLineToRelative(2.065f)
curveToRelative(0.342f, 2.041f, 0.903f, 4.34f, 1.359f, 6.199f)
curveToRelative(0.069f, 0.283f, 0.135f, 0.552f, 0.195f, 0.801f)
horizontalLineToRelative(-1.82f)
close()
moveTo(21.5f, 21.0f)
horizontalLineToRelative(-0.402f)
curveToRelative(0.635f, -2.004f, 1.515f, -5.211f, 1.814f, -8.358f)
curveToRelative(0.048f, -0.504f, -0.162f, -0.999f, -0.559f, -1.314f)
curveToRelative(-0.396f, -0.316f, -0.925f, -0.41f, -1.407f, -0.251f)
lineToRelative(-2.164f, 0.718f)
lineToRelative(-1.844f, -0.697f)
curveToRelative(-0.435f, -0.163f, -0.921f, -0.118f, -1.317f, 0.126f)
curveToRelative(-0.396f, 0.244f, -0.656f, 0.657f, -0.705f, 1.119f)
curveToRelative(-0.279f, 2.637f, -0.913f, 6.66f, -1.356f, 8.611f)
curveToRelative(-0.169f, 0.743f, 0.007f, 1.511f, 0.482f, 2.106f)
curveToRelative(0.477f, 0.598f, 1.19f, 0.94f, 1.958f, 0.94f)
horizontalLineToRelative(5.5f)
curveToRelative(0.829f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.671f, -1.5f, -1.5f, -1.5f)
close()
moveTo(17.939f, 21.0f)
horizontalLineToRelative(-1.319f)
curveToRelative(0.348f, -1.685f, 0.757f, -4.2f, 1.05f, -6.42f)
lineToRelative(0.55f, 0.208f)
curveToRelative(0.322f, 0.122f, 0.676f, 0.129f, 1.002f, 0.021f)
lineToRelative(0.376f, -0.125f)
curveToRelative(-0.469f, 2.598f, -1.224f, 5.025f, -1.66f, 6.316f)
close()
}
}
.build()
return _horseshoeBroken!!
}
private var _horseshoeBroken: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,507 | icons | MIT License |
CashSDK/src/main/java/cash/just/sdk/model/WacBaseResponse.kt | atmcoin | 259,331,275 | false | null | package cash.just.sdk.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class WacBaseResponse(
@field:Json(name = "result") val result: String,
@field:Json(name = "error") val error: String?) | 3 | null | 2 | 6 | 4ee49b5495878fc704563b4b5bd2de64d4183d75 | 264 | cash-sdk-android | MIT License |
src/main/java/ru/hollowhorizon/hollowengine/common/network/MouseClickedPacket.kt | HollowHorizon | 586,593,959 | false | {"Kotlin": 281958, "Java": 87172, "GLSL": 1597} | package ru.hollowhorizon.hollowengine.common.network
import kotlinx.serialization.Serializable
import net.minecraft.world.entity.player.Player
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.event.entity.player.PlayerEvent
import ru.hollowhorizon.hc.common.network.HollowPacketV2
import ru.hollowhorizon.hc.common.network.HollowPacketV3
import ru.hollowhorizon.hollowengine.client.ClientEvents
@HollowPacketV2(HollowPacketV2.Direction.TO_SERVER)
@Serializable
class MouseClickedPacket(val button: MouseButton) : HollowPacketV3<MouseClickedPacket> {
override fun handle(player: Player, data: MouseClickedPacket) {
MinecraftForge.EVENT_BUS.post(ServerMouseClickedEvent(player, data.button))
}
}
class ServerMouseClickedEvent(player: Player, val button: MouseButton) : PlayerEvent(player)
@HollowPacketV2(HollowPacketV2.Direction.TO_SERVER)
@Serializable
class MouseButtonWaitPacket(val button: MouseButton) : HollowPacketV3<MouseButtonWaitPacket> {
override fun handle(player: Player, data: MouseButtonWaitPacket) {
ClientEvents.canceledButtons.add(data.button)
}
}
@HollowPacketV2(HollowPacketV2.Direction.TO_CLIENT)
@Serializable
class MouseButtonWaitResetPacket : HollowPacketV3<MouseButtonWaitResetPacket> {
override fun handle(player: Player, data: MouseButtonWaitResetPacket) {
ClientEvents.canceledButtons.clear()
}
}
@Serializable
class Container(val data: MouseButton)
enum class MouseButton {
LEFT, RIGHT, MIDDLE;
companion object {
fun from(value: Int): MouseButton {
return entries[value]
}
}
}
| 1 | Kotlin | 5 | 7 | d9c6c9c0d9a7a8e62c24e30548d1cee5c2ef853c | 1,629 | HollowEngine | MIT License |
gallery/src/androidTest/java/academy/compose/gallery/ui/GalleryContentTest.kt | roshanrai06 | 493,086,982 | false | {"Kotlin": 789427} | package academy.compose.gallery.ui
import academy.compose.gallery.R
import academy.compose.gallery.Tags.TAG_DENIED_PERMISSION
import academy.compose.gallery.Tags.TAG_IMAGE_GALLERY
import academy.compose.gallery.Tags.TAG_PROGRESS
import academy.compose.gallery.model.Image
import android.net.Uri
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.platform.app.InstrumentationRegistry
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@ExperimentalFoundationApi
@ExperimentalPermissionsApi
class GalleryContentTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun Image_Gallery_Displayed() {
val permissionState = object : PermissionState {
override val hasPermission: Boolean
get() = true
override val permission: String
get() = ""
override val permissionRequested: Boolean
get() = false
override val shouldShowRationale: Boolean
get() = false
override fun launchPermissionRequest() { }
}
composeTestRule.setContent {
GalleryContent(
media = listOf(Image(0, Uri.EMPTY, "")),
permissionState = permissionState,
openSettings = {}
)
}
composeTestRule
.onNodeWithTag(TAG_IMAGE_GALLERY)
.assertIsDisplayed()
}
@Test
fun Progress_Displayed() {
val permissionState = object : PermissionState {
override val hasPermission: Boolean
get() = true
override val permission: String
get() = ""
override val permissionRequested: Boolean
get() = false
override val shouldShowRationale: Boolean
get() = false
override fun launchPermissionRequest() { }
}
composeTestRule.setContent {
GalleryContent(
media = null,
permissionState = permissionState,
openSettings = {}
)
}
composeTestRule
.onNodeWithTag(TAG_PROGRESS)
.assertIsDisplayed()
}
@Test
fun Denied_Permission_Displayed() {
val permissionState = object : PermissionState {
override val hasPermission: Boolean
get() = false
override val permission: String
get() = ""
override val permissionRequested: Boolean
get() = true
override val shouldShowRationale: Boolean
get() = false
override fun launchPermissionRequest() { }
}
composeTestRule.setContent {
GalleryContent(
media = null,
permissionState = permissionState,
openSettings = {}
)
}
composeTestRule
.onNodeWithTag(TAG_DENIED_PERMISSION)
.assertIsDisplayed()
}
@Test
fun Permission_Request_Triggered() {
val permissionState = mock<PermissionState>()
whenever(permissionState.permissionRequested)
.doReturn(false)
whenever(permissionState.hasPermission)
.doReturn(false)
composeTestRule.setContent {
GalleryContent(
media = null,
permissionState = permissionState,
openSettings = {}
)
}
val grantPermission = InstrumentationRegistry.getInstrumentation().targetContext
.getString(R.string.permission_explainer_action)
composeTestRule
.onNodeWithText(grantPermission)
.performClick()
verify(permissionState).launchPermissionRequest()
}
} | 0 | Kotlin | 0 | 0 | cabaed56980873e857a3b62e99295d6c617b10af | 4,314 | learning-compose | Apache License 2.0 |
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/model/rest/UploadSignatureQueryBuilder.kt | matrix-org | 287,466,066 | false | null | /*
* Copyright 2020 New Vector Ltd
* Copyright 2020 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.matrix.android.sdk.internal.crypto.model.rest
import org.matrix.android.sdk.internal.crypto.model.CryptoCrossSigningKey
import org.matrix.android.sdk.internal.crypto.model.CryptoDeviceInfo
import org.matrix.android.sdk.internal.crypto.model.toRest
/**
* Helper class to build CryptoApi#uploadSignatures params
*/
internal data class UploadSignatureQueryBuilder(
private val deviceInfoList: MutableList<CryptoDeviceInfo> = mutableListOf(),
private val signingKeyInfoList: MutableList<CryptoCrossSigningKey> = mutableListOf()
) {
fun withDeviceInfo(deviceInfo: CryptoDeviceInfo) = apply {
deviceInfoList.add(deviceInfo)
}
fun withSigningKeyInfo(info: CryptoCrossSigningKey) = apply {
signingKeyInfoList.add(info)
}
fun build(): Map<String, Map<String, @JvmSuppressWildcards Any>> {
val map = HashMap<String, HashMap<String, Any>>()
val usersList = (deviceInfoList.map { it.userId } + signingKeyInfoList.map { it.userId })
.distinct()
usersList.forEach { userID ->
val userMap = HashMap<String, Any>()
deviceInfoList.filter { it.userId == userID }.forEach { deviceInfo ->
userMap[deviceInfo.deviceId] = deviceInfo.toRest()
}
signingKeyInfoList.filter { it.userId == userID }.forEach { keyInfo ->
keyInfo.unpaddedBase64PublicKey?.let { base64Key ->
userMap[base64Key] = keyInfo.toRest()
}
}
map[userID] = userMap
}
return map
}
}
| 75 | null | 6 | 97 | 55cc7362de34a840c67b4bbb3a14267bc8fd3b9c | 2,249 | matrix-android-sdk2 | Apache License 2.0 |
FottballScheduleApp/app/src/main/java/com/achmadabrar/myapplication/core/di/ViewModelFactory.kt | achmadabrar | 316,360,868 | false | null | package com.achmadabrar.myapplication.core.di
class ViewModelFactory {
} | 1 | null | 1 | 1 | 707d75bba3461130b977f476de594a566b96f929 | 73 | test_scanner_java | Creative Commons Attribution 4.0 International |
sykepenger-model/src/main/kotlin/no/nav/helse/serde/api/builders/ArbeidsgiverBuilder.kt | navikt | 193,907,367 | false | null | package no.nav.helse.serde.api.builders
import no.nav.helse.Toggle
import no.nav.helse.person.Arbeidsgiver
import no.nav.helse.person.ForkastetVedtaksperiode
import no.nav.helse.person.Vedtaksperiode
import no.nav.helse.person.VilkårsgrunnlagHistorikk
import no.nav.helse.serde.api.ArbeidsgiverDTO
import no.nav.helse.serde.api.GhostPeriodeDTO
import no.nav.helse.serde.api.v2.HendelseDTO
import no.nav.helse.serde.api.v2.buildere.GenerasjonerBuilder
import no.nav.helse.serde.api.v2.buildere.IVilkårsgrunnlagHistorikk
import no.nav.helse.somFødselsnummer
import no.nav.helse.sykdomstidslinje.Sykdomshistorikk
import no.nav.helse.utbetalingslinjer.Utbetaling
import java.time.LocalDateTime
import java.util.*
internal class ArbeidsgiverBuilder(
private val arbeidsgiver: Arbeidsgiver,
vilkårsgrunnlagHistorikk: VilkårsgrunnlagHistorikk,
private val id: UUID,
private val organisasjonsnummer: String,
fødselsnummer: String,
inntektshistorikkBuilder: InntektshistorikkBuilder
) : BuilderState() {
private val utbetalingshistorikkBuilder = UtbetalingshistorikkBuilder()
private val utbetalinger = mutableListOf<Utbetaling>()
private val gruppeIder = mutableMapOf<Vedtaksperiode, UUID>()
private val perioderBuilder = VedtaksperioderBuilder(
arbeidsgiver = arbeidsgiver,
fødselsnummer = fødselsnummer,
inntektshistorikkBuilder = inntektshistorikkBuilder,
gruppeIder = gruppeIder,
vilkårsgrunnlagHistorikk = vilkårsgrunnlagHistorikk
)
private val forkastetPerioderBuilder = VedtaksperioderBuilder(
arbeidsgiver = arbeidsgiver,
fødselsnummer = fødselsnummer,
inntektshistorikkBuilder = inntektshistorikkBuilder,
gruppeIder = gruppeIder,
vilkårsgrunnlagHistorikk = vilkårsgrunnlagHistorikk,
byggerForkastedePerioder = true
)
internal fun build(hendelser: List<HendelseDTO>, fødselsnummer: String, vilkårsgrunnlagHistorikk: IVilkårsgrunnlagHistorikk): ArbeidsgiverDTO {
val utbetalingshistorikk = utbetalingshistorikkBuilder.build()
val ghostPerioder = arbeidsgiver.ghostPerioder()
return ArbeidsgiverDTO(
organisasjonsnummer = organisasjonsnummer,
id = id,
vedtaksperioder = perioderBuilder.build(hendelser, utbetalingshistorikk) + forkastetPerioderBuilder.build(hendelser, utbetalingshistorikk).filter { it.tilstand.visesNårForkastet() },
utbetalingshistorikk = utbetalingshistorikk,
generasjoner = if (Toggle.SpeilApiV2.enabled) GenerasjonerBuilder(hendelser, fødselsnummer.somFødselsnummer(), vilkårsgrunnlagHistorikk, arbeidsgiver).build() else null,
ghostPerioder = ghostPerioder?.ghostPerioder?.map {
GhostPeriodeDTO(
fom = it.fom.coerceAtLeast(it.skjæringstidspunkt),
tom = it.tom,
skjæringstidspunkt = it.skjæringstidspunkt,
vilkårsgrunnlagHistorikkInnslagId = ghostPerioder.historikkInnslagId
)
} ?: emptyList()
)
}
override fun preVisitPerioder(vedtaksperioder: List<Vedtaksperiode>) {
pushState(perioderBuilder)
}
override fun preVisitForkastedePerioder(vedtaksperioder: List<ForkastetVedtaksperiode>) {
pushState(forkastetPerioderBuilder)
}
override fun preVisitUtbetalinger(utbetalinger: List<Utbetaling>) {
this.utbetalinger.addAll(utbetalinger)
pushState(utbetalingshistorikkBuilder)
}
override fun preVisitSykdomshistorikk(sykdomshistorikk: Sykdomshistorikk) {
pushState(utbetalingshistorikkBuilder)
}
override fun preVisitUtbetalingstidslinjeberegning(
id: UUID,
tidsstempel: LocalDateTime,
organisasjonsnummer: String,
sykdomshistorikkElementId: UUID,
inntektshistorikkInnslagId: UUID,
vilkårsgrunnlagHistorikkInnslagId: UUID
) {
utbetalingshistorikkBuilder.preVisitUtbetalingstidslinjeberegning(
id,
tidsstempel,
organisasjonsnummer,
sykdomshistorikkElementId,
inntektshistorikkInnslagId,
vilkårsgrunnlagHistorikkInnslagId
)
}
override fun postVisitArbeidsgiver(
arbeidsgiver: Arbeidsgiver,
id: UUID,
organisasjonsnummer: String
) {
popState()
}
}
| 0 | Kotlin | 2 | 3 | 9572b362ab94daa6a730331c309a1cdc0ec25e3e | 4,410 | helse-spleis | MIT License |
server/src/main/kotlin/com/thoughtworks/archguard/report/controller/BadSmellThresholdController.kt | archguard | 460,910,110 | false | {"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32} | package com.thoughtworks.archguard.report.controller
import com.thoughtworks.archguard.report.domain.badsmell.ThresholdSuiteService
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/bad-smell-threshold")
class BadSmellThresholdController(val thresholdSuiteService: ThresholdSuiteService) {
@PostMapping("/reload")
fun reloadThresholdCache() {
thresholdSuiteService.reloadAllSuites()
}
}
| 1 | Kotlin | 89 | 575 | 049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8 | 581 | archguard | MIT License |
games-mpp/games-server/src/main/kotlin/net/zomis/games/server/test/TestPlayMenu.kt | Zomis | 125,767,793 | false | null | package net.zomis.games.server.test
import net.zomis.games.dsl.DslConsoleSetup
import net.zomis.games.server2.ServerGames
import java.io.File
import java.util.*
object TestPlayMenu {
val root = File("playthroughs")
val choices = TestPlayChoices(
gameName = { ServerGames.games.keys.random() },
playersCount = { it.setup().playersCount.random() },
config = { it.setup().getDefaultConfig() }
)
fun main(game: String? = null) {
val f = root
f.walk().filter { it.isFile && it.name.endsWith(".json") }.forEach {
if (game == null || it.absolutePath.contains(game)) {
println(it.absolutePath)
PlayTests.fullJsonTest(it, choices, true)
}
}
}
fun menu() {
println("Choose your option")
println("C: Create new test")
println("F: Run a file test")
println("A: Run all tests")
println("G: Run all tests for specific game")
val scanner = Scanner(System.`in`)
when (scanner.nextLine()) {
"" -> return
"f", "F" -> {
println("Enter file name")
var f = root
while (!f.isFile) {
f.listFiles()!!.forEach {
println(it.name)
}
f = File(f, scanner.nextLine())
}
PlayTests.fullJsonTest(f, choices, true)
}
"c", "C" -> {
val gameSpec = DslConsoleSetup().chooseGame(scanner)
val setup = ServerGames.entrypoint(gameSpec.name)?.setup()
?: throw IllegalArgumentException("Invalid game type: ${gameSpec.name}")
println("Enter players (${setup.playersCount})")
val playersCount = scanner.nextLine().toInt()
PlayTests.createNew(File("playthroughs", "t.json"), gameSpec.name, playersCount, null)
}
"a", "A" -> main()
"g", "G" -> {
ServerGames.games.map { it.key }.sorted().forEach { println(it) }
println("Enter game name")
val chosenGame = scanner.nextLine()
main(chosenGame)
}
}
}
fun file(s: String): File = File(root, s)
}
fun main() {
// PlayTests.fullJsonTest(TestPlayMenu.file("TTTUpgrade.json"), TestPlayMenu.choices, true)
// PlayTests.fullJsonTest(TestPlayMenu.file("UR.json"), TestPlayMenu.choices, true)
// PlayTests.fullJsonTest(TestPlayMenu.file("Backgammon.json"), TestPlayMenu.choices, true)
// PlayTests.fullJsonTest(TestPlayMenu.file("KingDomino.json"), TestPlayMenu.choices, true)
TestPlayMenu.menu()
}
| 89 | null | 5 | 17 | dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0 | 2,741 | Games | MIT License |
gallery/src/commonMain/kotlin/com/konyaco/fluent/gallery/screen/basicinput/ToggleSwitchScreen.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11419712, "Java": 256912} | package com.konyaco.fluent.gallery.screen.basicinput
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.konyaco.fluent.component.Switcher
import com.konyaco.fluent.gallery.annotation.Component
import com.konyaco.fluent.gallery.annotation.Sample
import com.konyaco.fluent.gallery.component.ComponentPagePath
import com.konyaco.fluent.gallery.component.GalleryPage
import com.konyaco.fluent.gallery.component.TodoComponent
import com.konyaco.fluent.source.generated.FluentSourceFile
@Component(index = 13, description = "A switch that can be toggled between 2 states.")
@Composable
fun ToggleSwitchScreen() {
GalleryPage(
title = "ToggleSwitch",
description = "Use ToggleSwitch controls to present users with exactly two mutually exclusive options (like on/off), where choosing an option results in an immediate commit. A toggle switch should have a single label.",
componentPath = FluentSourceFile.Switcher,
galleryPath = ComponentPagePath.ToggleSwitchScreen
) {
Section(
title = "A simple ToggleSwitch.",
sourceCode = sourceCodeOfToggleSwitchSample,
content = { ToggleSwitchSample() }
)
Section(
title = "A ToggleSwitch with custom header and content.",
sourceCode = ""
) {
TodoComponent()
}
}
}
@Sample
@Composable
private fun ToggleSwitchSample() {
var checked by remember { mutableStateOf(false) }
Switcher(checked, { checked = it }, text = if (checked) "On" else "Off")
} | 8 | Kotlin | 10 | 262 | 293d7ab02d80fb9fdd372826fdc0b42b1d6e0019 | 1,715 | compose-fluent-ui | Apache License 2.0 |
src/commonTest/kotlin/io/rebble/libpebblecommon/packets/AppMessageTest.kt | pebble-dev | 264,919,199 | false | {"Kotlin": 217944} | package io.rebble.libpebblecommon.packets
import assertIs
import assertUByteArrayEquals
import com.benasher44.uuid.Uuid
import com.benasher44.uuid.uuidFrom
import io.rebble.libpebblecommon.protocolhelpers.PebblePacket
import kotlin.test.Test
import kotlin.test.assertEquals
internal class AppMessageTest {
@Test
fun serializeDeserializePushMessage() {
val testPushMessage = AppMessage.AppMessagePush(
5u,
uuidFrom("30880933-cead-49f6-ba94-3a6f8cd3218a"),
listOf(
AppMessageTuple.createUByteArray(77u, ubyteArrayOf(1u, 170u, 245u)),
AppMessageTuple.createString(6710u, "Hello World"),
AppMessageTuple.createString(7710u, "Emoji: \uD83D\uDC7D."),
AppMessageTuple.createByte(38485u, -7),
AppMessageTuple.createUByte(2130680u, 177u.toUByte()),
AppMessageTuple.createShort(2845647u, -20),
AppMessageTuple.createUShort(2845648u, 49885u.toUShort()),
AppMessageTuple.createInt(2845649u, -707573),
AppMessageTuple.createUInt(2845650u, 2448461u)
)
)
val bytes = testPushMessage.serialize()
val newMessage = PebblePacket.deserialize(bytes)
assertIs<AppMessage.AppMessagePush>(newMessage)
val list = newMessage.dictionary.list
assertEquals(testPushMessage.dictionary.list.size, list.size)
assertUByteArrayEquals(ubyteArrayOf(1u, 170u, 245u), list[0].dataAsBytes)
assertEquals("Hello World", list[1].dataAsString)
assertEquals("Emoji: \uD83D\uDC7D.", list[2].dataAsString)
assertEquals(-7, list[3].dataAsSignedNumber)
assertEquals(177, list[4].dataAsUnsignedNumber)
assertEquals(-20, list[5].dataAsSignedNumber)
assertEquals(49885, list[6].dataAsUnsignedNumber)
assertEquals(-707573, list[7].dataAsSignedNumber)
assertEquals(2448461, list[8].dataAsUnsignedNumber)
assertEquals(testPushMessage, newMessage)
}
@Test
fun serializeDeserializeAckMessage() {
val testPushMessage = AppMessage.AppMessageACK(
74u
)
val bytes = testPushMessage.serialize()
val newMessage = PebblePacket.deserialize(bytes)
assertIs<AppMessage.AppMessageACK>(newMessage)
assertEquals(74u, newMessage.transactionId.get())
}
@Test
fun serializeDeserializeNackMessage() {
val testPushMessage = AppMessage.AppMessageNACK(
244u
)
val bytes = testPushMessage.serialize()
val newMessage = PebblePacket.deserialize(bytes)
assertIs<AppMessage.AppMessageNACK>(newMessage)
assertEquals(244u, newMessage.transactionId.get())
}
@Test
fun appMessageShortShouldBeLittleEndian() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createShort(0u, -50),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
3u,
2u, 0u,
206u, 255u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
@Test
fun appMessageUShortShouldBeLittleEndian() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createUShort(0u, 4876u),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
2u,
2u, 0u,
12u, 19u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
@Test
fun appMessageIntShouldBeLittleEndian() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createInt(0u, -90000),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
3u,
4u, 0u,
112u, 160u, 254u, 255u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
@Test
fun appMessageUIntShouldBeLittleEndian() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createUInt(0u, 900000u),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
2u,
4u, 0u,
160u, 187u, 13u, 0u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
@Test
fun appMessageStringShouldBeBigEndianAndTerminatedWithZero() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createString(0u, "Hello"),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
1u,
6u, 0u,
'H'.code.toUByte(),
'e'.code.toUByte(),
'l'.code.toUByte(),
'l'.code.toUByte(),
'o'.code.toUByte(),
0u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
@Test
fun appMessageBytesShouldBeBigEndian() {
val testPushMessage = AppMessage.AppMessagePush(
0u,
Uuid(0L, 0L),
listOf(
AppMessageTuple.createUByteArray(0u, ubyteArrayOf(1u, 2u, 3u)),
)
)
val expectedMessage = ubyteArrayOf(
1u, 0u, 0u, 0u,
0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
0u, 0u, 0u, 0u,
0u, 1u,
0u, 0u, 0u, 0u,
0u,
3u, 0u,
1u, 2u, 3u
)
assertUByteArrayEquals(
expectedMessage,
testPushMessage.m.toBytes()
)
}
} | 1 | Kotlin | 4 | 3 | cc6b8fbee0503c57d545b68853926f6c9191e072 | 6,835 | libpebblecommon | Apache License 2.0 |
idea/testData/quickfix/suppress/availability/memberSuppressForMember.kt | JakeWharton | 99,388,807 | false | null | // "Suppress 'REDUNDANT_NULLABLE' for fun foo" "true"
class C {
[suppress("REDUNDANT_NULLABLE")]
fun foo(): String?<caret>? = null
} | 214 | null | 4829 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 141 | kotlin | Apache License 2.0 |
base/src/main/java/com/nimroddayan/commitbrowser/common/recyclerview/OnLoadMoreScrollListener.kt | Nimrodda | 175,999,170 | false | null | /*
* Copyright 2019 <NAME> <EMAIL>
*
* 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.codepond.commitbrowser.common.recyclerview
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import timber.log.Timber
abstract class OnLoadMoreScrollListener(
private val threshold: Int
) : RecyclerView.OnScrollListener() {
private var loading = false
private var totalCountBeforeLoad: Int = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val visibleCount = layoutManager.childCount
val totalCount = layoutManager.itemCount
val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
Timber.v("visibleCount = %d", visibleCount)
Timber.v("totalCount = %d", totalCount)
Timber.v("lastVisibleItemPosition = %d", lastVisibleItemPosition)
if (!loading && lastVisibleItemPosition == totalCount - 1 - threshold) {
loading = true
totalCountBeforeLoad = totalCount
Timber.v("Loading more...")
onLoadMore()
} else if (loading && totalCount > totalCountBeforeLoad) {
Timber.v("Finished loading")
loading = false
}
}
protected abstract fun onLoadMore()
}
| 1 | null | 9 | 56 | c633a321eeb9f6d8aea2f42408d041553b4e938c | 1,902 | github-commit-browser | Apache License 2.0 |
app/src/main/java/antuere/how_are_you/presentation/screens/secure_entry/ui_compose/SecureEntryScreenContent.kt | antuere | 526,507,044 | false | null | package antuere.how_are_you.presentation.screens.secure_entry.ui_compose
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import antuere.how_are_you.R
import antuere.how_are_you.presentation.base.ui_compose_components.IconApp
import antuere.how_are_you.presentation.base.ui_compose_components.pin_code.NumericKeypadWrapper
import antuere.how_are_you.presentation.base.ui_compose_components.pin_code.PinCirclesIndicatesWrapper
import antuere.how_are_you.presentation.screens.secure_entry.state.SecureEntryIntent
import antuere.how_are_you.presentation.screens.secure_entry.state.SecureEntryState
import antuere.how_are_you.util.extensions.fixedSize
import antuere.how_are_you.util.extensions.paddingTopBar
@Composable
fun SecureEntryScreenContent(
viewState: () -> SecureEntryState,
onIntent: (SecureEntryIntent) -> Unit,
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.paddingTopBar()
) {
IconApp()
Spacer(modifier = Modifier.weight(0.9F))
Text(text = stringResource(id = R.string.enter_a_pin))
Spacer(modifier = Modifier.weight(0.2F))
PinCirclesIndicatesWrapper { viewState().pinCirclesState }
Spacer(modifier = Modifier.weight(0.4F))
NumericKeypadWrapper(
onClick = { onIntent(SecureEntryIntent.NumberClicked(it)) },
onClickClear = { onIntent(SecureEntryIntent.PinStateReset) },
isShowBiometricBtn = { viewState().isShowBiometricBtn },
onClickBiometric = { onIntent(SecureEntryIntent.BiometricBtnClicked) },
)
Spacer(modifier = Modifier.weight(0.4F))
TextButton(onClick = { onIntent(SecureEntryIntent.SignOutBtnClicked) }) {
Text(
text = stringResource(id = R.string.sign_out),
fontSize = 14f.fixedSize,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.weight(0.1F))
}
} | 1 | Kotlin | 1 | 1 | dccddea7bf36f0910b87c09becd0de2d74ac26b2 | 2,533 | HowAreYou | Apache License 2.0 |
presenter/src/main/java/cn/woyeshi/presenter/base/IBaseDialog.kt | wys619 | 137,435,286 | false | {"Java": 102079, "Kotlin": 56934} | package cn.woyeshi.presenter.base
/**
* Created by wys on 2017/11/8.
*/
interface IBaseDialog : IBaseView {
} | 1 | Java | 1 | 2 | 4d4cbc3e30d503220ab39ef42308ff9872465829 | 112 | android_framework | Apache License 2.0 |
app/src/main/java/xyz/tberghuis/floatingtimer/composables/BackgroundTransCheckbox.kt | tberghuis | 500,632,576 | false | {"Kotlin": 183666, "Ruby": 955} | package xyz.tberghuis.floatingtimer.composables
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import xyz.tberghuis.floatingtimer.R
interface BackgroundTransCheckboxVm {
var isBackgroundTransparent: Boolean
}
@Composable
fun ColumnScope.BackgroundTransCheckbox(
modifier: Modifier = Modifier,
vm: BackgroundTransCheckboxVm
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(
checked = vm.isBackgroundTransparent,
onCheckedChange = {
vm.isBackgroundTransparent = it
},
)
Text(stringResource(R.string.transparent_background))
}
}
@Preview
@Composable
fun PreviewBackgroundTransCheckbox() {
val vm = remember {
object : BackgroundTransCheckboxVm {
override var isBackgroundTransparent by mutableStateOf(false)
}
}
Column(
Modifier
.fillMaxSize()
.border(3.dp, Color.Red),
verticalArrangement = Arrangement.Center,
) {
BackgroundTransCheckbox(vm = vm)
}
} | 22 | Kotlin | 6 | 78 | c6f792d5b7a339a93a88511421b5f72ea5053df6 | 1,795 | FloatingCountdownTimer | MIT License |
donut-kata/src/main/kotlin/bnymellon/codekatas/donutkatakotlin/Customer.kt | BNYMellon | 105,218,129 | false | null | /*
* Copyright 2022 The Bank of New York Mellon.
*
* 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 bnymellon.codekatas.donutkatakotlin
import org.eclipse.collections.api.list.ListIterable
import org.eclipse.collections.api.set.SetIterable
import org.eclipse.collections.impl.factory.Lists
class Customer(val name: String?)
{
private val deliveries = Lists.mutable.empty<Delivery>()
override fun equals(other: Any?): Boolean
{
if (this === other)
{
return true
}
if (other == null || javaClass != other.javaClass)
{
return false
}
val customer = other as Customer?
return this.name == customer!!.name
}
override fun hashCode(): Int
{
return this.name?.hashCode() ?: 0
}
fun named(name: String): Boolean
{
return name == this.name
}
fun addDelivery(delivery: Delivery)
{
this.deliveries.add(delivery)
}
fun getDeliveries(): ListIterable<Delivery>
{
return this.deliveries.asUnmodifiable()
}
val totalDonutsOrdered: Long
get() = this.deliveries.sumOfInt { it.totalDonuts }
val donutTypesOrdered: SetIterable<DonutType>
get() = this.deliveries
.flatCollect { it.donuts }
.collect { it.type }
.toSet()
override fun toString(): String
{
return "Customer(" +
"name='" + this.name + '\'' +
')'
}
}
| 8 | null | 98 | 392 | 093772e5a8a0707490d3d513875a04b139b8472c | 2,010 | CodeKatas | Apache License 2.0 |
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/parallel/Any.kt | fuookami | 359,831,793 | false | {"Kotlin": 1866628, "Python": 6629} | package fuookami.ospf.kotlin.utils.parallel
import kotlinx.coroutines.*
import fuookami.ospf.kotlin.utils.math.*
import fuookami.ospf.kotlin.utils.error.*
import fuookami.ospf.kotlin.utils.functional.*
suspend inline fun <T> Iterable<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return this.anyParallelly(UInt64.ten, predicate)
}
suspend inline fun <T> Iterable<T>.anyParallelly(
segment: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val iterator = [email protected]()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.any { predicate(it) }
})
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}
} catch (e: CancellationException) {
true
}
}
suspend inline fun <T> Iterable<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return this.tryAnyParallelly(UInt64.ten, predicate)
}
suspend inline fun <T> Iterable<T>.tryAnyParallelly(
segment: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
var error: Error? = null
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val iterator = [email protected]()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.any {
when (val result = predicate(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
false
}
}
}
})
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}.let { Ok(it) }
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(true)
}
}
suspend inline fun <T> Collection<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return (this as Iterable<T>).anyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> Collection<T>.anyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return (this as Iterable<T>).anyParallelly(this.usize / concurrentAmount, predicate)
}
suspend inline fun <T> Collection<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return (this as Iterable<T>).tryAnyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> Collection<T>.tryAnyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return (this as Iterable<T>).tryAnyParallelly(this.usize / concurrentAmount, predicate)
}
suspend inline fun <T> List<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return this.anyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> List<T>.anyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val segmentAmount = [email protected] / concurrentAmount.toInt()
var i = 0
while (i != [email protected]) {
val j = i
val k = i + minOf(
segmentAmount,
[email protected] - i
)
promises.add(async(Dispatchers.Default) {
[email protected](j, k).any { predicate(it) }
})
i = k
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}
} catch (e: CancellationException) {
true
}
}
suspend inline fun <T> List<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return this.tryAnyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> List<T>.tryAnyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
var error: Error? = null
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val segmentAmount = [email protected] / concurrentAmount.toInt()
var i = 0
while (i != [email protected]) {
val j = i
val k = i + minOf(
segmentAmount,
[email protected] - i
)
promises.add(async(Dispatchers.Default) {
[email protected](j, k).any {
when (val result = predicate(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
false
}
}
}
})
i = k
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}.let { Ok(it) }
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(true)
}
}
| 0 | Kotlin | 0 | 1 | a3cff7b2702baba923fcb0fa4a82ed4b84e3a0ff | 6,940 | ospf-kotlin | Apache License 2.0 |
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/parallel/Any.kt | fuookami | 359,831,793 | false | {"Kotlin": 1866628, "Python": 6629} | package fuookami.ospf.kotlin.utils.parallel
import kotlinx.coroutines.*
import fuookami.ospf.kotlin.utils.math.*
import fuookami.ospf.kotlin.utils.error.*
import fuookami.ospf.kotlin.utils.functional.*
suspend inline fun <T> Iterable<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return this.anyParallelly(UInt64.ten, predicate)
}
suspend inline fun <T> Iterable<T>.anyParallelly(
segment: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val iterator = [email protected]()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.any { predicate(it) }
})
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}
} catch (e: CancellationException) {
true
}
}
suspend inline fun <T> Iterable<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return this.tryAnyParallelly(UInt64.ten, predicate)
}
suspend inline fun <T> Iterable<T>.tryAnyParallelly(
segment: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
var error: Error? = null
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val iterator = [email protected]()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.any {
when (val result = predicate(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
false
}
}
}
})
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}.let { Ok(it) }
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(true)
}
}
suspend inline fun <T> Collection<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return (this as Iterable<T>).anyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> Collection<T>.anyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return (this as Iterable<T>).anyParallelly(this.usize / concurrentAmount, predicate)
}
suspend inline fun <T> Collection<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return (this as Iterable<T>).tryAnyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> Collection<T>.tryAnyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return (this as Iterable<T>).tryAnyParallelly(this.usize / concurrentAmount, predicate)
}
suspend inline fun <T> List<T>.anyParallelly(
crossinline predicate: SuspendPredicate<T>
): Boolean {
return this.anyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> List<T>.anyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendPredicate<T>
): Boolean {
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val segmentAmount = [email protected] / concurrentAmount.toInt()
var i = 0
while (i != [email protected]) {
val j = i
val k = i + minOf(
segmentAmount,
[email protected] - i
)
promises.add(async(Dispatchers.Default) {
[email protected](j, k).any { predicate(it) }
})
i = k
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}
} catch (e: CancellationException) {
true
}
}
suspend inline fun <T> List<T>.tryAnyParallelly(
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
return this.tryAnyParallelly(
defaultConcurrentAmount,
predicate
)
}
suspend inline fun <T> List<T>.tryAnyParallelly(
concurrentAmount: UInt64,
crossinline predicate: SuspendTryPredicate<T>
): Ret<Boolean> {
var error: Error? = null
return try {
coroutineScope {
val promises = ArrayList<Deferred<Boolean>>()
val segmentAmount = [email protected] / concurrentAmount.toInt()
var i = 0
while (i != [email protected]) {
val j = i
val k = i + minOf(
segmentAmount,
[email protected] - i
)
promises.add(async(Dispatchers.Default) {
[email protected](j, k).any {
when (val result = predicate(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
false
}
}
}
})
i = k
}
for (promise in promises) {
if (promise.await()) {
cancel()
return@coroutineScope true
}
}
false
}.let { Ok(it) }
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(true)
}
}
| 0 | Kotlin | 0 | 1 | a3cff7b2702baba923fcb0fa4a82ed4b84e3a0ff | 6,940 | ospf-kotlin | Apache License 2.0 |
plugin/src/main/kotlin/com/github/grishberg/profiler/androidstudio/PluginContext.kt | Grigory-Rylov | 256,819,360 | false | null | package com.github.grishberg.profiler.androidstudio
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
class PluginContext(
private val project: Project
) : ProjectComponent {
val adb by lazy { AsAdbWrapper(project, PluginLogger()) }
}
fun Project.context(): PluginContext {
return this.getComponent(PluginContext::class.java)
}
| 19 | Kotlin | 3 | 97 | e0ba609640cea72c301ff1537dc9cdd9b67bfe4c | 393 | android-methods-profiler | Apache License 2.0 |
src/macosMain/kotlin/kaylibkit/kCore/KCore.macos.kt | Its-Kenta | 690,260,636 | false | {"Kotlin": 257105, "Makefile": 2337} | package kaylibkit.kCore
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.convert
import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.osx.proc_pidpath
import platform.posix.F_OK
import platform.posix.PATH_MAX
import platform.posix.access
import platform.posix.getpid
@OptIn(ExperimentalForeignApi::class)
actual fun setTraceLogCallbackInternal(callback: TraceLogCallback) {
kaylibc.SetTraceLogCallback(callback)
}
/**
* Returns the absolute path to the 'resources' folder located at the same location as your executable.
*
* This property provides the path to the 'resources' folder associated with your executable.
* Ensure that a folder named 'resources' is present in the same directory as your executable.
*
* @return The absolute path to the 'resources' folder, or null if it doesn't exist or cannot be determined.
*/
@OptIn(ExperimentalForeignApi::class)
actual inline val resourcePath: String?
get() {
try {
val pid = getpid() // Get the process ID of the current running process.
val buffer = ByteArray(PATH_MAX) // Create a buffer to store the path to the executable file.
// Use the proc_pidpath function to obtain the path to the executable file.
// The result is the length of the path.
val pathLength = proc_pidpath(pid, buffer.refTo(0), buffer.size.convert())
// Check if the path length is less than or equal to zero, indicating an error. Throw exception if error is found
if (pathLength <= 0) throw ResourcePathException("Failed to retrieve executable path.")
val executablePath = buffer.toKString() // Convert the buffer to a Kotlin string to get the full path to the executable.
// Find the index of the last slash character ('/') in the executable path, which separates the directory from the executable file name.
val lastSlashIndex = executablePath.lastIndexOf('/')
if (lastSlashIndex == -1) throw ResourcePathException("Invalid executable path format: $executablePath.")
val executableDir = executablePath.substring(0, lastSlashIndex + 1) // Extract the directory portion of the executable path, including the trailing slash.
val resourceDir = executableDir + "resources" // Return the directory path of the executable file along with the "resources" subdirectory.
// Check if the "resources" directory exists
if (access(resourceDir, F_OK) != 0) throw ResourcePathException("The 'resources' directory does not exist at: $resourceDir, unable to load resources.")
return resourceDir
} catch (e: ResourcePathException) {
println("ResourcePathException: ${e.message}")
return null
}
} | 0 | Kotlin | 0 | 0 | ac1b1a0ec2f6f6f2f85cada81b27b50586069a6b | 2,819 | KaylibKit | zlib License |
app/src/main/java/com/example/android/dagger/dagger/components/AppComponent.kt | SyedNoorullahShah | 326,466,661 | false | null | package com.example.android.dagger.dagger.components
import android.content.Context
import com.example.android.dagger.dagger.modules.StorageModule
import com.example.android.dagger.main.MainActivity
import com.example.android.dagger.user.UserManager
import dagger.BindsInstance
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [StorageModule::class])
interface AppComponent {
fun getUserComponentBuilder(): UserComponent.Builder
fun getLoginComponentBuilder(): LoginComponent.Builder
fun getRegComponentBuilder(): RegistrationComponent.Builder
fun getSplashComponentBuilder(): SplashComponent.Builder
fun getUserManager(): UserManager
@Component.Builder
interface Builder {
fun build(): AppComponent
@BindsInstance
fun context(ctx: Context): Builder
}
} | 0 | Kotlin | 0 | 0 | b9fecd231c6038c7612eb5c7a23b18359795761f | 850 | DaggerDemo | Apache License 2.0 |
compiler/testData/compileKotlinAgainstKotlin/SimpleValAnonymousObject.B.kt | javaljj | 50,647,805 | true | {"Java": 15915057, "Kotlin": 12574163, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 28583, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 6859, "Shell": 4704, "IDL": 4669, "Batchfile": 3703} | import pkg.ClassA
fun main(args: Array<String>) {
val obj = ClassA.DEFAULT
obj.toString()
}
| 0 | Java | 0 | 1 | c9cc9c55cdcc706c1d382a1539998728a2e3ca50 | 101 | kotlin | Apache License 2.0 |
atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImplTest.kt | input-output-hk | 564,174,099 | false | {"Kotlin": 859118, "Gherkin": 3494, "JavaScript": 375} | package io.iohk.atala.prism.walletsdk.pollux
import io.iohk.atala.prism.walletsdk.mercury.ApiMock
import io.iohk.atala.prism.walletsdk.prismagent.CastorMock
import io.ktor.http.HttpStatusCode
import kotlinx.coroutines.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class PolluxImplTest {
lateinit var pollux: PolluxImpl
lateinit var castorMock: CastorMock
lateinit var apiMock: ApiMock
@BeforeTest
fun setup() {
castorMock = CastorMock()
val json =
"{\"name\":\"Schema name\",\"version\":\"1.1\",\"attrNames\":[\"name\",\"surname\"],\"issuerId\":\"did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550\"}"
apiMock = ApiMock(HttpStatusCode.OK, json)
pollux = PolluxImpl(castorMock, apiMock)
}
@Test
fun testGetSchema_whenAnoncred_thenSchemaCorrect() = runTest {
val schema = pollux.getSchema("")
val attrNames = listOf("name", "surname")
assertEquals("Schema name", schema.name)
assertEquals("1.1", schema.version)
assertEquals(attrNames, schema.attrNames)
assertEquals("did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550", schema.issuerId)
}
}
| 3 | Kotlin | 0 | 6 | 1a350ac29d5afcc74906878ddef904d5c6578448 | 1,274 | atala-prism-wallet-sdk-kmm | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/screens/Home.kt | Jorkoh | 347,354,718 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.screens
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.BottomSheetScaffold
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.ui.theme.Elevations
import com.example.androiddevchallenge.ui.theme.Theme
import com.example.androiddevchallenge.ui.theme.greenCustom
import com.example.androiddevchallenge.ui.theme.redCustom
@Composable
fun Home() {
HomeContent()
}
@Composable
fun HomeContent() {
Surface(color = MaterialTheme.colors.background) {
BottomSheetScaffold(
sheetShape = RoundedCornerShape(0.dp),
sheetPeekHeight = 64.dp,
sheetContent = { BottomSheetContent() }
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
TabSelector()
Text(
"Balance",
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier
.paddingFromBaseline(top = 32.dp, bottom = 8.dp)
.padding(horizontal = 16.dp)
)
Text(
"$73,589.01",
style = MaterialTheme.typography.h1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier
.paddingFromBaseline(top = 48.dp, bottom = 24.dp)
.padding(horizontal = 16.dp)
)
Text(
"+412.35 today",
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.greenCustom,
modifier = Modifier
.paddingFromBaseline(top = 16.dp, bottom = 32.dp)
.padding(horizontal = 16.dp)
)
Button(
onClick = {},
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.primary
),
shape = MaterialTheme.shapes.large,
elevation = ButtonDefaults.elevation(
Elevations.buttonElevation,
Elevations.buttonElevation,
Elevations.buttonElevation
),
modifier = Modifier
.height(48.dp)
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
Text(
"TRANSACT",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onPrimary,
)
}
Spacer(Modifier.height(16.dp))
GraphType()
Spacer(Modifier.height(16.dp))
Image(
painter = painterResource(R.drawable.ic_home_illos),
contentDescription = null
)
Spacer(
Modifier
.height(32.dp)
.padding(horizontal = 16.dp)
)
}
}
}
}
@Composable
fun TabSelector() {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
"ACCOUNT",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground,
modifier = Modifier.paddingFromBaseline(top = 64.dp, bottom = 8.dp)
)
Text(
"WATCHLIST",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground.copy(alpha = 0.5f),
modifier = Modifier.paddingFromBaseline(top = 64.dp, bottom = 8.dp)
)
Text(
"PROFILE",
style = MaterialTheme.typography.button,
color = MaterialTheme.colors.onBackground.copy(alpha = 0.5f),
modifier = Modifier.paddingFromBaseline(top = 64.dp, bottom = 8.dp)
)
}
}
@Composable
fun GraphType() {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.horizontalScroll(rememberScrollState())
) {
Spacer(Modifier.width(8.dp))
GraphTypeItem(name = "Week", dropDown = true)
GraphTypeItem(name = "ETFs")
GraphTypeItem(name = "Stocks")
GraphTypeItem(name = "Funds")
GraphTypeItem(name = "Currencies")
GraphTypeItem(name = "Markets")
Spacer(Modifier.width(8.dp))
}
}
@Composable
fun GraphTypeItem(name: String, dropDown: Boolean = false) {
OutlinedButton(
onClick = { },
colors = ButtonDefaults.outlinedButtonColors(
backgroundColor = MaterialTheme.colors.background
),
elevation = ButtonDefaults.elevation(
Elevations.buttonElevation,
Elevations.buttonElevation,
Elevations.buttonElevation
),
border = BorderStroke(
ButtonDefaults.OutlinedBorderSize,
MaterialTheme.colors.onBackground
),
shape = MaterialTheme.shapes.large,
modifier = Modifier.height(40.dp),
) {
Text(
name,
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.onBackground,
modifier = Modifier.paddingFromBaseline(top = 16.dp, bottom = 32.dp)
)
if (dropDown) {
Spacer(modifier = Modifier.width(4.dp))
Icon(
imageVector = Icons.Outlined.ExpandMore,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colors.onBackground
)
}
}
}
@Composable
fun BottomSheetContent() {
LazyColumn(
modifier = Modifier.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
content = {
item {
Text(
"Positions",
style = MaterialTheme.typography.subtitle1,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.paddingFromBaseline(top = 40.dp, bottom = 24.dp)
)
}
items(positions) { position ->
Divider(color = MaterialTheme.colors.onSurface)
PositionItem(position)
}
}
)
}
@Composable
fun PositionItem(item: Item) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.height(56.dp)
.fillMaxWidth()
) {
Column(modifier = Modifier.fillMaxHeight()) {
Text(
item.price,
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.paddingFromBaseline(top = 24.dp)
)
Text(
item.change,
style = MaterialTheme.typography.body1,
color = if (item.changeDirection == ChangeDirection.Positive) {
MaterialTheme.colors.greenCustom
} else {
MaterialTheme.colors.redCustom
},
modifier = Modifier.paddingFromBaseline(top = 16.dp, bottom = 16.dp)
)
}
Spacer(Modifier.width(16.dp))
Column(
modifier = Modifier
.fillMaxHeight()
.weight(1f)
) {
Text(
item.symbol,
style = MaterialTheme.typography.h3,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.paddingFromBaseline(top = 24.dp)
)
Text(
item.name,
style = MaterialTheme.typography.body1,
color = MaterialTheme.colors.onSurface,
modifier = Modifier.paddingFromBaseline(top = 16.dp, bottom = 16.dp)
)
}
Image(
modifier = Modifier.fillMaxHeight(),
painter = painterResource(id = item.imageRes),
contentDescription = null,
)
}
}
enum class ChangeDirection {
Positive, Negative
}
data class Item(
val imageRes: Int,
val symbol: String,
val name: String,
val price: String,
val change: String,
val changeDirection: ChangeDirection
)
val positions = listOf(
Item(
imageRes = R.drawable.ic_home_alk,
symbol = "ALK",
name = "Alaska Air Group, Inc.",
price = "$7,918",
change = "-0.54%",
changeDirection = ChangeDirection.Negative
),
Item(
imageRes = R.drawable.ic_home_ba,
symbol = "BA",
name = "Boeing Co.",
price = "$1,293",
change = "+4.18%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_dal,
symbol = "DAL",
name = "Delta Airlines Inc.",
price = "$893.50",
change = "-0.54%",
changeDirection = ChangeDirection.Negative
),
Item(
imageRes = R.drawable.ic_home_exp,
symbol = "EXPE",
name = "Expedia Group Inc.",
price = "$12,301",
change = "+2.51%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_eadsy,
symbol = "EADSY",
name = "Airbus SE",
price = "$12,301",
change = "+1.38%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_jblu,
symbol = "JBLU",
name = "Jetblue Airways Corp.",
price = "$8,521",
change = "+1.56%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_mar,
symbol = "MAR",
name = "Marriott International Inc.",
price = "$521",
change = "+2.75%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_ccl,
symbol = "CCL",
name = "Carnival Corp",
price = "$5,481",
change = "+0.14%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_rcl,
symbol = "RCL",
name = "<NAME>",
price = "$9,184",
change = "+1.69%",
changeDirection = ChangeDirection.Positive
),
Item(
imageRes = R.drawable.ic_home_trvl,
symbol = "TRVL",
name = "Travelocity Inc.",
price = "$654",
change = "+3.23%",
changeDirection = ChangeDirection.Positive
),
)
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun HomeLightPreview() {
Theme {
HomeContent()
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun HomeDarkPreview() {
Theme(darkTheme = true) {
HomeContent()
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun PositionsLightPreview() {
Theme {
Surface {
BottomSheetContent()
}
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun PositionsDarkPreview() {
Theme(darkTheme = true) {
Surface {
BottomSheetContent()
}
}
}
| 0 | Kotlin | 2 | 13 | 417d81a0250d079c9012ac15cf014b88ad342b96 | 13,857 | compose-challenge-week3 | Apache License 2.0 |
plugins/amazonq/chat/jetbrains-community/src/software/aws/toolkits/jetbrains/services/cwc/messages/CwcMessage.kt | aws | 91,485,909 | false | null | // Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.cwc.messages
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import software.aws.toolkits.jetbrains.services.amazonq.auth.AuthFollowUpType
import software.aws.toolkits.jetbrains.services.amazonq.messages.AmazonQMessage
import software.aws.toolkits.jetbrains.services.amazonq.onboarding.OnboardingPageInteractionType
import software.aws.toolkits.jetbrains.services.cwc.clients.chat.model.FollowUpType
import java.time.Instant
sealed interface CwcMessage : AmazonQMessage
// === UI -> App Messages ===
sealed interface IncomingCwcMessage : CwcMessage {
data class ClearChat(
@JsonProperty("tabID") val tabId: String,
) : IncomingCwcMessage
data class Help(
@JsonProperty("tabID") val tabId: String,
) : IncomingCwcMessage
data class ChatPrompt(
val chatMessage: String,
val command: String,
@JsonProperty("tabID") val tabId: String,
val userIntent: String?,
) : IncomingCwcMessage
data class TabAdded(
@JsonProperty("tabID") val tabId: String,
val tabType: String,
) : IncomingCwcMessage
data class TabRemoved(
@JsonProperty("tabID") val tabId: String,
val tabType: String,
) : IncomingCwcMessage
data class TabChanged(
@JsonProperty("tabID") val tabId: String,
@JsonProperty("prevTabID") val prevTabId: String?,
) : IncomingCwcMessage
data class FollowupClicked(
val followUp: FollowUp,
@JsonProperty("tabID") val tabId: String,
val messageId: String?,
val command: String,
val tabType: String,
) : IncomingCwcMessage
data class CopyCodeToClipboard(
val command: String?,
@JsonProperty("tabID") val tabId: String,
val messageId: String,
val code: String,
val insertionTargetType: String?,
val eventId: String?,
val codeBlockIndex: Int?,
val totalCodeBlocks: Int?
) : IncomingCwcMessage
data class InsertCodeAtCursorPosition(
@JsonProperty("tabID") val tabId: String,
val messageId: String,
val code: String,
val insertionTargetType: String?,
val codeReference: List<CodeReference>?,
val eventId: String?,
val codeBlockIndex: Int?,
val totalCodeBlocks: Int?
) : IncomingCwcMessage
data class TriggerTabIdReceived(
@JsonProperty("triggerID") val triggerId: String,
@JsonProperty("tabID") val tabId: String,
) : IncomingCwcMessage
data class StopResponse(
@JsonProperty("tabID") val tabId: String,
) : IncomingCwcMessage
data class ChatItemVoted(
@JsonProperty("tabID") val tabId: String,
val messageId: String,
val vote: String, // upvote / downvote
) : IncomingCwcMessage
data class ChatItemFeedback(
@JsonProperty("tabID") val tabId: String,
val selectedOption: String,
val comment: String?,
val messageId: String,
) : IncomingCwcMessage
data class UIFocus(
val command: String,
@JsonDeserialize(using = FocusTypeDeserializer::class)
@JsonSerialize(using = FocusTypeSerializer::class)
val type: FocusType,
) : IncomingCwcMessage
data class ClickedLink(
@JsonProperty("command") val type: LinkType,
@JsonProperty("tabID") val tabId: String,
val messageId: String?,
val link: String,
) : IncomingCwcMessage
data class AuthFollowUpWasClicked(
@JsonProperty("tabID") val tabId: String,
val authType: AuthFollowUpType,
) : IncomingCwcMessage
data class OpenSettings(
@JsonProperty("tabID") val tabId: String? = null,
) : IncomingCwcMessage
}
enum class FocusType {
FOCUS,
BLUR,
}
enum class LinkType(
@field:JsonValue val command: String,
) {
SourceLink("source-link-click"),
BodyLink("response-body-link-click"),
FooterInfoLink("footer-info-link-click"),
}
class FocusTypeDeserializer : JsonDeserializer<FocusType>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): FocusType = FocusType.valueOf(p.valueAsString.uppercase())
}
class FocusTypeSerializer : JsonSerializer<FocusType>() {
override fun serialize(value: FocusType, gen: JsonGenerator, serializers: SerializerProvider) {
gen.writeString(value.name.lowercase())
}
}
sealed class UiMessage(
open val tabId: String?,
open val type: String,
) : CwcMessage {
val time = Instant.now().epochSecond
val sender = "CWChat"
}
enum class ChatMessageType(
@field:JsonValue val json: String,
) {
AnswerStream("answer-stream"),
AnswerPart("answer-part"),
Answer("answer"),
AIPrompt("ai-prompt"),
Prompt("prompt"),
}
data class CodeReference(
val licenseName: String? = null,
val repository: String? = null,
val url: String? = null,
val recommendationContentSpan: RecommendationContentSpan? = null,
val information: String,
)
data class RecommendationContentSpan(
val start: Int,
val end: Int,
)
data class FollowUp(
val type: FollowUpType,
val pillText: String,
val prompt: String,
)
data class Suggestion(
val title: String,
val url: String,
val body: String,
val id: Int,
val type: String?,
val context: List<String>,
)
// === App -> UI messages ===
data class ChatMessage(
@JsonProperty("tabID") override val tabId: String,
@JsonProperty("triggerID") val triggerId: String,
val messageType: ChatMessageType,
val messageId: String,
val message: String? = null,
val followUps: List<FollowUp>? = null,
val followUpsHeader: String? = null,
val relatedSuggestions: List<Suggestion>? = null,
val codeReference: List<CodeReference>? = null,
) : UiMessage(
tabId = tabId,
type = "chatMessage",
)
data class EditorContextCommandMessage(
val message: String?,
@JsonProperty("triggerID") val triggerId: String?,
val command: String?,
) : UiMessage(
tabId = null,
type = "editorContextCommandMessage",
)
data class AuthNeededException(
@JsonProperty("tabID") override val tabId: String,
@JsonProperty("triggerID") val triggerId: String,
val authType: AuthFollowUpType,
val message: String,
) : UiMessage(
tabId = tabId,
type = "authNeededException",
)
data class ErrorMessage(
@JsonProperty("tabID") override val tabId: String,
val title: String,
val message: String,
val messageId: String?,
) : UiMessage(
tabId = tabId,
type = "errorMessage",
)
data class QuickActionMessage(
val message: String,
@JsonProperty("triggerID") val triggerId: String,
) : UiMessage(
tabId = null,
type = "editorContextCommandMessage",
)
data class OnboardingPageInteractionMessage(
val message: String,
val interactionType: OnboardingPageInteractionType,
@JsonProperty("triggerID") val triggerId: String
) : UiMessage(
tabId = null,
type = "editorContextCommandMessage",
)
data class OpenSettingsMessage(
@JsonProperty("tabID") override val tabId: String,
) : UiMessage(
tabId = tabId,
type = "openSettingsMessage",
)
| 519 | null | 220 | 757 | a81caf64a293b59056cef3f8a6f1c977be46937e | 7,833 | aws-toolkit-jetbrains | Apache License 2.0 |
lint/lint-gradle/src/test/java/androidx/lint/gradle/InternalApiUsageDetectorTest.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2024 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.lint.gradle
import com.android.tools.lint.checks.infrastructure.TestMode
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class InternalApiUsageDetectorTest : GradleLintDetectorTest(
detector = InternalApiUsageDetector(),
issues = listOf(InternalApiUsageDetector.ISSUE)
) {
@Test
fun `Test usage of internal Gradle API`() {
val input = kotlin(
"""
import org.gradle.api.component.SoftwareComponent
import org.gradle.api.internal.component.SoftwareComponentInternal
fun getSoftwareComponent() : SoftwareComponent {
return object : SoftwareComponentInternal {
override fun getUsages(): Set<out UsageContext> {
TODO()
}
}
}
""".trimIndent()
)
lint()
.files(*STUBS, input)
// Adding import aliases adds new warnings and that is working as intended.
.skipTestModes(TestMode.IMPORT_ALIAS)
.run()
.expect(
"""
src/test.kt:2: Error: Avoid using internal Gradle APIs [InternalGradleApiUsage]
import org.gradle.api.internal.component.SoftwareComponentInternal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
""".trimIndent()
)
lint()
.files(*STUBS, input)
// Adding import aliases adds new warnings and that is working as intended.
.testModes(TestMode.IMPORT_ALIAS)
.run()
.expect(
"""
src/test.kt:2: Error: Avoid using internal Gradle APIs [InternalGradleApiUsage]
import org.gradle.api.internal.component.SoftwareComponentInternal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/test.kt:4: Error: Avoid using internal Gradle APIs [InternalGradleApiUsage]
import org.gradle.api.internal.component.SoftwareComponentInternal as IMPORT_ALIAS_2_SOFTWARECOMPONENTINTERNAL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 errors, 0 warnings
""".trimIndent()
)
}
@Test
fun `Test usage of internal Android Gradle API`() {
val input = kotlin(
"""
import com.android.build.gradle.internal.lint.VariantInputs
""".trimIndent()
)
lint()
.files(*STUBS, input)
// Import aliases mode is covered by other tests
.skipTestModes(TestMode.IMPORT_ALIAS)
.run()
.expect(
"""
src/test.kt:1: Error: Avoid using internal Android Gradle Plugin APIs [InternalGradleApiUsage]
import com.android.build.gradle.internal.lint.VariantInputs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
""".trimIndent()
)
}
@Test
fun `Test usage of Internal annotation`() {
val input = kotlin(
"""
import java.io.File
import org.gradle.api.Task
import org.gradle.api.tasks.Internal
class MyTask : Task {
@get:Internal
val notInput: File
}
""".trimIndent()
)
check(input).expectClean()
}
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 4,405 | androidx | Apache License 2.0 |
core/src/main/kotlin/io/github/llmagentbuilder/core/AgentFactory.kt | alexcheng1982 | 780,391,516 | false | {"Kotlin": 121686, "Mustache": 20143, "TypeScript": 7650, "Handlebars": 4563, "Java": 3523, "Python": 1902, "CSS": 1545, "JavaScript": 89} | package io.github.alexcheng1982.llmagentbuilder.core
import io.github.alexcheng1982.llmagentbuilder.core.executor.AgentExecutor
import io.github.alexcheng1982.llmagentbuilder.core.tool.AgentToolWrappersProvider
import io.github.alexcheng1982.llmagentbuilder.core.tool.AgentToolsProvider
import io.github.alexcheng1982.llmagentbuilder.core.tool.AutoDiscoveredAgentToolsProvider
import io.micrometer.observation.ObservationRegistry
import org.slf4j.LoggerFactory
object AgentFactory {
private val logger = LoggerFactory.getLogger(javaClass)
fun createChatAgent(
planner: Planner,
name: String? = null,
description: String? = null,
usageInstruction: String? = null,
agentToolsProvider: AgentToolsProvider? = null,
id: String? = null,
observationRegistry: ObservationRegistry? = null,
): ChatAgent {
val defaultName = "ChatAgent"
val executor = createAgentExecutor(
name ?: defaultName,
planner,
agentToolsProvider ?: AutoDiscoveredAgentToolsProvider,
observationRegistry
)
return ExecutableChatAgent(
executor,
name ?: defaultName,
description ?: "A conversational chat agent",
usageInstruction ?: "Ask me anything",
id,
observationRegistry,
).also {
logger.info(
"Created ChatAgent [{}] with planner [{}]",
name,
planner
)
}
}
fun <REQUEST : AgentRequest, RESPONSE> create(
name: String,
description: String,
usageInstruction: String,
planner: Planner,
responseFactory: (Map<String, Any>) -> RESPONSE,
agentToolsProvider: AgentToolsProvider = AutoDiscoveredAgentToolsProvider,
id: String? = null,
observationRegistry: ObservationRegistry? = null,
): Agent<REQUEST, RESPONSE> {
val executor = createAgentExecutor(
name,
planner,
agentToolsProvider,
observationRegistry
)
return ExecutableAgent(
name,
description,
usageInstruction,
executor,
responseFactory,
id,
observationRegistry,
)
}
private fun createAgentExecutor(
agentName: String,
planner: Planner,
agentToolsProvider: AgentToolsProvider,
observationRegistry: ObservationRegistry? = null,
): AgentExecutor {
return AgentExecutor(
agentName,
planner,
AgentToolWrappersProvider(
agentToolsProvider,
observationRegistry
).get(),
observationRegistry = observationRegistry,
)
}
private open class ExecutableAgent<REQUEST : AgentRequest, RESPONSE>(
private val name: String,
private val description: String,
private val usageInstruction: String,
private val executor: AgentExecutor,
private val responseFactory: (Map<String, Any>) -> RESPONSE,
private val id: String? = null,
private val observationRegistry: ObservationRegistry? = null,
) :
Agent<REQUEST, RESPONSE> {
private val logger = LoggerFactory.getLogger("AgentExecutor")
override fun id(): String {
return id ?: super.id()
}
override fun name(): String {
return name
}
override fun description(): String {
return description
}
override fun usageInstruction(): String {
return usageInstruction
}
override fun call(request: REQUEST): RESPONSE {
logger.info(
"Start executing agent [{}] with request [{}]",
name(),
request
)
val response = responseFactory(executor.call(request.toMap()))
logger.info(
"Finished executing agent [{}] with response [{}]",
name(),
response
)
return response
}
}
private class ExecutableChatAgent(
executor: AgentExecutor,
name: String,
description: String,
usageInstruction: String,
id: String? = null,
observationRegistry: ObservationRegistry? = null,
) : ExecutableAgent<ChatAgentRequest, ChatAgentResponse>(
name,
description,
usageInstruction,
executor,
ChatAgentResponse::fromMap,
id,
observationRegistry,
), ChatAgent
} | 0 | Kotlin | 0 | 0 | dfab459c5d657051693786c08be4ffcf791f7637 | 4,675 | llm-agent-builder | Apache License 2.0 |
kodando-mithril/src/test/kotlin/kodando.mithril/CreateComponentUsingObject.kt | kodando | 81,663,289 | false | null | package kodando.mithril
import kodando.jest.Spec
import kodando.jest.expect
import kodando.mithril.elements.button
import kodando.mithril.elements.div
import kodando.mithril.elements.span
import org.w3c.dom.events.Event
import kotlin.browser.document
class CreateComponentUsingClassSpec : Spec() {
private class CounterByClass : View<CounterByClass.Props> {
interface Props : kodando.mithril.Props {
var count: Int
var onClick: (Event) -> Unit
}
override fun view(vnode: VNode<Props>): VNode<*>? {
val props = vnode.attrs ?: return null
return root {
div("counter") {
span {
content(props.count)
}
button {
type = "button"
onClick = props.onClick
content("Increment")
}
}
}
}
}
private fun Props.counterByClass(count: Int, applier: Applier<CounterByClass.Props>) {
addChild(CounterByClass::class) {
this.count = count
applier()
}
}
init {
describe("Component using a class") {
it("should be able to create a new vnode") byChecking {
val node = root {
counterByClass(1) {
}
}
expect(node).toBeDefined()
val container = document.createElement("div").also {
render(it, node!!)
}
expect(container.innerHTML.trim()).toBe(
"""<div class="counter"><span>1</span><button type="button">Increment</button></div>"""
)
}
}
}
}
| 12 | Kotlin | 5 | 76 | f1428066ca01b395c1611717fde5463ba0042b19 | 1,528 | kodando | MIT License |
kodando-mithril/src/test/kotlin/kodando.mithril/CreateComponentUsingObject.kt | kodando | 81,663,289 | false | null | package kodando.mithril
import kodando.jest.Spec
import kodando.jest.expect
import kodando.mithril.elements.button
import kodando.mithril.elements.div
import kodando.mithril.elements.span
import org.w3c.dom.events.Event
import kotlin.browser.document
class CreateComponentUsingClassSpec : Spec() {
private class CounterByClass : View<CounterByClass.Props> {
interface Props : kodando.mithril.Props {
var count: Int
var onClick: (Event) -> Unit
}
override fun view(vnode: VNode<Props>): VNode<*>? {
val props = vnode.attrs ?: return null
return root {
div("counter") {
span {
content(props.count)
}
button {
type = "button"
onClick = props.onClick
content("Increment")
}
}
}
}
}
private fun Props.counterByClass(count: Int, applier: Applier<CounterByClass.Props>) {
addChild(CounterByClass::class) {
this.count = count
applier()
}
}
init {
describe("Component using a class") {
it("should be able to create a new vnode") byChecking {
val node = root {
counterByClass(1) {
}
}
expect(node).toBeDefined()
val container = document.createElement("div").also {
render(it, node!!)
}
expect(container.innerHTML.trim()).toBe(
"""<div class="counter"><span>1</span><button type="button">Increment</button></div>"""
)
}
}
}
}
| 12 | Kotlin | 5 | 76 | f1428066ca01b395c1611717fde5463ba0042b19 | 1,528 | kodando | MIT License |
src/main/kotlin/com/cognifide/gradle/sling/common/instance/check/TimeoutCheck.kt | Cognifide | 138,027,523 | false | null | package com.cognifide.gradle.sling.common.instance.check
import com.cognifide.gradle.sling.common.instance.InstanceException
import com.cognifide.gradle.common.utils.Formats
import java.util.concurrent.TimeUnit
class TimeoutCheck(group: CheckGroup) : DefaultCheck(group) {
/**
* Prevents too long unavailability time (instance never responds anything).
*/
val unavailableTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(1)) }
/**
* Prevents too long inactivity time (instance state is no longer changing).
*/
val stateTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(10)) }
/**
* Prevents circular restarting of OSGi bundles & components (e.g installing SP/CFP takes too much time).
*/
val constantTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(30)) }
override fun check() {
if (!instance.available && progress.stateTime >= unavailableTime.get()) {
throw InstanceException("Instance unavailable timeout reached '${Formats.duration(progress.stateTime)}' for $instance!")
}
if (progress.stateTime >= stateTime.get()) {
throw InstanceException("Instance state timeout reached '${Formats.duration(progress.stateTime)}' for $instance!")
}
if (runner.runningTime >= constantTime.get()) {
throw InstanceException("Instance constant timeout reached '${Formats.duration(runner.runningTime)}'!")
}
}
}
| 0 | null | 2 | 15 | b3e7244f887b24dece21571a5a63ae79ef0c7597 | 1,484 | gradle-sling-plugin | Apache License 2.0 |
src/main/kotlin/com/cognifide/gradle/sling/common/instance/check/TimeoutCheck.kt | Cognifide | 138,027,523 | false | null | package com.cognifide.gradle.sling.common.instance.check
import com.cognifide.gradle.sling.common.instance.InstanceException
import com.cognifide.gradle.common.utils.Formats
import java.util.concurrent.TimeUnit
class TimeoutCheck(group: CheckGroup) : DefaultCheck(group) {
/**
* Prevents too long unavailability time (instance never responds anything).
*/
val unavailableTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(1)) }
/**
* Prevents too long inactivity time (instance state is no longer changing).
*/
val stateTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(10)) }
/**
* Prevents circular restarting of OSGi bundles & components (e.g installing SP/CFP takes too much time).
*/
val constantTime = sling.obj.long { convention(TimeUnit.MINUTES.toMillis(30)) }
override fun check() {
if (!instance.available && progress.stateTime >= unavailableTime.get()) {
throw InstanceException("Instance unavailable timeout reached '${Formats.duration(progress.stateTime)}' for $instance!")
}
if (progress.stateTime >= stateTime.get()) {
throw InstanceException("Instance state timeout reached '${Formats.duration(progress.stateTime)}' for $instance!")
}
if (runner.runningTime >= constantTime.get()) {
throw InstanceException("Instance constant timeout reached '${Formats.duration(runner.runningTime)}'!")
}
}
}
| 0 | null | 2 | 15 | b3e7244f887b24dece21571a5a63ae79ef0c7597 | 1,484 | gradle-sling-plugin | Apache License 2.0 |
src/easy/_67AddBinary.kt | ilinqh | 390,190,883 | false | {"Kotlin": 395506, "Java": 32733} | package easy
class _67AddBinary {
class Solution {
fun addBinary(a: String, b: String): String {
val tempA: String
val tempB: String
if (a.length >= b.length) {
tempA = a.reversed()
tempB = b.reversed()
} else {
tempA = b.reversed()
tempB = a.reversed()
}
var addition = 0
val sb = StringBuffer()
for (i in tempA.indices) {
val x = tempA[i] - '0'
val y = if (i < tempB.length) {
tempB[i] - '0'
} else {
0
}
val sum = x + y + addition
sb.append((sum % 2).digitToChar())
addition = sum / 2
}
if (addition == 1) {
sb.append('1')
}
return sb.toString().reversed()
}
}
// Best
class BestSolution {
fun addBinary(a: String, b: String): String {
val result: StringBuilder = StringBuilder()
var needCarry = false
val count = Math.max(a.length, b.length)
for (i in 0 until count) {
val aTmp = a.getReversedCharByIndex(i)
val bTmp = b.getReversedCharByIndex(i)
if(aTmp != bTmp) {
result.append(if (needCarry) "0" else "1")
} else {
result.append(if (needCarry) "1" else "0")
needCarry = aTmp == '1'
}
}
if (needCarry) result.append("1")
return result.reversed().toString()
}
fun String.getReversedCharByIndex(index: Int) = if (index < length) this[length - index - 1] else '0'
}
} | 0 | Kotlin | 0 | 0 | 985f2f1a022a25d39782cd36ae3d0ab33fed8ac5 | 1,834 | AlgorithmsProject | Apache License 2.0 |
nj2k/nj2k-services/src/org/jetbrains/kotlin/nj2k/nullabilityAnalysis/BoundTypeStorage.kt | cr8tpro | 189,964,139 | false | null | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.nj2k.nullabilityAnalysis
import com.intellij.psi.PsiComment
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.nj2k.postProcessing.resolve
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class BoundTypeStorage(private val analysisAnalysisContext: AnalysisContext, private val printConstraints: Boolean) {
private val cache = mutableMapOf<KtExpression, BoundType>()
private val printer = Printer(analysisAnalysisContext)
fun boundTypeFor(expression: KtExpression): BoundType =
cache.getOrPut(expression) {
if (expression is KtParenthesizedExpression) return@getOrPut boundTypeFor(expression.expression!!)
val boundType =
when (expression) {
is KtParenthesizedExpression -> expression.expression?.let { boundTypeFor(it) }
is KtQualifiedExpression ->
expression.selectorExpression?.toBoundType(
boundTypeFor(expression.receiverExpression)
)
else -> expression.getQualifiedExpressionForSelector()?.let { boundTypeFor(it) }
} ?: expression.toBoundType(null)
?: LiteralBoundType(expression.isNullable())
if (printConstraints) {
if (expression.getNextSiblingIgnoringWhitespace() !is PsiComment) {
val comment = with(printer) {
KtPsiFactory(expression.project).createComment("/*${boundType.asString()}*/")
}
expression.parent.addAfter(comment, expression)
}
}
boundType
}
fun boundTypeForType(
type: KotlinType,
contextBoundType: BoundType?,
typeParameterDescriptors: Map<TypeParameterDescriptor, TypeVariable>
): BoundType? =
type.toBoundType(contextBoundType, typeParameterDescriptors)
private fun KtExpression.resolveToTypeVariable(): TypeVariable? =
getCalleeExpressionIfAny()
?.safeAs<KtReferenceExpression>()
?.resolve()
?.safeAs<KtDeclaration>()
?.let {
analysisAnalysisContext.declarationToTypeVariable[it]
} ?: KtPsiUtil.deparenthesize(this)?.let { analysisAnalysisContext.declarationToTypeVariable[it] }
private fun KtExpression.toBoundTypeAsTypeVariable(): BoundType? =
resolveToTypeVariable()?.let { TypeVariableBoundType(it, getForcedNullability()) }
private fun KtExpression.toBoundTypeAsCallExpression(contextBoundType: BoundType?): BoundType? {
val typeElement = getCalleeExpressionIfAny()
?.safeAs<KtReferenceExpression>()
?.resolve()
?.safeAs<KtCallableDeclaration>()
?.typeReference
?.typeElement
typeElement?.let { analysisAnalysisContext.typeElementToTypeVariable[it] }?.also {
return TypeVariableBoundType(it)
}
val bindingContext = analyze()
val descriptor =
getResolvedCall(bindingContext)?.candidateDescriptor?.original?.safeAs<CallableDescriptor>() ?: return null
val typeParameters =
if (this is KtCallElement) {
typeArguments.mapIndexed { index, typeArgument ->
//TODO better check
descriptor.typeParameters[index] to
analysisAnalysisContext.typeElementToTypeVariable.getValue(typeArgument.typeReference?.typeElement!!)
}.toMap()
} else emptyMap()
return descriptor.returnType?.toBoundType(contextBoundType, typeParameters)
}
private fun KtExpression.toBoundTypeAsCastExpression(): BoundType? {
val castExpression = KtPsiUtil.deparenthesize(this)
?.safeAs<KtBinaryExpressionWithTypeRHS>()
?.takeIf { KtPsiUtil.isUnsafeCast(it) }
?: return null
return castExpression.right?.typeElement
?.let { analysisAnalysisContext.typeElementToTypeVariable[it] }
?.let { TypeVariableBoundType(it) }
}
private fun KtExpression.toBoundType(contextBoundType: BoundType?): BoundType? {
toBoundTypeAsTypeVariable()?.also { return it }
toBoundTypeAsCallExpression(contextBoundType)?.also { return it }
toBoundTypeAsCastExpression()?.also { return it }
return null
}
private fun KotlinType.toBoundType(
contextBoundType: BoundType?,
typeParameterDescriptors: Map<TypeParameterDescriptor, TypeVariable>
): BoundType? {
fun KotlinType.toBoundType(): BoundType? {
val forcedNullability = when {
isMarkedNullable -> Nullability.NULLABLE
else -> null
}
val target = constructor.declarationDescriptor
return when (target) {
is ClassDescriptor -> {
val classReference = DescriptorClassReference(target)
GenericBoundType(
classReference,
(arguments zip constructor.parameters).map { (typeArgument, typeParameter) ->
BoundTypeTypeParameter(
typeArgument.type.toBoundType() ?: return null,
typeParameter.variance
)
},
forcedNullability,
isNullable()
)
}
is TypeParameterDescriptor -> {
when {
target in typeParameterDescriptors ->
TypeVariableBoundType(typeParameterDescriptors.getValue(target), forcedNullability)
contextBoundType != null ->
contextBoundType.typeParameters.getOrNull(target.index)?.boundType?.withForcedNullability(forcedNullability)
else -> null
}
}
else -> error(toString())
}
}
return toBoundType()
}
} | 0 | null | 1 | 2 | dca23f871cc22acee9258c3d58b40d71e3693858 | 6,974 | kotlin | Apache License 2.0 |
core/mockserver/src/androidTest/java/com/kurly/android/mockserver/MockServerTest.kt | SunChulBaek | 777,505,298 | false | {"Kotlin": 101661} | package com.kurly.android.mockserver
import com.kurly.android.mockserver.core.FileProvider
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
internal class MockServerTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var fileProvider: FileProvider
@Before
fun init() {
hiltRule.inject()
}
@Test
fun `리소스 파일 읽기 테스트`() {
println(fileProvider.getJsonFromAsset("file_read_test.json"))
}
}
| 0 | Kotlin | 0 | 0 | db5e6d56944f09336196b7ebda7cff61f6bd82b4 | 631 | HelloKurly | Apache License 2.0 |
app/src/test/kotlin/com/codementor/dmmfwk/ordertaking/ValidateOrderSpec.kt | goerge | 367,695,134 | false | {"Kotlin": 32705} | package com.codementor.dmmfwk.ordertaking
import arrow.core.right
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.arrow.isRight
import strikt.arrow.value
import strikt.assertions.isEqualTo
import strikt.assertions.single
import java.math.BigDecimal
internal class ValidateOrderSpec {
@Test
fun `creates ValidatedOrder if input is valid and products exist`() {
val productCodeExists: CheckProductCodeExists = { _ -> true }
val addressExists: CheckAddressExists = { _ ->
CheckedAddress(
addressLine1 = "My Street 1",
city = "Best City in Town",
zipCode = "2342"
).right()
}
val unvalidatedOrder = UnvalidatedOrder(
orderId = "OR-123",
customerInfo = UnvalidatedCustomerInfo(
firstName = "Peter",
lastName = "Parker",
emailAddress = "<EMAIL>"
),
shippingAddress = UnvalidatedAddress(
addressLine1 = "My Street 1",
city = "Best City in Town",
zipCode = "2342"
),
billingAddress = UnvalidatedAddress(
addressLine1 = "My Street 1",
city = "Best City in Town",
zipCode = "2342"
),
lines = listOf(
UnvalidatedOrderLine("OL-123", "W1234", BigDecimal.TEN)
)
)
val result = validateOrder(productCodeExists, addressExists, unvalidatedOrder)
expectThat(result).isRight().value.and {
get { lines }.single().and {
get { orderLineId.value } isEqualTo "OL-123"
}
}
}
}
| 0 | Kotlin | 0 | 1 | e629002408004d8c2b28c87864d23da52044ff67 | 1,742 | DomainModelingMadeFunctionalWithKotlin | Apache License 2.0 |
camera/camera-core/src/androidTest/java/androidx/camera/core/impl/utils/ExifOutputStreamTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.core.impl.utils
import android.graphics.Bitmap
import android.os.Build
import androidx.camera.core.impl.CameraCaptureMetaData
import androidx.exifinterface.media.ExifInterface
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import com.google.common.truth.Truth.assertThat
import java.io.File
import org.junit.Test
@LargeTest
@SdkSuppress(minSdkVersion = 21)
public class ExifOutputStreamTest {
@Test
public fun canSetExifOnCompressedBitmap() {
// Arrange.
val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
val exifData = ExifData.builderForDevice()
.setImageWidth(bitmap.width)
.setImageHeight(bitmap.height)
.setFlashState(CameraCaptureMetaData.FlashState.NONE)
.setExposureTimeNanos(0)
.build()
val fileWithExif = File.createTempFile("testWithExif", ".jpg")
val outputStreamWithExif = ExifOutputStream(fileWithExif.outputStream(), exifData)
fileWithExif.deleteOnExit()
val fileWithoutExif = File.createTempFile("testWithoutExif", ".jpg")
val outputStreamWithoutExif = fileWithoutExif.outputStream()
fileWithoutExif.deleteOnExit()
// Act.
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStreamWithExif)
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStreamWithoutExif)
// Verify with ExifInterface
val withExif = ExifInterface(fileWithExif.inputStream())
val withoutExif = ExifInterface(fileWithoutExif.inputStream())
// Assert.
// Model comes from default builder
assertThat(withExif.getAttribute(ExifInterface.TAG_MODEL)).isEqualTo(Build.MODEL)
assertThat(withoutExif.getAttribute(ExifInterface.TAG_MODEL)).isNull()
assertThat(withExif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)).isEqualTo("100")
assertThat(withoutExif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)).isEqualTo("100")
assertThat(withExif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH)).isEqualTo("100")
assertThat(withoutExif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH)).isEqualTo("100")
assertThat(withExif.getAttribute(ExifInterface.TAG_FLASH)?.toShort())
.isEqualTo(ExifInterface.FLAG_FLASH_NO_FLASH_FUNCTION)
assertThat(withoutExif.getAttribute(ExifInterface.TAG_FLASH)).isNull()
assertThat(withExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)?.toFloat()?.toInt())
.isEqualTo(0)
assertThat(withoutExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)).isNull()
}
} | 28 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,261 | androidx | Apache License 2.0 |
app/src/test/java/com/example/cepraceapp/MainViewModelTest.kt | EASY-CODES | 762,273,839 | false | {"Kotlin": 40025} | package com.example.cepraceapp
import com.engedu.ceprace.domain.model.AddressVO
import com.engedu.ceprace.initializer.CepRaceInitImpl
import com.example.cepraceapp.util.ViewState
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
class MainViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
//sut
private lateinit var mainViewModel: MainViewModel
//mock
private val cepRaceInit: CepRaceInitImpl = mockk()
//fake
private val vo = AddressVO("VIA CEP", "avenida cd 18", "marilucy", "tucurui", "pa")
@Test
fun executeSuccessReturnViewStateSuccess() = runTest {
//Arrange
coEvery { cepRaceInit.execute(any()) } returns vo //stub
mainViewModel = MainViewModel(cepRaceInit)
//Action
mainViewModel.getAddress("68459370")
//Assert
Assert.assertEquals(ViewState.Success(vo), mainViewModel.addressState.value)
}
@Test
fun executeErrorReturnViewStateError() = runTest {
//Arrange
coEvery { cepRaceInit.execute(any()) } throws Exception() //stub
mainViewModel = MainViewModel(cepRaceInit)
//Action
mainViewModel.getAddress("68459370")
//Assert
Assert.assertEquals(
ViewState.Error(
error = "Parece que ninguém cruzou a linha de chagada =(",
tryAgain = mainViewModel::tryAgain
), mainViewModel.addressState.value
)
}
}
| 1 | Kotlin | 0 | 1 | 849c0ca131ad74841159c4f05e2eabaedbcd8288 | 1,574 | ceprace | Apache License 2.0 |
appfit/src/test/java/io/appfit/appfit/networking/ApiClientTest.kt | uptech | 774,969,130 | false | {"Kotlin": 17434, "Java": 573} | package io.appfit.appfit.networking
import android.os.Build
import com.google.gson.GsonBuilder
import io.appfit.appfit.properties.DeviceProperties
import io.appfit.appfit.properties.EventSystemProperties
import io.appfit.appfit.properties.OperatingSystem
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Assert
import org.junit.Test
import java.util.Date
import java.util.UUID
@OptIn(ExperimentalCoroutinesApi::class)
class ApiClientTest {
private val apiClient = ApiClient(apiKey = "<KEY>)
@Test
fun testSingleEvent() = runTest {
val event = MetricEvent(
occurredAt = Date(),
payload = EventPayload(
sourceEventId = UUID.randomUUID(),
eventName = "unit_test",
userId = null,
anonymousId = "android_studio_75fbf7a3-2197-4353-9b39-eeadf4628c68",
properties = mapOf("language" to "kotlin"),
systemProperties = EventSystemProperties(
appVersion = "1.0.0",
device = DeviceProperties(
manufacturer = "Unit",
model = "Test"
),
operatingSystem = OperatingSystem(
version = "14"
)
)
)
)
advanceUntilIdle()
val result = apiClient.send(event)
Assert.assertEquals(true, result)
}
@Test
fun testBatchEvents() = runTest {
val event = MetricEvent(
occurredAt = Date(),
payload = EventPayload(
sourceEventId = UUID.randomUUID(),
eventName = "unit_test",
userId = null,
anonymousId = "android_studio_75fbf7a3-2197-4353-9b39-eeadf4628c68",
properties = mapOf("language" to "kotlin"),
systemProperties = EventSystemProperties(
appVersion = "1.0.0",
device = DeviceProperties(
manufacturer = "Unit",
model = "Test"
),
operatingSystem = OperatingSystem(
version = Build.VERSION.RELEASE
)
)
)
)
advanceUntilIdle()
val result = apiClient.send(listOf(event))
Assert.assertEquals(true, result)
}
} | 0 | Kotlin | 0 | 0 | 3d2c0416d8d6dd01dce0d7ca97cfc19bd8afd10a | 2,534 | appfit-kotlin-sdk | MIT License |
jdroid-android-core/src/main/java/com/jdroid/android/kotlin/FragmentExtensions.kt | fwonly123 | 198,339,170 | false | {"Java Properties": 2, "Markdown": 6, "Gradle": 22, "Shell": 1, "YAML": 2, "EditorConfig": 1, "Ignore List": 16, "XML": 233, "Kotlin": 394, "Java": 254, "JSON": 5, "JavaScript": 1, "INI": 2, "HTML": 1} | package com.jdroid.android.kotlin
import android.os.Parcelable
import androidx.fragment.app.Fragment
import java.io.Serializable
import java.util.ArrayList
fun Fragment.getSerializableArgument(key: String?): Serializable? {
return arguments?.getSerializable(key)
}
fun Fragment.getRequiredSerializableArgument(key: String?): Serializable {
return arguments?.getSerializable(key)!!
}
fun Fragment.getIntArgument(key: String?): Int? {
return arguments?.getInt(key)
}
fun Fragment.getRequiredIntArgument(key: String?): Int {
return arguments?.getInt(key)!!
}
fun Fragment.getFloatArgument(key: String?): Float? {
return arguments?.getFloat(key)
}
fun Fragment.getRequiredFloatArgument(key: String?): Float {
return arguments?.getFloat(key)!!
}
fun Fragment.getBooleanArgument(key: String?): Boolean? {
return arguments?.getBoolean(key)
}
fun Fragment.getRequiredBooleanArgument(key: String?): Boolean {
return arguments?.getBoolean(key)!!
}
fun Fragment.getStringArgument(key: String?): String? {
return arguments?.getString(key)
}
fun Fragment.getRequiredStringArgument(key: String?): String {
return arguments?.getString(key)!!
}
fun Fragment.getDoubleArgument(key: String?): Double? {
return arguments?.getDouble(key)
}
fun Fragment.getRequiredDoubleArgument(key: String?): Double {
return arguments?.getDouble(key)!!
}
fun <T : Parcelable> Fragment.getParcelableArrayListArgument(key: String?): ArrayList<T>? {
return arguments?.getParcelableArrayList(key)
}
fun <T : Parcelable> Fragment.getRequiredParcelableArrayListArgument(key: String?): ArrayList<T> {
return arguments?.getParcelableArrayList(key)!!
}
fun <T : Parcelable> Fragment.getParcelableArgument(key: String?): T? {
return arguments?.getParcelable(key)
}
fun <T : Parcelable> Fragment.getRequiredParcelableArgument(key: String?): T {
return arguments?.getParcelable(key)!!
}
| 1 | null | 1 | 1 | 578194586fc7d7e71d3742756651d658cb498bd0 | 1,921 | jdroid-android | Apache License 2.0 |
compiler/testData/diagnostics/tests/extensions/contextReceivers/twoReceiverCandidatesError.kt | JetBrains | 3,432,266 | false | null | // !LANGUAGE: +ContextReceivers
// FIR_IDENTICAL
fun String.foo() {}
context(Int, Double)
fun bar() {
<!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>foo<!>() // should be prohibited
}
fun main() {
with(1) {
with(2.0) {
bar()
}
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 266 | kotlin | Apache License 2.0 |
OptiGUI/src/main/kotlin/opekope2/optigui/internal/BuiltinPreprocessors.kt | opekope2 | 578,779,647 | false | null | package opekope2.optigui.internal
import net.minecraft.block.entity.*
import net.minecraft.block.enums.ChestType
import net.minecraft.client.MinecraftClient
import net.minecraft.client.gui.screen.ingame.BookScreen
import net.minecraft.client.gui.screen.ingame.HandledScreen
import net.minecraft.client.gui.screen.ingame.LecternScreen
import net.minecraft.entity.Entity
import net.minecraft.entity.mob.SkeletonHorseEntity
import net.minecraft.entity.mob.ZombieHorseEntity
import net.minecraft.entity.passive.*
import net.minecraft.entity.vehicle.ChestMinecartEntity
import net.minecraft.entity.vehicle.HopperMinecartEntity
import net.minecraft.state.property.EnumProperty
import net.minecraft.util.Nameable
import opekope2.optigui.InitializerContext
import opekope2.optigui.properties.*
import opekope2.optigui.service.RegistryLookupService
import opekope2.optigui.service.getService
import opekope2.util.comparatorOutputWorkaround
import opekope2.util.getComparatorOutputWorkaround
@Suppress("unused")
internal fun initializePreprocessors(context: InitializerContext) {
context.registerPreprocessor<BrewingStandBlockEntity>(::processCommonComparable)
context.registerPreprocessor<EnchantingTableBlockEntity>(::processCommon)
context.registerPreprocessor<FurnaceBlockEntity>(::processCommonComparable)
context.registerPreprocessor<BlastFurnaceBlockEntity>(::processCommonComparable)
context.registerPreprocessor<SmokerBlockEntity>(::processCommonComparable)
context.registerPreprocessor<HopperBlockEntity>(::processCommonComparable)
context.registerPreprocessor<HopperMinecartEntity>(::processCommonComparable)
context.registerPreprocessor<ChestBlockEntity>(::processChest)
context.registerPreprocessor<TrappedChestBlockEntity>(::processChest)
context.registerPreprocessor<EnderChestBlockEntity>(::processCommon)
context.registerPreprocessor<BarrelBlockEntity>(::processCommonComparable)
context.registerPreprocessor<ChestMinecartEntity>(::processCommonComparable)
context.registerPreprocessor<BeaconBlockEntity>(::processBeacon)
context.registerPreprocessor<VillagerEntity>(::processVillager)
context.registerPreprocessor<WanderingTraderEntity>(::processCommon)
context.registerPreprocessor<DispenserBlockEntity>(::processCommonComparable)
context.registerPreprocessor<DropperBlockEntity>(::processCommonComparable)
context.registerPreprocessor<HorseEntity>(::processCommon)
context.registerPreprocessor<DonkeyEntity>(::processDonkey)
context.registerPreprocessor<MuleEntity>(::processDonkey)
context.registerPreprocessor<LlamaEntity>(::processLlama)
context.registerPreprocessor<TraderLlamaEntity>(::processLlama)
context.registerPreprocessor<ZombieHorseEntity>(::processCommon)
context.registerPreprocessor<SkeletonHorseEntity>(::processCommon)
context.registerPreprocessor<ShulkerBoxBlockEntity>(::processCommonComparable)
context.registerPreprocessor<LecternBlockEntity>(::processLectern)
}
private val lookup: RegistryLookupService by lazy(::getService)
private fun processCommon(blockEntity: BlockEntity): Any? {
val world = blockEntity.world ?: return null
return DefaultProperties(
container = lookup.lookupBlockId(world.getBlockState(blockEntity.pos).block),
name = (blockEntity as? Nameable)?.customName?.string,
biome = lookup.lookupBiomeId(world, blockEntity.pos),
height = blockEntity.pos.y
)
}
private fun processCommonComparable(blockEntity: BlockEntity): Any? {
val world = blockEntity.world ?: return null
val screen = MinecraftClient.getInstance().currentScreen
return CommonComparatorProperties(
container = lookup.lookupBlockId(world.getBlockState(blockEntity.pos).block),
name = (blockEntity as? Nameable)?.customName?.string,
biome = lookup.lookupBiomeId(world, blockEntity.pos),
height = blockEntity.pos.y,
comparatorOutput = (screen as? HandledScreen<*>)?.screenHandler?.getComparatorOutputWorkaround() ?: 0
)
}
fun processCommon(entity: Entity): Any? {
val world = entity.entityWorld ?: return null
return DefaultProperties(
container = lookup.lookupEntityId(entity),
name = entity.customName?.string,
biome = lookup.lookupBiomeId(world, entity.blockPos),
height = entity.blockY
)
}
private fun processCommonComparable(entity: Entity): Any? {
val world = entity.world ?: return null
val screen = MinecraftClient.getInstance().currentScreen
return CommonComparatorProperties(
container = lookup.lookupEntityId(entity),
name = entity.customName?.string,
biome = lookup.lookupBiomeId(world, entity.blockPos),
height = entity.blockY,
comparatorOutput = (screen as? HandledScreen<*>)?.screenHandler?.getComparatorOutputWorkaround() ?: 0
)
}
private fun processBeacon(beacon: BeaconBlockEntity): Any? {
val world = beacon.world ?: return null
return BeaconProperties(
container = lookup.lookupBlockId(world.getBlockState(beacon.pos).block),
name = (beacon as? Nameable)?.customName?.string,
biome = lookup.lookupBiomeId(world, beacon.pos),
height = beacon.pos.y,
level = beacon.level
)
}
private val chestTypeEnum = EnumProperty.of("type", ChestType::class.java)
private fun processChest(chest: ChestBlockEntity): Any? {
val world = chest.world ?: return null
val state = world.getBlockState(chest.pos)
val type = state.entries[chestTypeEnum]
val screen = MinecraftClient.getInstance().currentScreen
return ChestProperties(
container = lookup.lookupBlockId(world.getBlockState(chest.pos).block),
name = chest.customName?.string,
biome = lookup.lookupBiomeId(world, chest.pos),
height = chest.pos.y,
isLarge = type != ChestType.SINGLE,
comparatorOutput = (screen as? HandledScreen<*>)?.screenHandler?.getComparatorOutputWorkaround() ?: 0
)
}
private fun processDonkey(donkey: AbstractDonkeyEntity): Any? {
val world = donkey.entityWorld ?: return null
return DonkeyProperties(
container = lookup.lookupEntityId(donkey),
name = donkey.customName?.string,
biome = lookup.lookupBiomeId(world, donkey.blockPos),
height = donkey.blockY,
hasChest = donkey.hasChest()
)
}
private fun processLlama(llama: LlamaEntity): Any? {
val world = llama.entityWorld ?: return null
return LlamaProperties(
container = lookup.lookupEntityId(llama),
name = llama.customName?.string,
biome = lookup.lookupBiomeId(world, llama.blockPos),
height = llama.blockY,
carpetColor = llama.carpetColor?.getName(),
hasChest = llama.hasChest()
)
}
private fun processVillager(villager: VillagerEntity): Any? {
val world = villager.entityWorld ?: return null
return VillagerProperties(
container = lookup.lookupEntityId(villager),
name = villager.customName?.string,
biome = lookup.lookupBiomeId(world, villager.blockPos),
height = villager.blockY,
level = villager.villagerData.level,
profession = lookup.lookupVillagerProfessionId(villager.villagerData.profession),
type = lookup.lookupVillagerTypeId(villager.villagerData.type)
)
}
private fun processLectern(lectern: LecternBlockEntity): Any? {
val world = lectern.world ?: return null
// Workaround, because LecternBlockEntity doesn't sync
val screen = MinecraftClient.getInstance().currentScreen
return LecternProperties(
container = lookup.lookupBlockId(world.getBlockState(lectern.pos).block),
name = null,
biome = lookup.lookupBiomeId(world, lectern.pos),
height = lectern.pos.y,
currentPage = (screen as? BookScreen)?.pageIndex?.plus(1) ?: return null,
pageCount = (screen as? BookScreen)?.pageCount ?: return null,
comparatorOutput = (screen as? LecternScreen)?.comparatorOutputWorkaround ?: 0
)
}
| 6 | Kotlin | 1 | 11 | e707fe6d94c7cd6d78a6898052854a3de219693e | 8,060 | OptiGUI | MIT License |
client/src/main/java/com/google/devtools/moe/client/dvcs/git/GitClonedRepository.kt | cgruber | 35,457,241 | true | {"Java": 758603, "Kotlin": 129754, "Starlark": 41938, "Shell": 1679} | /*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.moe.client.dvcs.git
import com.google.common.collect.ImmutableList
import com.google.devtools.moe.client.CommandRunner
import com.google.devtools.moe.client.CommandRunner.CommandException
import com.google.devtools.moe.client.FileSystem
import com.google.devtools.moe.client.FileSystem.Lifetime
import com.google.devtools.moe.client.Lifetimes
import com.google.devtools.moe.client.MoeProblem
import com.google.devtools.moe.client.codebase.LocalWorkspace
import com.google.devtools.moe.client.config.RepositoryConfig
import java.io.File
import java.io.IOException
import java.nio.file.Paths
/**
* Git implementation of [LocalWorkspace], i.e. a 'git clone' to local disk.
*/
// open for mocking
open class GitClonedRepository(
private val cmd: CommandRunner,
private val filesystem: FileSystem,
private val repositoryName: String,
private val config: RepositoryConfig,
/**
* The location to clone from. If snapshotting a locally modified Writer, this will _not_ be
* the same as repositoryConfig.getUrl(). Otherwise, it will.
*/
private val repositoryUrl: String?,
private val lifetimes: Lifetimes
) : LocalWorkspace {
private lateinit var localCloneTempDir: File
private var clonedLocally = false
/** The revision of this clone, a Git hash ID */
private var revId: String? = null
constructor(
cmd: CommandRunner,
filesystem: FileSystem,
repositoryName: String,
config: RepositoryConfig,
lifetimes: Lifetimes
) : this(cmd, filesystem, repositoryName, config, config.url, lifetimes)
override fun getRepositoryName() = repositoryName
override fun getConfig() = config
override fun getLocalTempDir() = localCloneTempDir.also { check(clonedLocally) }
@Throws(CommandException::class, IOException::class)
private fun initLocal(dir: File?) {
cmd.runCommand("", "git", ImmutableList.of("init", dir!!.absolutePath))
cmd.runCommand(dir.absolutePath, "git", listOf("remote", "add", "origin", repositoryUrl))
val fetchArgs = listOf("fetch") +
(config.tag?.let { listOf("--tags") } ?: listOf()) +
(config.depth?.let { listOf("--depth=${config.depth}") } ?: listOf()) +
"origin" +
(config.branch ?: config.tag ?: DEFAULT_BRANCH)
cmd.runCommand(dir.absolutePath, "git", fetchArgs)
if (config.paths.isNotEmpty()) {
cmd.runCommand(dir.absolutePath, "git", listOf("config", "core.sparseCheckout", "true"))
filesystem.write(
"""${java.lang.String.join("\n", config.paths)}
""".trimIndent(),
Paths.get(dir.absolutePath, ".git", "info", "sparse-checkout").toFile()
)
}
}
override fun cloneLocallyAtHead(cloneLifetime: Lifetime) {
check(!clonedLocally)
val tempDirName = when {
config.branch != null -> "git_clone_${repositoryName}_${config.branch}_"
config.tag != null -> "git_clone_${repositoryName}_${config.tag}_"
else -> "git_clone_${repositoryName}_"
}
localCloneTempDir = filesystem.getTemporaryDirectory(tempDirName, cloneLifetime)
try {
initLocal(localCloneTempDir)
val pullArgs = listOf("pull") +
(config.tag?.let { listOf("--tags") } ?: listOf()) +
when {
config.shallowCheckout -> listOf("--depth=1")
config.depth != null -> listOf("--depth=${config.depth}")
else -> listOf()
} +
"origin" +
(config.branch ?: config.tag ?: DEFAULT_BRANCH)
cmd.runCommand(localCloneTempDir.absolutePath, "git", pullArgs)
clonedLocally = true
revId = HEAD
} catch (e: CommandException) {
throw MoeProblem(e, "Could not clone from git repo at $repositoryUrl: ${e.stderr}")
} catch (e: IOException) {
throw MoeProblem(e, "Could not clone from git repo at $repositoryUrl: ${e.message}")
}
}
override fun updateToRevision(revId: String) {
check(clonedLocally)
check(this.revId == HEAD)
try {
val headHash = runGitCommand("rev-parse", HEAD).trim { it <= ' ' }
// If we are updating to a revision other than the branch's head, branch from that revision.
// Otherwise, no update/checkout is necessary since we are already at the desired revId,
// branch head.
if (headHash != revId) {
if (config.shallowCheckout) {
// Unshallow the repository to enable checking out given revId.
runGitCommand(
"fetch",
"--unshallow",
"origin",
config.branch ?: config.tag ?: DEFAULT_BRANCH)
}
runGitCommand("checkout", revId, "-b", MOE_MIGRATIONS_BRANCH_PREFIX + revId)
}
this.revId = revId
} catch (e: CommandException) {
throw MoeProblem(e, "Could not update git repo at %s: %s", localTempDir, e.stderr)
}
}
override fun archiveAtRevision(revId: String?): File {
check(clonedLocally)
val revId = if (revId.isNullOrEmpty()) HEAD else revId
val archiveLocation = filesystem.getTemporaryDirectory(
"git_archive_${repositoryName}_${revId}_", lifetimes.currentTask()
)
try {
filesystem.makeDirs(archiveLocation)
// Using this just to get a filename.
val tarballPath = filesystem.getTemporaryDirectory(
"git_tarball_${repositoryName}_$revId.tar.", lifetimes.currentTask()
).absolutePath
// Git doesn't support archiving to a directory: it only supports
// archiving to a tar. The fastest way to do this would be to pipe the
// output directly into tar, however, there's no option for that using
// the classes we have. (michaelpb)
val args = listOf("archive", "--format=tar", "--output=$tarballPath", revId) + config.paths
runGitCommand(*args.toTypedArray())
// Untar the tarball we just made
cmd.runCommand(
"", "tar", listOf("xf", tarballPath, "-C", archiveLocation.absolutePath)
)
} catch (e: CommandException) {
throw MoeProblem(e, "Could not archive git clone at ${localTempDir.absolutePath}")
} catch (e: IOException) {
throw MoeProblem(
e,
"IOException archiving clone at ${localTempDir.absolutePath} to revision $revId"
)
}
return archiveLocation
}
/**
* Runs a git command with the given arguments, in this cloned repository's directory.
*
* @param args a list of arguments for git
* @return a string containing the STDOUT result
*/
@Throws(CommandException::class)
// open for testing
open fun runGitCommand(vararg args: String): String {
return cmd
.runCommand(
localTempDir.absolutePath,
"git",
args.toList()
)
}
companion object {
/**
* A prefix for branches MOE creates to write migrated changes. For example, if there have been
* revisions in a to-repository since an equivalence revision, MOE won't try to merge or rebase
* those changes -- instead, it will create a branch with this prefix from the equivalence
* revision.
*/
const val MOE_MIGRATIONS_BRANCH_PREFIX = "moe_writing_branch_from_"
const val DEFAULT_BRANCH = "master"
const val HEAD = "HEAD"
}
}
| 1 | Java | 1 | 1 | 56f4cb8b1c673123757343d754931d2ed4b6ea26 | 7,764 | MOE | Apache License 2.0 |
shuttle/permissions/presentation/src/main/kotlin/shuttle/permissions/presentation/ui/PermissionItem.kt | 4face-studi0 | 462,194,990 | false | null | package shuttle.permissions.presentation.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material.icons.rounded.Warning
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import shuttle.design.PreviewUtils
import shuttle.design.theme.Dimens
import shuttle.design.theme.ShuttleTheme
import shuttle.permissions.presentation.model.PermissionItemUiModel
import studio.forface.shuttle.design.R
@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun PermissionItem(
permissionItem: PermissionItemUiModel,
onRequestPermission: () -> Unit
) {
val containerColor =
if (permissionItem.isGranted()) MaterialTheme.colorScheme.secondaryContainer
else MaterialTheme.colorScheme.errorContainer
Card(
colors = CardDefaults.cardColors(containerColor = containerColor),
modifier = Modifier
.padding(horizontal = Dimens.Margin.Medium, vertical = Dimens.Margin.Small)
.fillMaxWidth()
) {
Box(
modifier = Modifier
.padding(horizontal = Dimens.Margin.Medium, vertical = Dimens.Margin.Small)
.fillMaxWidth()
) {
when (permissionItem) {
is PermissionItemUiModel.Granted -> GrantedPermissionItem(permissionItem)
is PermissionItemUiModel.NotGranted -> NotGrantedPermissionItem(permissionItem, onRequestPermission)
}
}
}
}
@Composable
private fun GrantedPermissionItem(permissionItem: PermissionItemUiModel.Granted) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Text(text = stringResource(permissionItem.name), style = MaterialTheme.typography.titleLarge)
Icon(
painter = rememberVectorPainter(image = Icons.Rounded.CheckCircle),
tint = MaterialTheme.colorScheme.secondary,
contentDescription = stringResource(permissionItem.permissionGrantedDescription),
modifier = Modifier.size(Dimens.Icon.Medium)
)
}
Spacer(modifier = Modifier.height(Dimens.Margin.Small))
Text(
text = stringResource(permissionItem.permissionGrantedDescription),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Justify,
modifier = Modifier.fillMaxWidth()
)
}
}
@Composable
private fun NotGrantedPermissionItem(
permissionItem: PermissionItemUiModel.NotGranted,
onRequestPermission: () -> Unit
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Text(text = stringResource(permissionItem.name), style = MaterialTheme.typography.titleLarge)
Icon(
painter = rememberVectorPainter(image = Icons.Rounded.Warning),
tint = MaterialTheme.colorScheme.error,
contentDescription = stringResource(permissionItem.permissionNotGrantedDescription),
modifier = Modifier.size(Dimens.Icon.Medium)
)
}
Spacer(modifier = Modifier.height(Dimens.Margin.Small))
Text(
text = stringResource(permissionItem.description),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Justify,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(Dimens.Margin.Small))
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
Button(onClick = onRequestPermission) {
Text(text = stringResource(permissionItem.buttonText))
}
}
}
}
@Composable
@Preview(showBackground = true, widthDp = PreviewUtils.Dimens.Medium.Width)
private fun GrantedPermissionItemPreview() {
val uiModel = PermissionItemUiModel.Granted(
name = R.string.permissions_location_background_name,
permissionGrantedDescription = R.string.permissions_location_background_granted_description
)
ShuttleTheme {
PermissionItem(uiModel, onRequestPermission = {})
}
}
@Composable
@Preview(showBackground = true, widthDp = PreviewUtils.Dimens.Medium.Width)
private fun NotGrantedPermissionItemPreview() {
val uiModel = PermissionItemUiModel.NotGranted(
name = R.string.permissions_location_background_name,
description = R.string.permissions_location_background_description,
permissionNotGrantedDescription = R.string.permissions_location_background_not_granted_description,
buttonText = R.string.permissions_location_action
)
ShuttleTheme {
PermissionItem(uiModel, onRequestPermission = {})
}
}
| 11 | Kotlin | 0 | 14 | 55ab90f13bb96e10add14d45cd3117ada38262ed | 5,877 | Shuttle | Apache License 2.0 |
harness/bunnymark/src/main/kotlin/godot/benchmark/bunnymark/BunnymarkV3.kt | utopia-rise | 289,462,532 | false | null | package godot.benchmark.bunnymark
import godot.*
import godot.annotation.RegisterClass
import godot.annotation.RegisterFunction
import godot.annotation.RegisterSignal
import godot.benchmark.bunnymark.v3.Bunny
import godot.core.Vector2
import godot.signals.signal
@RegisterClass("BunnymarkV3")
class BunnymarkV3 : Node2D() {
@RegisterSignal
val benchmarkFinished by signal<Int>("bunnyCount")
private val randomNumberGenerator = RandomNumberGenerator()
private val bunnyTexture = ResourceLoader.load("res://images/godot_bunny.png") as Texture2D
private val label = Label()
private val bunnies = Node2D()
private lateinit var screenSize: Vector2
@RegisterFunction
override fun _ready() {
randomNumberGenerator.randomize()
addChild(bunnies)
label.setPosition(Vector2(0, 20))
addChild(label)
}
@RegisterFunction
override fun _process(delta: Double) {
screenSize = getViewportRect().size
label.text = "Bunnies ${bunnies.getChildCount()}"
}
@RegisterFunction
fun addBunny() {
val bunny = Bunny()
bunny.texture = bunnyTexture
bunnies.addChild(bunny)
bunny.position = Vector2(screenSize.x / 2, screenSize.y / 2)
bunny.speed = Vector2(randomNumberGenerator.randi() % 200 + 50, randomNumberGenerator.randi() % 200 + 50)
}
@RegisterFunction
fun removeBunny() {
val childCount = bunnies.getChildCount()
if (childCount != 0) {
val bunny = bunnies.getChild(childCount - 1)
bunnies.removeChild(bunny!!)
bunny.queueFree()
}
}
@RegisterFunction
fun finish() {
benchmarkFinished.emit(bunnies.getChildCount())
}
}
| 63 | null | 44 | 634 | ac2a1bd5ea931725e2ed19eb5093dea171962e3f | 1,578 | godot-kotlin-jvm | MIT License |
src/main/kotlin/com/sandrabot/sandra/commands/fun/Cat.kt | sandrabot | 121,549,855 | false | {"Kotlin": 178016} | /*
* Copyright 2017-2022 <NAME> and <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sandrabot.sandra.commands.`fun`
import com.sandrabot.sandra.entities.Command
import com.sandrabot.sandra.events.CommandEvent
import com.sandrabot.sandra.utils.httpClient
import com.sandrabot.sandra.utils.string
import dev.minn.jda.ktx.coroutines.await
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonObject
@Suppress("unused")
class Cat : Command() {
override suspend fun execute(event: CommandEvent) = withContext(Dispatchers.IO) {
event.deferReply(ephemeral = true).await()
val response = httpClient.get("https://cataas.com/cat?json=true")
if (response.status == HttpStatusCode.OK) {
val url = response.body<JsonObject>().string("url")
event.sendMessage("https://cataas.com$url").queue()
} else event.sendError(event.getAny("core.interaction_error")).queue()
}
}
| 1 | Kotlin | 3 | 9 | 525ce86e911a8439fed034cc038a2887693d4ba5 | 1,601 | sandra | Apache License 2.0 |
src/jvmMain/kotlin/matt/prim/endian/endian.kt | mgroth0 | 532,381,102 | false | {"Kotlin": 46339} | @file:JvmName("EndianJvmKt")
package matt.prim.endian
| 0 | Kotlin | 0 | 0 | c75eab71a13c5ec46b89e2fedbaeb6b0527a01f3 | 56 | prim | MIT License |
plugin/src/test/kotlin/org/jetbrains/hackathon2024/utils/ParseUtils.kt | ALikhachev | 858,702,876 | false | {"Kotlin": 37448, "Java": 265} | package org.jetbrains.hackathon2024.utils
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.stream.Collectors
internal fun parseClassFile(pathToClassFile: String): String {
val processBuilder = ProcessBuilder(
"javap",
"-v",
pathToClassFile,
)
processBuilder.redirectErrorStream()
val process = processBuilder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
process.waitFor()
return reader.lines().collect(Collectors.joining("\n"))
} | 0 | Kotlin | 0 | 0 | 8e6470ece4f3e04980223f9fe0efc8201024d127 | 546 | kapifence | Apache License 2.0 |
core/src/commonMain/kotlin/info/igreque/keepmecontributingkt/core/ContributionStatusChecker.kt | igrep | 176,618,584 | false | null | package info.igreque.keepmecontributingkt.core
class ContributionStatusChecker(
private val onChanged: (CheckResult) -> Unit,
private val gitHubClient: GitHubClient,
private val getBeginningOfToday: (Unit) -> Timestamp
) {
data class CheckResult(
val target: CheckTarget,
val contributionStatus: ContributionStatus
)
suspend fun doCheck(target: CheckTarget) {
if (!target.isFormFilled()) return
val beginningOfToday = getBeginningOfToday(Unit)
if (hasAlreadyCommittedAfter(target, beginningOfToday)) {
onChanged(CheckResult(target, ContributionStatus.DoneNoCheck))
return
}
onChanged(CheckResult(target, ContributionStatus.Unknown))
val (contributionStatus, latestCommitDate) = try {
val fetchedDate = gitHubClient.getLatestCommitDate(
target.contributorName.toString(),
target.repositoryName.toString()
)
if (fetchedDate > beginningOfToday) {
Pair(ContributionStatus.Done, fetchedDate)
} else {
Pair(ContributionStatus.NotYet, fetchedDate)
}
} catch (e: Throwable) {
Pair(ContributionStatus.Error(e), target.lastCommitTime)
}
onChanged(CheckResult(target.updateLastCommitTime(latestCommitDate), contributionStatus))
}
private fun hasAlreadyCommittedAfter(target: CheckTarget, beginningOfToday: Timestamp) =
target.lastCommitTime != null && target.lastCommitTime > beginningOfToday
} | 2 | Kotlin | 0 | 0 | 0a4ee2aebb48306d8788e076f183e7e82df0b57d | 1,579 | keep-me-contributing-kt | Apache License 2.0 |
src/main/kotlin/dev/crashteam/keanalytics/controller/MarketDbApiController.kt | crashteamdev | 643,974,955 | false | null | package dev.crashteam.keanalytics.controller
import dev.crashteam.keanalytics.controller.model.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import dev.crashteam.keanalytics.domain.mongo.ReportDocument
import dev.crashteam.keanalytics.domain.mongo.ReportStatus
import dev.crashteam.keanalytics.domain.mongo.ReportType
import dev.crashteam.keanalytics.domain.mongo.ReportVersion
import dev.crashteam.keanalytics.report.ReportFileService
import dev.crashteam.keanalytics.report.ReportService
import dev.crashteam.keanalytics.report.model.ReportJob
import dev.crashteam.keanalytics.repository.mongo.CategoryRepository
import dev.crashteam.keanalytics.repository.mongo.ProductCustomRepositoryImpl
import dev.crashteam.keanalytics.repository.mongo.ReportRepository
import dev.crashteam.keanalytics.repository.mongo.UserRepository
import dev.crashteam.keanalytics.repository.mongo.model.FindProductFilter
import dev.crashteam.keanalytics.repository.mongo.model.ProductTotalOrderAggregate
import dev.crashteam.keanalytics.repository.mongo.model.ShopTotalOrder
import dev.crashteam.keanalytics.repository.mongo.pageable.PageResult
import dev.crashteam.keanalytics.service.CategoryService
import dev.crashteam.keanalytics.service.ProductService
import dev.crashteam.keanalytics.service.UserRestrictionService
import org.springframework.core.convert.ConversionService
import org.springframework.format.annotation.DateTimeFormat
import org.springframework.http.*
import org.springframework.web.bind.annotation.*
import org.springframework.web.client.RestTemplate
import org.springframework.web.client.exchange
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.math.BigDecimal
import java.math.RoundingMode
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.*
import javax.validation.Valid
private val log = KotlinLogging.logger {}
@RestController
@RequestMapping(path = ["v1"], produces = [MediaType.APPLICATION_JSON_VALUE])
class MarketDbApiController(
private val productCustomRepository: ProductCustomRepositoryImpl,
private val reportRepository: ReportRepository,
private val userRepository: UserRepository,
private val categoryRepository: CategoryRepository,
private val productService: ProductService,
private val categoryService: CategoryService,
private val conversionService: ConversionService,
private val reportFileService: ReportFileService,
private val reportService: ReportService,
private val userRestrictionService: UserRestrictionService,
private val restTemplate: RestTemplate,
) {
@GetMapping("/shop/top")
suspend fun getTopShopByOrders(): ResponseEntity<Flux<ShopTotalOrder>> {
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(productCustomRepository.findTopShopsByTotalOrders())
}
@GetMapping("/product/top")
suspend fun getTopProductByOrders(): ResponseEntity<Flux<ProductTotalOrderAggregate>> {
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(productCustomRepository.findTopProductByOrders(100))
}
@GetMapping("/product/search")
suspend fun searchProduct(
@RequestParam(required = false) category: String?,
@RequestParam(required = false) seller: String?,
@RequestParam(name = "seller_link", required = false) sellerLink: String?,
@RequestParam(name = "product_name", required = false) productName: String?,
@RequestParam(name = "order_amount_gt", required = false) orderAmountGt: Long?,
@RequestParam(name = "order_amount_lt", required = false) orderAmountLt: Long?,
@RequestParam(defaultValue = "0") page: Int,
@RequestParam(defaultValue = "20") size: Int,
@RequestParam(defaultValue = "product_id,desc") sort: Array<String>,
): ResponseEntity<Mono<PageResult<ProductView>>> {
val filter = FindProductFilter(
category = category,
sellerName = seller,
sellerLink = sellerLink,
productName = productName,
orderAmountGt = orderAmountGt,
orderAmountLt = orderAmountLt,
)
val productsPageResult = productService.findProductByProperties(filter, sort, page, size).map { pageResult ->
val productViewList = pageResult.result.map {
conversionService.convert(it, ProductView::class.java)!!
}
PageResult(productViewList, pageResult.pageSize, pageResult.page, pageResult.totalPages)
}
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(productsPageResult)
}
@GetMapping("/product/{id}")
suspend fun getProduct(@PathVariable id: String): ResponseEntity<ProductView> {
val product = productService.getProduct(id.toLong()).map {
conversionService.convert(it, ProductView::class.java)!!
}.awaitSingleOrNull() ?: return ResponseEntity.notFound().build()
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(product)
}
@GetMapping("/product/{product_id}/orders")
suspend fun getProductSalesInfo(
@PathVariable(name = "product_id") id: Long,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<ProductTotalOrdersView> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
val productTotalSales = productService.getProductOrders(id, fromTime, toTime)
?: return ResponseEntity.notFound().build()
val productTotalSalesView = conversionService.convert(productTotalSales, ProductTotalOrdersView::class.java)!!
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(productTotalSalesView)
}
@GetMapping("/product/sales/")
suspend fun getProductSales(
@RequestParam productIds: LongArray,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<Map<Long, ProductTotalSalesView>> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
val userDocument = userRepository.findByApiKey_HashKey(apiKey).awaitSingleOrNull()
val limitProductIds = if (productIds.size > 60) {
log.warn { "Too match productIds on product sales endpoint. userId=${userDocument?.userId}" }
productIds.take(60).toLongArray()
} else productIds
val productsSales = productService.getProductsSales(limitProductIds, fromTime, toTime)
if (productsSales == null) {
log.warn { "Not found product sales for productIds=$limitProductIds; fromTime=$fromTime; toTime=$toTime" }
return ResponseEntity.notFound().build()
}
val groupedByProductId: Map<Long, List<ProductSkuTotalSalesView>> = productsSales.groupBy(
{ it.productId },
{
if (it.dayChange.isEmpty()) {
ProductSkuTotalSalesView(
it.productId,
it.skuId,
BigDecimal.ZERO,
0,
it.seller.let { ProductTotalSalesSeller(it.title, it.link, it.accountId) })
} else {
val totalSalesAmount =
it.dayChange.map { dayChange -> dayChange.salesAmount }.reduce { a, b -> a + b }
val totalOrderAmount =
it.dayChange.map { dayChange -> dayChange.orderAmount }.reduce { a, b -> a + b }
ProductSkuTotalSalesView(
it.productId,
it.skuId,
totalSalesAmount,
totalOrderAmount,
it.seller.let { ProductTotalSalesSeller(it.title, it.link, it.accountId) })
}
}
)
val productTotalSales = groupedByProductId.mapValues {
val totalSalesAmount = it.value.map { it.salesAmount }.reduce { a, b -> a + b }
val totalOrderAmount = it.value.map { it.orderAmount }.reduce { a, b -> a + b }
val daysBetween = ChronoUnit.DAYS.between(fromTime, toTime)
val dailyOrder = BigDecimal.valueOf(totalOrderAmount)
.divide(BigDecimal.valueOf(daysBetween), 2, RoundingMode.HALF_UP)
ProductTotalSalesView(it.key, totalSalesAmount, totalOrderAmount, dailyOrder, it.value[0].seller)
}
return ResponseEntity.ok(productTotalSales)
}
@GetMapping("/product/{product_id}/sku/{sku_id}/sales")
suspend fun getProductSales(
@PathVariable(name = "product_id") id: Long,
@PathVariable(name = "sku_id") skuId: Long,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestParam(defaultValue = "0") page: Int,
@RequestParam(defaultValue = "20") size: Int,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<PageResult<ProductSkuHistoricalView>> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
val pageResult = productService.getProductSkuSalesHistory(id, skuId, fromTime, toTime, page, size)
if (pageResult == null) {
log.warn { "Not found history for productId=$id; skuId=$skuId; fromTime=$fromTime; toTime=$toTime" }
return ResponseEntity.notFound().build()
}
val productSalesView =
pageResult.result.map { conversionService.convert(it, ProductSkuHistoricalView::class.java)!! }
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(PageResult(productSalesView, pageResult.pageSize, pageResult.page))
}
@GetMapping("/category/sales")
suspend fun getCategorySales(
@RequestParam(name = "ids") ids: List<Long>,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestParam(defaultValue = "0") page: Int,
@RequestParam(defaultValue = "20") size: Int,
@RequestParam(defaultValue = "sku_id,desc") sort: Array<String>,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<CategorySalesViewWrapper> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
val categorySales = productService.getCategorySales(ids, fromTime, toTime, sort, page, size).awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
val categorySalesViewWrapper = conversionService.convert(categorySales, CategorySalesViewWrapper::class.java)
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(categorySalesViewWrapper)
}
@GetMapping("/seller/sales")
suspend fun getSellerSales(
@RequestParam(name = "title", required = false) title: String?,
@RequestParam(name = "link", required = false) link: String?,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestParam(defaultValue = "0") page: Int,
@RequestParam(defaultValue = "20") size: Int,
@RequestParam(defaultValue = "sku_id,desc") sort: Array<String>,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<CategorySalesViewWrapper> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
if (title == null && link == null) {
return ResponseEntity.badRequest().build()
}
val categorySales =
productService.getSellerSalesPageable(title, link, fromTime, toTime, sort, page, size).awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
val categorySalesViewWrapper = conversionService.convert(categorySales, CategorySalesViewWrapper::class.java)
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(categorySalesViewWrapper)
}
@GetMapping("/categories")
suspend fun getCategories(): ResponseEntity<Flux<CategoryView>> {
val categories = categoryService.getAllCategories().map {
conversionService.convert(it, CategoryView::class.java)!!
}
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(categories)
}
@GetMapping("/category/products")
suspend fun getCategoryProductIds(@RequestParam(name = "ids") ids: List<Long>): ResponseEntity<List<Long>> {
val categoryProducts = productService.getCategoryProductIds(ids).collectList().awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(categoryProducts)
}
@GetMapping("/category/sellers")
suspend fun getCategorySellerIds(@RequestParam(name = "ids") ids: List<Long>): ResponseEntity<List<Long>> {
val categoryProducts = productService.getCategorySellerIds(ids).collectList().awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(categoryProducts)
}
@GetMapping("/seller/products")
suspend fun getSellerProducts(@RequestParam sellerLink: String): ResponseEntity<List<Long>> {
val sellerProductIds = productService.getSellerProductIdsByLink(sellerLink).collectList().awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(sellerProductIds)
}
@GetMapping("/report/seller/{link}")
suspend fun generateReportBySeller(
@PathVariable(name = "link") sellerLink: String,
@RequestParam(name = "period") daysPeriod: Int,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
@RequestHeader(name = "Idempotence-Key", required = true) idempotenceKey: String
): ResponseEntity<ReportJob> {
val user = userRepository.findByApiKey_HashKey(apiKey).awaitSingleOrNull()
?: throw IllegalStateException("User not found")
// Check report period permission
val checkDaysAccess = userRestrictionService.checkDaysAccess(user, daysPeriod)
if (checkDaysAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
// Check daily report count permission
val userReportDailyReportCount = reportService.getUserShopReportDailyReportCount(user.userId)
val checkReportAccess =
userRestrictionService.checkShopReportAccess(user, userReportDailyReportCount?.toInt() ?: 0)
if (checkReportAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build()
}
// Save report job
val jobId = UUID.randomUUID().toString()
val report = reportRepository.findByRequestIdAndSellerLink(idempotenceKey, sellerLink).awaitSingleOrNull()
if (report != null && report.status != ReportStatus.FAILED) {
return ResponseEntity.ok().body(ReportJob(report.jobId, report.reportId))
}
reportRepository.save(
ReportDocument(
reportId = null,
requestId = idempotenceKey,
jobId = jobId,
userId = user.userId,
period = null,
interval = daysPeriod,
createdAt = LocalDateTime.now(),
sellerLink = sellerLink,
categoryPublicId = null,
reportType = ReportType.SELLER,
status = ReportStatus.PROCESSING,
version = ReportVersion.V1
)
).awaitSingleOrNull()
reportService.incrementShopUserReportCount(user.userId)
return ResponseEntity.ok().body(ReportJob(jobId))
}
@GetMapping("/report/category")
suspend fun generateReportByCategory(
@RequestParam(name = "ids") ids: List<Long>,
@RequestParam(name = "period") daysPeriod: Int,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
@RequestHeader(name = "Idempotence-Key", required = true) idempotenceKey: String
): ResponseEntity<Any> {
val user = userRepository.findByApiKey_HashKey(apiKey).awaitSingleOrNull()
?: throw IllegalStateException("User not found")
// Check report period permission
val checkDaysAccess = userRestrictionService.checkDaysAccess(user, daysPeriod)
if (checkDaysAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
// Check daily report count permission
val userReportDailyReportCount = reportService.getUserCategoryReportDailyReportCount(user.userId)
val checkReportAccess = userRestrictionService.checkCategoryReportAccess(
user, userReportDailyReportCount?.toInt() ?: 0
)
if (checkReportAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build()
}
val categoryDocument = if (ids.size == 1) {
categoryRepository.findByPublicId(ids.first()).awaitSingleOrNull()
?: throw IllegalArgumentException("Invalid category id")
} else {
val path = productService.buildCategoryPath(ids)
categoryRepository.findByPath(path).awaitFirstOrNull()
?: throw IllegalArgumentException("Invalid category path: $path")
}
val jobId = UUID.randomUUID().toString()
val report = reportRepository.findByRequestIdAndCategoryPublicId(idempotenceKey, categoryDocument.publicId)
.awaitSingleOrNull()
if (report != null && report.status != ReportStatus.FAILED) {
return ResponseEntity.ok().body(ReportJob(report.jobId, report.reportId))
}
val categoryTitlePath = ids.map {
categoryRepository.findByPublicId(it).awaitSingle().title
}
log.info { "Create report document with categoryId=${categoryDocument.publicId} and categoryPath=$categoryTitlePath" }
reportRepository.save(
ReportDocument(
reportId = null,
requestId = idempotenceKey,
jobId = jobId,
userId = user.userId,
period = null,
interval = daysPeriod,
createdAt = LocalDateTime.now(),
sellerLink = null,
categoryPublicId = categoryDocument.publicId,
categoryPath = categoryTitlePath,
reportType = ReportType.CATEGORY,
status = ReportStatus.PROCESSING,
version = ReportVersion.V1
)
).awaitSingleOrNull()
reportService.incrementCategoryUserReportCount(user.userId)
return ResponseEntity.ok().body(ReportJob(jobId))
}
@GetMapping("/report/{report_id}")
suspend fun getReportBySellerWithId(
@PathVariable(name = "report_id") reportId: String,
): ResponseEntity<ByteArray> {
val report = reportFileService.getReport(reportId) ?: return ResponseEntity.notFound().build()
val reportData = withContext(Dispatchers.IO) {
report.stream.readAllBytes()
}
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"${report.name}.xlsx\"")
.body(reportData)
}
@GetMapping("/report/state/{job_id}")
suspend fun getReportStatus(@PathVariable(name = "job_id") jobId: String): ResponseEntity<ReportStatusView> {
val reportDoc = reportRepository.findByJobId(jobId).awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
return ResponseEntity.ok(
ReportStatusView(
reportId = reportDoc.reportId,
jobId = reportDoc.jobId,
status = reportDoc.status.name.lowercase(),
interval = reportDoc.interval ?: -1,
reportType = reportDoc.reportType?.name ?: "unknown",
createdAt = reportDoc.createdAt,
sellerLink = reportDoc.sellerLink,
categoryId = reportDoc.categoryPublicId
)
)
}
@GetMapping("/reports")
suspend fun getReports(
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
): ResponseEntity<MutableList<ReportStatusView>> {
val user = userRepository.findByApiKey_HashKey(apiKey).awaitSingleOrNull()
?: return ResponseEntity.notFound().build()
val reportDocuments =
reportRepository.findByUserIdAndCreatedAtFromTime(user.userId, fromTime).map { reportDoc ->
ReportStatusView(
reportId = reportDoc.reportId,
jobId = reportDoc.jobId,
status = reportDoc.status.name.lowercase(),
interval = reportDoc.interval ?: -1,
reportType = reportDoc.reportType?.name ?: "unknown",
createdAt = reportDoc.createdAt,
sellerLink = reportDoc.sellerLink,
categoryId = reportDoc.categoryPublicId
)
}.collectList().awaitSingleOrNull() ?: return ResponseEntity.notFound().build()
return ResponseEntity.ok(reportDocuments)
}
@GetMapping("/similar/products")
suspend fun getSimilarProducts(
@RequestParam(value = "productId", required = true) @Valid productId: Long,
@RequestParam(value = "skuId", required = true) @Valid skuId: Long
): ResponseEntity<List<SimilarItemView>> {
val url = "https://api.marketdb.ru/repricer/v1/similar/products?productId=$productId&skuId=$skuId"
val httpHeaders = HttpHeaders().apply {
set("Authorization", "Basic cHJvbWV0aGV1czptYXJrZXRsb2xwYXNzd2Q=")
set("X-Request-Id", UUID.randomUUID().toString())
}
val httpEntity = HttpEntity<Any>(httpHeaders)
val responseEntity = restTemplate.exchange<List<SimilarItemView>>(url, HttpMethod.GET, httpEntity)
if (responseEntity.statusCode.is4xxClientError) {
return ResponseEntity.badRequest().build()
} else if (responseEntity.statusCode.is5xxServerError) {
return ResponseEntity.internalServerError().build()
}
return ResponseEntity.ok(responseEntity.body!!)
}
@GetMapping("/category/{category_id}/product/{product_id}/sku/{sku_id}/positions")
suspend fun getProductPositions(
@PathVariable(name = "category_id") categoryId: Long,
@PathVariable(name = "product_id") productId: Long,
@PathVariable(name = "sku_id") skuId: Long,
@RequestParam(name = "from_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) fromTime: LocalDateTime,
@RequestParam(name = "to_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) toTime: LocalDateTime,
@RequestHeader(name = "X-API-KEY", required = true) apiKey: String,
): ResponseEntity<ProductPositionView> {
if (!checkRequestDaysPermission(apiKey, fromTime, toTime)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
}
val productPositions = productService.getProductPositions(categoryId, productId, skuId, fromTime, toTime)
?: return ResponseEntity.ok(null)
if (productPositions.isEmpty()) return ResponseEntity.ok(null)
val positionAggregate = productPositions.first()
return ResponseEntity.ok(ProductPositionView(
categoryId = positionAggregate.id!!.categoryId,
productId = positionAggregate.id!!.productId,
skuId = positionAggregate.id!!.skuId,
history = productPositions.map {
ProductPositionHistoryView(
position = it.position!!,
date = it.id?.date!!
)
}
))
}
private suspend fun checkRequestDaysPermission(
apiKey: String,
fromTime: LocalDateTime,
toTime: LocalDateTime
): Boolean {
val daysCount = ChronoUnit.DAYS.between(fromTime, toTime)
if (daysCount <= 0) return true
val user = userRepository.findByApiKey_HashKey(apiKey).awaitSingleOrNull()
?: throw IllegalStateException("User not found")
val checkDaysAccess = userRestrictionService.checkDaysAccess(user, daysCount.toInt())
if (checkDaysAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return false
}
val checkDaysHistoryAccess = userRestrictionService.checkDaysHistoryAccess(user, fromTime)
if (checkDaysHistoryAccess == UserRestrictionService.RestrictionResult.PROHIBIT) {
return false
}
return true
}
}
| 2 | Kotlin | 0 | 0 | eebed26e9761ec2ccd12d6a1968098afdb2afc39 | 27,170 | ke-analytics | Apache License 2.0 |
openrndr-gl3/src/main/kotlin/org/openrndr/internal/gl3/ShaderGL3.kt | shi-weili | 237,852,942 | false | null | package org.openrndr.internal.gl3
import mu.KotlinLogging
import org.lwjgl.BufferUtils
import org.lwjgl.opengl.GL11C
import org.lwjgl.opengl.GL33C.*
import org.openrndr.color.ColorRGBa
import org.openrndr.draw.*
import org.openrndr.internal.Driver
import org.openrndr.math.*
import java.io.File
import java.io.FileWriter
import java.nio.Buffer
import java.nio.ByteBuffer
private val logger = KotlinLogging.logger {}
private var blockBindings = 0
class UniformBlockGL3(override val layout: UniformBlockLayout, val blockBinding: Int, val ubo: Int, val shadowBuffer: ByteBuffer) : UniformBlock {
internal val thread = Thread.currentThread()
private val lastValues = mutableMapOf<String, Any>()
var realDirty: Boolean = true
override val dirty: Boolean
get() = realDirty
companion object {
fun create(layout: UniformBlockLayout): UniformBlockGL3 {
synchronized(Driver.driver) {
val ubo = glGenBuffers()
glBindBuffer(GL_UNIFORM_BUFFER, ubo)
glBufferData(GL_UNIFORM_BUFFER, layout.sizeInBytes.toLong(), GL_DYNAMIC_DRAW)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
glBindBufferBase(GL_UNIFORM_BUFFER, blockBindings, ubo)
blockBindings++
val buffer = BufferUtils.createByteBuffer(layout.sizeInBytes)
return UniformBlockGL3(layout, blockBindings - 1, ubo, buffer)
}
}
}
override fun uniform(name: String, value: Float) {
if (lastValues[name] != value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.FLOAT32 && entry.size == 1) {
shadowBuffer.putFloat(entry.offset, value)
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
lastValues[name] = value
realDirty = true
}
}
override fun uniform(name: String, value: Vector2) {
if (lastValues[name] != value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR2_FLOAT32 && entry.size == 1) {
shadowBuffer.putFloat(entry.offset, value.x.toFloat())
shadowBuffer.putFloat(entry.offset + 4, value.y.toFloat())
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
lastValues[name] = value
realDirty = true
}
}
override fun uniform(name: String, value: Vector3) {
if (lastValues[name] != value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR3_FLOAT32 && entry.size == 1) {
shadowBuffer.putFloat(entry.offset, value.x.toFloat())
shadowBuffer.putFloat(entry.offset + 4, value.y.toFloat())
shadowBuffer.putFloat(entry.offset + 8, value.z.toFloat())
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
lastValues[name] = value
realDirty = true
}
}
override fun uniform(name: String, value: ColorRGBa) {
if (lastValues[name] != value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR4_FLOAT32 && entry.size == 1) {
shadowBuffer.putFloat(entry.offset, value.r.toFloat())
shadowBuffer.putFloat(entry.offset + 4, value.g.toFloat())
shadowBuffer.putFloat(entry.offset + 8, value.b.toFloat())
shadowBuffer.putFloat(entry.offset + 12, value.a.toFloat())
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
lastValues[name] = value
realDirty = true
}
}
override fun uniform(name: String, value: Vector4) {
if (lastValues[name] != value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR4_FLOAT32 && entry.size == 1) {
shadowBuffer.putFloat(entry.offset, value.x.toFloat())
shadowBuffer.putFloat(entry.offset + 4, value.y.toFloat())
shadowBuffer.putFloat(entry.offset + 8, value.z.toFloat())
shadowBuffer.putFloat(entry.offset + 12, value.w.toFloat())
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
lastValues[name] = value
realDirty = true
}
}
override fun uniform(name: String, value: Matrix44) {
if (lastValues[name] !== value) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.MATRIX44_FLOAT32 && entry.size == 1) {
(shadowBuffer as Buffer).position(entry.offset)
shadowBuffer.putFloat(value.c0r0.toFloat())
shadowBuffer.putFloat(value.c0r1.toFloat())
shadowBuffer.putFloat(value.c0r2.toFloat())
shadowBuffer.putFloat(value.c0r3.toFloat())
shadowBuffer.putFloat(value.c1r0.toFloat())
shadowBuffer.putFloat(value.c1r1.toFloat())
shadowBuffer.putFloat(value.c1r2.toFloat())
shadowBuffer.putFloat(value.c1r3.toFloat())
shadowBuffer.putFloat(value.c2r0.toFloat())
shadowBuffer.putFloat(value.c2r1.toFloat())
shadowBuffer.putFloat(value.c2r2.toFloat())
shadowBuffer.putFloat(value.c2r3.toFloat())
shadowBuffer.putFloat(value.c3r0.toFloat())
shadowBuffer.putFloat(value.c3r1.toFloat())
shadowBuffer.putFloat(value.c3r2.toFloat())
shadowBuffer.putFloat(value.c3r3.toFloat())
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
lastValues[name] = value
}
}
override fun uniform(name: String, value: Matrix55) {
if (lastValues[name] !== value) {
val entry = layout.entries[name]
if (entry != null) {
val values = value.floatArray
if (entry.type == UniformType.FLOAT32 && entry.size == 25) {
for (i in 0 until 25) {
shadowBuffer.putFloat(entry.offset + i * entry.stride, values[i])
}
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
lastValues[name] = value
}
}
override fun uniform(name: String, value: Array<Float>) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.FLOAT32 && entry.size == value.size) {
for (i in 0 until value.size) {
shadowBuffer.putFloat(entry.offset + i * entry.stride, value[i])
}
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
}
override fun uniform(name: String, value: Array<Vector2>) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR4_FLOAT32 && entry.size == value.size) {
shadowBuffer.safePosition(entry.offset)
for (i in 0 until value.size) {
shadowBuffer.putFloat(value[i].x.toFloat())
shadowBuffer.putFloat(value[i].y.toFloat())
}
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
}
override fun uniform(name: String, value: Array<Vector3>) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR4_FLOAT32 && entry.size == value.size) {
shadowBuffer.safePosition(entry.offset)
for (i in 0 until value.size) {
shadowBuffer.putFloat(value[i].x.toFloat())
shadowBuffer.putFloat(value[i].y.toFloat())
shadowBuffer.putFloat(value[i].z.toFloat())
}
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
}
override fun uniform(name: String, value: Array<Vector4>) {
val entry = layout.entries[name]
if (entry != null) {
if (entry.type == UniformType.VECTOR4_FLOAT32 && entry.size == value.size) {
shadowBuffer.safePosition(entry.offset)
for (i in 0 until value.size) {
shadowBuffer.putFloat(value[i].x.toFloat())
shadowBuffer.putFloat(value[i].y.toFloat())
shadowBuffer.putFloat(value[i].z.toFloat())
}
} else {
throw RuntimeException("uniform mismatch")
}
} else {
throw RuntimeException("uniform not found $name")
}
realDirty = true
}
override fun upload() {
if (Thread.currentThread() != thread) {
throw IllegalStateException("current thread ${Thread.currentThread()} is not equal to creation thread $thread")
}
realDirty = false
glBindBuffer(GL_UNIFORM_BUFFER, ubo)
shadowBuffer.safeRewind()
glBufferSubData(GL_UNIFORM_BUFFER, 0L, shadowBuffer)
checkGLErrors()
glBindBuffer(GL_UNIFORM_BUFFER, 0)
}
}
private fun ByteBuffer.safePosition(offset: Int) {
(this as Buffer).position(offset)
}
private fun ByteBuffer.safeRewind() {
(this as Buffer).rewind()
}
internal fun checkShaderInfoLog(`object`: Int, code: String, sourceFile: String) {
logger.debug { "getting shader info log" }
val logLength = IntArray(1)
glGetShaderiv(`object`, GL_INFO_LOG_LENGTH, logLength)
logger.debug { "log length: ${logLength[0]}" }
if (logLength[0] > 0) {
logger.debug { "getting log" }
val infoLog = BufferUtils.createByteBuffer(logLength[0])
(infoLog as Buffer).rewind()
glGetShaderInfoLog(`object`, logLength, infoLog)
val infoBytes = ByteArray(logLength[0])
infoLog.get(infoBytes)
println("GLSL compilation problems in\n ${String(infoBytes)}")
val temp = File("ShaderError.txt")
FileWriter(temp).use {
it.write(code)
}
System.err.println("click.to.see.shader.code(ShaderError.txt:1)")
logger.error { "GLSL shader compilation failed for $sourceFile" }
throw Exception("Shader error: $sourceFile")
}
}
fun checkProgramInfoLog(`object`: Int, sourceFile: String) {
val logLength = IntArray(1)
glGetProgramiv(`object`, GL_INFO_LOG_LENGTH, logLength)
if (logLength[0] > 1) {
val infoLog = BufferUtils.createByteBuffer(logLength[0])
glGetProgramInfoLog(`object`, logLength, infoLog)
val linkInfoBytes = ByteArray(logLength[0])
infoLog.get(linkInfoBytes)
println("GLSL link problems in\n ${String(linkInfoBytes)}")
logger.warn {
val infoBytes = ByteArray(logLength[0])
infoLog.get(infoBytes)
"GLSL link problems in\n ${String(infoBytes)}"
}
throw Exception("Shader error: $sourceFile")
}
}
class ShaderGL3(val program: Int,
val name: String,
val vertexShader: VertexShaderGL3,
val fragmentShader: FragmentShaderGL3,
override val session: Session?) : Shader {
private var destroyed = false
private var running = false
private var uniforms: MutableMap<String, Int> = hashMapOf()
private var attributes: MutableMap<String, Int> = hashMapOf()
private var blockBindings = hashMapOf<String, Int>()
private val blocks: MutableMap<String, Int> = hashMapOf()
/**
* Is this a shader created by the user, i.e. should we perform extra checking on the inputs
*/
internal var userShader = true
companion object {
fun create(vertexShader: VertexShaderGL3, fragmentShader: FragmentShaderGL3, session: Session?): ShaderGL3 {
synchronized(Driver.driver) {
debugGLErrors()
val name = "${vertexShader.name} / ${fragmentShader.name}"
val program = glCreateProgram()
debugGLErrors()
glAttachShader(program, vertexShader.shaderObject)
debugGLErrors()
glAttachShader(program, fragmentShader.shaderObject)
debugGLErrors()
glLinkProgram(program)
debugGLErrors()
val linkStatus = IntArray(1)
glGetProgramiv(program, GL_LINK_STATUS, linkStatus)
debugGLErrors()
if (linkStatus[0] != GL_TRUE) {
checkProgramInfoLog(program, "noname")
}
glFinish()
return ShaderGL3(program, name, vertexShader, fragmentShader, session)
}
}
}
override fun createBlock(blockName: String): UniformBlock {
val layout = blockLayout(blockName)
if (layout != null) {
return UniformBlockGL3.create(layout)
} else {
throw RuntimeException("block does not exists $blockName")
}
}
override fun blockLayout(blockName: String): UniformBlockLayout? {
val blockIndex = glGetUniformBlockIndex(program, blockName)
if (blockIndex == -1) {
return null
}
val blockSize = run {
val blockSizeBuffer = BufferUtils.createIntBuffer(1)
glGetActiveUniformBlockiv(program, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, blockSizeBuffer)
blockSizeBuffer[0]
}
if (blockSize != 0) {
val uniformCount = run {
val uniformCountBuffer = BufferUtils.createIntBuffer(1)
glGetActiveUniformBlockiv(program, blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, uniformCountBuffer)
uniformCountBuffer[0]
}
val uniformIndicesBuffer = BufferUtils.createIntBuffer(uniformCount)
val uniformIndices = run {
glGetActiveUniformBlockiv(program, blockIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, uniformIndicesBuffer)
(uniformIndicesBuffer as Buffer).rewind()
val array = IntArray(uniformCount)
uniformIndicesBuffer.get(array)
array
}
(uniformIndicesBuffer as Buffer).rewind()
val uniformTypes = run {
val buffer = BufferUtils.createIntBuffer(uniformCount)
glGetActiveUniformsiv(program, uniformIndicesBuffer, GL_UNIFORM_TYPE, buffer)
(buffer as Buffer).rewind()
val array = IntArray(uniformCount)
buffer.get(array)
array
}
val uniformSizes = run {
val buffer = BufferUtils.createIntBuffer(uniformCount)
glGetActiveUniformsiv(program, uniformIndicesBuffer, GL_UNIFORM_SIZE, buffer)
(buffer as Buffer).rewind()
val array = IntArray(uniformCount)
buffer.get(array)
array
}
val uniformOffsets = run {
val buffer = BufferUtils.createIntBuffer(uniformCount)
glGetActiveUniformsiv(program, uniformIndicesBuffer, GL_UNIFORM_OFFSET, buffer)
(buffer as Buffer).rewind()
val array = IntArray(uniformCount)
buffer.get(array)
array
}
val uniformStrides = run {
val buffer = BufferUtils.createIntBuffer(uniformCount)
glGetActiveUniformsiv(program, uniformIndicesBuffer, GL_UNIFORM_ARRAY_STRIDE, buffer)
(buffer as Buffer).rewind()
val array = IntArray(uniformCount)
buffer.get(array)
array
}
val uniformNames = uniformIndices.map {
glGetActiveUniformName(program, it, 128)
}
checkGLErrors()
return UniformBlockLayout(blockSize, (0 until uniformCount).map {
UniformDescription(uniformNames[it].replace(Regex("\\[.*\\]"), ""), uniformTypes[it].toUniformType(), uniformSizes[it], uniformOffsets[it], uniformStrides[it])
}.associateBy { it.name })
} else {
return null
}
}
override fun block(blockName: String, block: UniformBlock) {
if (Thread.currentThread() != (block as UniformBlockGL3).thread) {
throw IllegalStateException("block is created on ${block.thread} and is now used on ${Thread.currentThread()}")
}
if (!running) {
throw IllegalStateException("use begin() before setting blocks")
}
val blockIndex = blockIndex(blockName)
if (blockIndex == -1) {
throw IllegalArgumentException("block not found $blockName")
}
if (blockBindings[blockName] != block.blockBinding) {
//checkGLErrors()
glUniformBlockBinding(program, blockIndex, block.blockBinding)
debugGLErrors()
blockBindings[blockName] = block.blockBinding
}
}
fun blockIndex(block: String): Int {
return blocks.getOrPut(block) {
glGetUniformBlockIndex(program, block)
}
}
fun uniformIndex(uniform: String, query: Boolean = false): Int =
uniforms.getOrPut(uniform) {
val location = glGetUniformLocation(program, uniform)
debugGLErrors()
if (location == -1 && !query) {
logger.warn {
"shader ${name} does not have uniform $uniform"
}
}
location
}
override fun begin() {
logger.trace { "shader begin $name" }
running = true
glUseProgram(program)
debugGLErrors {
when (it) {
GL_INVALID_VALUE -> "program is neither 0 nor a value generated by OpenGL"
GL_INVALID_OPERATION -> "program ($program) is not a program object / program could not be made part of current state / transform feedback mode is active."
else -> null
}
}
}
override fun end() {
logger.trace { "shader end $name" }
glUseProgram(0)
debugGLErrors()
running = false
}
override fun hasUniform(name: String): Boolean {
return uniformIndex(name, true) != -1
}
override fun uniform(name: String, value: ColorRGBa) {
val index = uniformIndex(name)
if (index != -1) {
glUniform4f(index, value.r.toFloat(), value.g.toFloat(), value.b.toFloat(), value.a.toFloat())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Vector3) {
val index = uniformIndex(name)
if (index != -1) {
glUniform3f(index, value.x.toFloat(), value.y.toFloat(), value.z.toFloat())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Vector4) {
val index = uniformIndex(name)
if (index != -1) {
glUniform4f(index, value.x.toFloat(), value.y.toFloat(), value.z.toFloat(), value.w.toFloat())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, x: Float, y: Float, z: Float, w: Float) {
val index = uniformIndex(name)
if (index != -1) {
glUniform4f(index, x, y, z, w)
}
}
override fun uniform(name: String, x: Float, y: Float, z: Float) {
val index = uniformIndex(name)
if (index != -1) {
glUniform3f(index, x, y, z)
}
}
override fun uniform(name: String, x: Float, y: Float) {
val index = uniformIndex(name)
if (index != -1) {
glUniform2f(index, x, y)
}
}
override fun uniform(name: String, value: Int) {
val index = uniformIndex(name)
if (index != -1) {
glUniform1i(index, value)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Boolean) {
val index = uniformIndex(name)
if (index != -1) {
glUniform1i(index, if (value) 1 else 0)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Vector2) {
val index = uniformIndex(name)
if (index != -1) {
glUniform2f(index, value.x.toFloat(), value.y.toFloat())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Float) {
val index = uniformIndex(name)
if (index != -1) {
glUniform1f(index, value)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Double) {
val index = uniformIndex(name)
if (index != -1) {
glUniform1f(index, value.toFloat())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Matrix33) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
glUniformMatrix3fv(index, false, value.toFloatArray())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Matrix44) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
glUniformMatrix4fv(index, false, value.toFloatArray())
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Array<Vector2>) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
val floatValues = FloatArray(value.size * 2)
for (i in 0 until value.size) {
floatValues[i * 2] = value[i].x.toFloat()
floatValues[i * 2 + 1] = value[i].y.toFloat()
}
glUniform2fv(index, floatValues)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Array<Vector3>) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
val floatValues = FloatArray(value.size * 3)
for (i in 0 until value.size) {
floatValues[i * 3] = value[i].x.toFloat()
floatValues[i * 3 + 1] = value[i].y.toFloat()
floatValues[i * 3 + 2] = value[i].z.toFloat()
}
glUniform3fv(index, floatValues)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: Array<Vector4>) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
val floatValues = FloatArray(value.size * 4)
for (i in 0 until value.size) {
floatValues[i * 4] = value[i].x.toFloat()
floatValues[i * 4 + 1] = value[i].y.toFloat()
floatValues[i * 4 + 2] = value[i].z.toFloat()
floatValues[i * 4 + 3] = value[i].w.toFloat()
}
glUniform4fv(index, floatValues)
postUniformCheck(name, index, value)
}
}
override fun uniform(name: String, value: FloatArray) {
val index = uniformIndex(name)
if (index != -1) {
logger.trace { "Setting uniform '$name' to $value" }
glUniform1fv(index, value)
postUniformCheck(name, index, value)
}
}
private fun postUniformCheck(name: String, index: Int, value: Any) {
val errorCheck = { it: Int ->
val currentProgram = glGetInteger(GL_CURRENT_PROGRAM)
fun checkUniform(): String {
if (currentProgram > 0) {
val lengthBuffer = BufferUtils.createIntBuffer(1)
val sizeBuffer = BufferUtils.createIntBuffer(1)
val typeBuffer = BufferUtils.createIntBuffer(1)
val nameBuffer = BufferUtils.createByteBuffer(256)
glGetActiveUniform(currentProgram, index, lengthBuffer, sizeBuffer, typeBuffer, nameBuffer)
val nameBytes = ByteArray(lengthBuffer[0])
nameBuffer.safeRewind()
nameBuffer.get(nameBytes)
val retrievedName = String(nameBytes)
return "($name/$retrievedName): ${sizeBuffer[0]} / ${typeBuffer[0]}}"
}
return "no program"
}
when (it) {
GL_INVALID_OPERATION -> "no current program object ($currentProgram), or uniform type mismatch (${checkUniform()}"
else -> null
}
}
if (userShader) {
checkGLErrors(errorCheck)
} else {
debugGLErrors(errorCheck)
}
}
fun attributeIndex(name: String): Int =
attributes.getOrPut(name) {
val location = glGetAttribLocation(program, name)
debugGLErrors()
location
}
override fun destroy() {
if (!destroyed) {
session?.untrack(this)
glDeleteProgram(program)
destroyed = true
Session.active.untrack(this)
}
}
}
private fun Int.toUniformType(): UniformType {
return when (this) {
GL_FLOAT -> UniformType.FLOAT32
GL_FLOAT_VEC2 -> UniformType.VECTOR2_FLOAT32
GL_FLOAT_VEC3 -> UniformType.VECTOR3_FLOAT32
GL_FLOAT_VEC4 -> UniformType.VECTOR4_FLOAT32
GL_INT -> UniformType.VECTOR2_INT32
GL_INT_VEC2 -> UniformType.VECTOR2_INT32
GL_INT_VEC3 -> UniformType.VECTOR3_INT32
GL_INT_VEC4 -> UniformType.VECTOR4_INT32
GL_FLOAT_MAT4 -> UniformType.MATRIX44_FLOAT32
GL_FLOAT_MAT3 -> UniformType.MATRIX33_FLOAT32
GL_FLOAT_MAT2 -> UniformType.MATRIX22_FLOAT32
else -> throw RuntimeException("unsupported uniform type $this")
}
}
| 1 | null | 0 | 1 | 2b69f8dd818e36106bf76862fff171dc2ae73e3a | 28,105 | openrndr | BSD 2-Clause with views sentence |
url/src/commonMain/kotlin/captain/SegmentMatch.kt | aSoft-Ltd | 635,681,621 | false | {"Kotlin": 47412, "JavaScript": 110} | @file:JsExport
package kiota
import kotlin.js.JsExport
sealed interface SegmentMatch {
val path: String
}
data class WildCardMatch(override val path: String) : SegmentMatch
data class DynamicParamMatch(
override val path: String,
val key: String,
val value: String
) : SegmentMatch
data class ExactMatch(override val path: String) : SegmentMatch | 0 | Kotlin | 1 | 9 | 58219fec52eeecc073a3bc25e219806c29eb13ce | 367 | captain | MIT License |
engine/src/main/kotlin/com/delphix/sdk/objects/CallResult.kt | CloudSurgeon | 212,463,880 | true | {"Kotlin": 586314, "Shell": 46347, "Java": 9931, "Dockerfile": 904} | /**
* Copyright (c) 2019 by Delphix. All rights reserved.
*/
package com.delphix.sdk.objects
/**
* Result of an API call.
*/
interface CallResult : TypedObject {
val status: String? // Indicates whether an error occurred during the call.
override val type: String
override fun toMap(): Map<String, Any?>
}
| 0 | Kotlin | 0 | 1 | 819f7e9ea1bb0c675e0d04d61cf05302c488d74f | 323 | titan-server | Apache License 2.0 |
lib/src/main/kotlin/tsl/nodes/RBNode.kt | spbu-coding-2023 | 771,651,556 | false | {"Kotlin": 20989} | package tsl.nodes
class RBNode<K : Comparable<K>, V>(key: K, value: V) : AbstractNode<K, V, RBNode<K, V>>(key, value) {
internal var parent: RBNode<K, V>? = null
enum class Color {
Black,
Red,
}
internal var color = Color.Red
internal fun switchColor(node2: RBNode<K, V>?) {
val node1color = this.color
if (node2 != null) {
this.color = node2.color
node2.color = node1color
}
}
internal fun rotateLeft() {
val rightChild = this.rightChild ?: return
val dad = this.parent
this.switchColor(rightChild)
rightChild.leftChild?.parent = this
this.rightChild = rightChild.leftChild
rightChild.leftChild = this
when {
this == dad?.leftChild -> dad.leftChild = rightChild
this == dad?.rightChild -> dad.rightChild = rightChild
}
this.parent = rightChild
rightChild.parent = dad
}
internal fun rotateRight() {
val leftChild = this.leftChild ?: return
val dad = this.parent
this.switchColor(leftChild)
leftChild.rightChild?.parent = this
this.leftChild = leftChild.rightChild
leftChild.rightChild = this
when {
this == dad?.leftChild -> dad.leftChild = leftChild
this == dad?.rightChild -> dad.rightChild = leftChild
}
this.parent = leftChild
leftChild.parent = dad
}
}
| 1 | Kotlin | 0 | 3 | 2415fef533d3c11221f7ec5cac675bb0e90a6dc9 | 1,485 | trees-2 | MIT License |
src/main/kotlin/sen/khyber/io/web/WebResponse.kt | kkysen | 155,031,918 | false | {"Gradle": 1, "Gradle Kotlin DSL": 1, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 19, "Java": 1, "INI": 2, "XML": 12} | package sen.khyber.io.web
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.io.ByteArrayInputStream
import java.io.CharArrayReader
import java.io.Closeable
import java.io.InputStream
import java.io.Reader
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
import kotlin.LazyThreadSafetyMode.NONE
class WebResponse(private val response: Response) : Closeable by response {
val request: Request get() = response.request()
val url: HttpUrl get() = request.url()
val urlString: String get() = url.toString()
val body: ResponseBody get() = response.body()!!
val contentType: MediaType by lazy(NONE) { body.contentType()!! }
val charset: Charset? by lazy(NONE) { contentType.charset() }
fun charset(default: Charset = Charsets.UTF_8): Charset = charset ?: default
private val lazyByteBuffer = lazy(NONE) { ByteBuffer.wrap(body.bytes()) }
val byteBuffer: ByteBuffer by lazyByteBuffer
val charBuffer: CharBuffer by lazy(NONE) { charset().decode(byteBuffer) }
val length: Long
get() =
if (lazyByteBuffer.isInitialized()) byteBuffer.array().size.toLong() else body.contentLength()
val bytes: ByteArray get() = byteBuffer.array()
val chars: CharArray get() = charBuffer.array()
val string: String by lazy(NONE) { charBuffer.toString() }
fun append(sb: StringBuilder): StringBuilder = sb.append(chars)
val stringBuilder: StringBuilder get() = append(StringBuilder(chars.size))
val inputStream: InputStream get() = ByteArrayInputStream(bytes)
val reader: Reader get() = CharArrayReader(chars)
fun put(out: ByteBuffer): ByteBuffer = out.put(byteBuffer.duplicate())
val document: Document by lazy(NONE) { Jsoup.parse(inputStream, charset().name(), urlString) }
} | 1 | null | 1 | 1 | 9d219ba44ef51f2f0f5744b54b904a67f8cac2a3 | 2,029 | ColumbiaDirectory | MIT License |
agorauikit_android/src/main/java/io/agora/agorauikit_android/AgoraVideoViewer+Buttons.kt | AgoraIO-Community | 241,705,248 | false | null | package io.agora.agorauikit_android
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
internal class ButtonContainer(context: Context) : LinearLayout(context)
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getControlContainer(): ButtonContainer {
this.controlContainer?.let {
return it
}
val container = ButtonContainer(context)
container.visibility = View.VISIBLE
container.gravity = Gravity.CENTER
val containerLayout = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 200, Gravity.BOTTOM)
this.addView(container, containerLayout)
this.controlContainer = container
return container
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getCameraButton(): AgoraButton {
this.camButton?.let {
return it
}
val agCamButton = AgoraButton(context = this.context)
agCamButton.clickAction = {
(this.context as Activity).runOnUiThread {
it.isSelected = !it.isSelected
it.background.setTint(if (it.isSelected) Color.RED else Color.GRAY)
this.agkit.enableLocalVideo(!it.isSelected)
}
}
this.camButton = agCamButton
agCamButton.setImageResource(R.drawable.ic_video_mute)
return agCamButton
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getMicButton(): AgoraButton {
this.micButton?.let {
return it
}
val agMicButton = AgoraButton(context = this.context)
agMicButton.clickAction = {
it.isSelected = !it.isSelected
it.background.setTint(if (it.isSelected) Color.RED else Color.GRAY)
this.userVideoLookup[this.userID]?.audioMuted = it.isSelected
this.agkit.muteLocalAudioStream(it.isSelected)
}
this.micButton = agMicButton
agMicButton.setImageResource(android.R.drawable.stat_notify_call_mute)
return agMicButton
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getFlipButton(): AgoraButton {
this.flipButton?.let {
return it
}
val agFlipButton = AgoraButton(context = this.context)
agFlipButton.clickAction = {
this.agkit.switchCamera()
}
this.flipButton = agFlipButton
agFlipButton.setImageResource(R.drawable.btn_switch_camera)
return agFlipButton
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getEndCallButton(): AgoraButton {
this.endCallButton?.let {
return it
}
val hangupButton = AgoraButton(this.context)
hangupButton.clickAction = {
this.agkit.stopPreview()
this.leaveChannel()
}
hangupButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel)
hangupButton.background.setTint(Color.RED)
this.endCallButton = hangupButton
return hangupButton
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.getScreenShareButton(): AgoraButton? {
return null
}
internal fun AgoraVideoViewer.builtinButtons(): MutableList<AgoraButton> {
val rtnButtons = mutableListOf<AgoraButton>()
for (button in this.agoraSettings.enabledButtons) {
rtnButtons += when (button) {
AgoraSettings.BuiltinButton.MIC -> this.getMicButton()
AgoraSettings.BuiltinButton.CAMERA -> this.getCameraButton()
AgoraSettings.BuiltinButton.FLIP -> this.getFlipButton()
AgoraSettings.BuiltinButton.END -> this.getEndCallButton()
}
}
return rtnButtons
}
@ExperimentalUnsignedTypes
internal fun AgoraVideoViewer.addVideoButtons() {
var container = this.getControlContainer()
val buttons = this.builtinButtons() + this.agoraSettings.extraButtons
container.visibility = if (buttons.isEmpty()) View.INVISIBLE else View.VISIBLE
val buttonSize = 100
val buttonMargin = 10f
buttons.forEach { button ->
val llayout = LinearLayout.LayoutParams(buttonSize, buttonSize)
llayout.gravity = Gravity.CENTER
container.addView(button, llayout)
}
val contWidth = (buttons.size.toFloat() + buttonMargin) * buttons.count()
this.positionButtonContainer(container, contWidth, buttonMargin)
}
@ExperimentalUnsignedTypes
private fun AgoraVideoViewer.positionButtonContainer(container: ButtonContainer, contWidth: Float, buttonMargin: Float) {
// TODO: Set container position and size
container.setBackgroundColor(this.agoraSettings.colors.buttonBackgroundColor)
container.background.alpha = this.agoraSettings.colors.buttonBackgroundAlpha
// (container.subBtnContainer.layoutParams as? FrameLayout.LayoutParams)!!.width = contWidth.toInt()
(this.backgroundVideoHolder.layoutParams as? ViewGroup.MarginLayoutParams)
?.bottomMargin = if (container.visibility == View.VISIBLE) container.measuredHeight else 0
// this.addView(container)
}
| 6 | null | 9 | 21 | 41f49c91f298bbcb1fe8926efb306a0767aa4d0f | 4,940 | VideoUIKit-Android | MIT License |
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/store/db/model/WithHeldSessionEntity.kt | matrix-org | 287,466,066 | false | null | /*
* Copyright (c) 2020 New Vector Ltd
*
* 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 im.vector.matrix.android.internal.crypto.store.db.model
import im.vector.matrix.android.internal.crypto.model.event.WithHeldCode
import io.realm.RealmObject
import io.realm.annotations.Index
/**
* When an encrypted message is sent in a room, the megolm key might not be sent to all devices present in the room.
* Sometimes this may be inadvertent (for example, if the sending device is not aware of some devices that have joined),
* but some times, this may be purposeful.
* For example, the sender may have blacklisted certain devices or users,
* or may be choosing to not send the megolm key to devices that they have not verified yet.
*/
internal open class WithHeldSessionEntity(
var roomId: String? = null,
var algorithm: String? = null,
@Index var sessionId: String? = null,
@Index var senderKey: String? = null,
var codeString: String? = null,
var reason: String? = null
) : RealmObject() {
var code: WithHeldCode?
get() {
return WithHeldCode.fromCode(codeString)
}
set(code) {
codeString = code?.value
}
companion object
}
| 91 | null | 4 | 97 | 55cc7362de34a840c67b4bbb3a14267bc8fd3b9c | 1,764 | matrix-android-sdk2 | Apache License 2.0 |
library/src/test/kotlin/me/proxer/library/util/ProxerUrlsTest.kt | proxer | 43,981,937 | false | {"Kotlin": 492567} | package me.proxer.library.util
import me.proxer.library.enums.AnimeLanguage
import me.proxer.library.enums.Device
import me.proxer.library.enums.Language
import me.proxer.library.util.ProxerUrls.hasProxerHost
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class ProxerUrlsTest {
@Test
fun testWebBase() {
ProxerUrls.webBase.toString() shouldBeEqualTo "https://proxer.me/"
}
@Test
fun testApiBase() {
ProxerUrls.apiBase.toString() shouldBeEqualTo "https://proxer.me/api/v1/"
}
@Test
fun testCdnBase() {
ProxerUrls.cdnBase.toString() shouldBeEqualTo "https://cdn.proxer.me/"
}
@Test
fun testNewsImage() {
ProxerUrls.newsImage("1", "2").toString() shouldBeEqualTo "https://cdn.proxer.me/news/tmp/1_2.png"
}
@Test
fun testUserImage() {
ProxerUrls.userImage("1").toString() shouldBeEqualTo "https://cdn.proxer.me/avatar/1"
}
@Test
fun testEntryImage() {
ProxerUrls.entryImage("1").toString() shouldBeEqualTo "https://cdn.proxer.me/cover/tmp/1.jpg"
}
@Test
fun testProxyImage() {
ProxerUrls.proxyImage("https://example.com/image.png".toHttpUrl()).toString() shouldBeEqualTo
"https://proxy.proxer.me/index.php?url=https%3A%2F%2Fexample.com%2Fimage.png"
}
@Test
fun testProxyImageString() {
ProxerUrls.proxyImage("https://example.com/image.png").toString() shouldBeEqualTo
"https://proxy.proxer.me/index.php?url=https%3A%2F%2Fexample.com%2Fimage.png"
}
@Test
fun testTranslatorGroupImage() {
ProxerUrls.translatorGroupImage("1").toString() shouldBeEqualTo "https://cdn.proxer.me/translatorgroups/1.jpg"
}
@Test
fun testIndustryImage() {
ProxerUrls.industryImage("1").toString() shouldBeEqualTo "https://cdn.proxer.me/industry/1.jpg"
}
@Test
fun testHosterImage() {
ProxerUrls.hosterImage("play.png").toString() shouldBeEqualTo "https://proxer.me/images/hoster/play.png"
}
@Test
fun testMangaPageImage() {
ProxerUrls.mangaPageImage("1", "2", "3", "SAO").toString() shouldBeEqualTo
"https://manga1.proxer.me/f/2/3/SAO"
}
@Test
fun testDonateWeb() {
ProxerUrls.donateWeb().toString() shouldBeEqualTo "https://proxer.me/donate?device=default"
}
@Test
fun testDonateWebWithDevice() {
ProxerUrls.donateWeb(Device.DEFAULT).toString() shouldBeEqualTo "https://proxer.me/donate?device=default"
}
@Test
fun testWikiWeb() {
ProxerUrls.wikiWeb("test").toString() shouldBeEqualTo "https://proxer.me/wiki/test?device=default"
}
@Test
fun testUserWeb() {
ProxerUrls.userWeb("1").toString() shouldBeEqualTo "https://proxer.me/user/1?device=default"
}
@Test
fun testUserWebWithDevice() {
ProxerUrls.userWeb("2", Device.LEGACY_DESKTOP).toString() shouldBeEqualTo
"https://proxer.me/user/2?device=desktop"
}
@Test
fun testForumWeb() {
ProxerUrls.forumWeb("1", "2").toString() shouldBeEqualTo
"https://proxer.me/forum/1/2?device=default"
}
@Test
fun testForumWebWithDevice() {
ProxerUrls.forumWeb("1", "2", Device.MOBILE).toString() shouldBeEqualTo
"https://proxer.me/forum/1/2?device=mobile"
}
@Test
fun testNewsWeb() {
ProxerUrls.newsWeb("4", "5").toString() shouldBeEqualTo
"https://proxer.me/forum/4/5?device=default"
}
@Test
fun testNewsWebWithDevice() {
ProxerUrls.newsWeb("4", "5", Device.UNSPECIFIED).toString() shouldBeEqualTo
"https://proxer.me/forum/4/5?device="
}
@Test
fun testInfoWeb() {
ProxerUrls.infoWeb("332").toString() shouldBeEqualTo "https://proxer.me/info/332?device=default"
}
@Test
fun testInfoWebWithDevice() {
ProxerUrls.infoWeb("12", Device.MOBILE).toString() shouldBeEqualTo
"https://proxer.me/info/12?device=mobile"
}
@Test
fun testIndustryWeb() {
ProxerUrls.industryWeb("453").toString() shouldBeEqualTo "https://proxer.me/industry/453?device=default"
}
@Test
fun testTranslatorGroupWeb() {
ProxerUrls.translatorGroupWeb("123").toString() shouldBeEqualTo
"https://proxer.me/translatorgroups/123?device=default"
}
@Test
fun testAnimeWeb() {
ProxerUrls.animeWeb("1", 2, AnimeLanguage.OTHER).toString() shouldBeEqualTo
"https://proxer.me/watch/1/2/misc?device=default"
}
@Test
fun testAnimeWebWithDevice() {
ProxerUrls.animeWeb("1", 2, AnimeLanguage.GERMAN_DUB, Device.LEGACY_HTML).toString() shouldBeEqualTo
"https://proxer.me/watch/1/2/gerdub?device=html"
}
@Test
fun testMangaWeb() {
ProxerUrls.mangaWeb("19", 8, Language.ENGLISH).toString() shouldBeEqualTo
"https://proxer.me/chapter/19/8/en?device=default"
}
@Test
fun testMangaWebWithDevice() {
ProxerUrls.mangaWeb("3", 4, Language.GERMAN, Device.LEGACY_DESKTOP).toString() shouldBeEqualTo
"https://proxer.me/chapter/3/4/de?device=desktop"
}
@Test
fun testRegisterWeb() {
ProxerUrls.registerWeb().toString() shouldBeEqualTo "https://proxer.me/register?device=default"
}
@Test
fun testCaptchaWeb() {
ProxerUrls.captchaWeb().toString() shouldBeEqualTo "https://proxer.me/misc/captcha?device=default"
}
@Test
fun testCaptchaWebWithIp() {
ProxerUrls.captchaWeb("1.2.3.4").toString() shouldBeEqualTo
"https://proxer.me/misc/captcha?ip=1.2.3.4&device=default"
}
@Test
fun testCaptchaWebWithDevice() {
ProxerUrls.captchaWeb(null, Device.MOBILE).toString() shouldBeEqualTo
"https://proxer.me/misc/captcha?device=mobile"
}
@Test
fun testHasProxerHost() {
"https://proxer.me/test".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostCdn() {
"https://cdn.proxer.me/test".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostProxy() {
"https://proxy.proxer.me/index.php?url=test".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostManga() {
"https://manga1.proxer.me/f/test".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostStream() {
"https://stream.proxer.me/files/embed-abc.html".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostFileStream() {
"https://s39-ps.proxer.me/files/test.mp4".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasDotSeparatedProxerHostFileStream() {
"https://s39.ps.proxer.me/files/test.mp4".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasNewProxerHostFileStream() {
"https://s39-psc.proxer.me/files/test.mp4".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasAlternativeProxerHostFileStream() {
"https://s3.stream.proxer.me/files/test.mp4".toHttpUrl().hasProxerHost shouldBe true
}
@Test
fun testHasProxerHostFileStreamFalse() {
"https://s39-psfalse.proxer.me/files/test.mp4".toHttpUrl().hasProxerHost shouldBe false
}
@Test
fun testHasProxerHostFalse() {
"https://example.me/test".toHttpUrl().hasProxerHost shouldBe false
}
}
| 0 | Kotlin | 2 | 13 | f55585b485c8eff6da944032690fe4de40a58e65 | 7,574 | ProxerLibJava | MIT License |
app/src/main/java/io/github/joaogouveia89/checkmarket/marketListItemAdd/presentation/ItemAddScreen.kt | joaogouveia89 | 842,192,758 | false | {"Kotlin": 125865} | package io.github.joaogouveia89.checkmarket.marketListItemAdd.presentation
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import io.github.joaogouveia89.checkmarket.core.presentation.topBars.CheckMarketSearchAppBar
import io.github.joaogouveia89.checkmarket.marketListItemAdd.model.MatchItem
import io.github.joaogouveia89.checkmarket.marketListItemAdd.presentation.state.ItemAddState
internal const val NEW_ITEM_ID = -1
@Composable
fun ItemAddScreen(
onNavigateBack: () -> Unit,
onItemSelect: (MatchItem) -> Unit,
onNewQuery: (String) -> Unit,
uiState: ItemAddState
) {
var query by rememberSaveable { mutableStateOf("") }
Scaffold(
topBar = {
// Top App Bar
CheckMarketSearchAppBar(
onBackClick = { onNavigateBack() },
onQueryChange = {
query = it
onNewQuery(query)
}
)
}
) { paddingValues ->
ItemAddContent(
modifier = Modifier
.padding(paddingValues),
itemAddContentState = uiState.itemAddItemContentState,
matchItems = uiState.matchItems,
onItemSelect = { matchItem ->
val item = if (matchItem.id == NEW_ITEM_ID) {
matchItem.copy(name = query)
} else matchItem
onItemSelect(item)
}
)
}
}
@Preview
@Composable
private fun MarketListItemAddScreenPreview() {
ItemAddScreen(
onNavigateBack = {},
onItemSelect = {},
uiState = ItemAddState(),
onNewQuery = {}
)
}
| 0 | Kotlin | 0 | 0 | 93fe1499efd2d6813ad969d56e93f31b40ea259a | 2,006 | CheckMarket | MIT License |
identity/src/main/java/com/stripe/android/identity/networking/models/Requirement.kt | stripe | 6,926,049 | false | null | package com.stripe.android.identity.networking.models
import com.stripe.android.identity.navigation.ConsentDestination
import com.stripe.android.identity.navigation.DocSelectionDestination
import com.stripe.android.identity.navigation.DriverLicenseScanDestination
import com.stripe.android.identity.navigation.DriverLicenseUploadDestination
import com.stripe.android.identity.navigation.IDScanDestination
import com.stripe.android.identity.navigation.IDUploadDestination
import com.stripe.android.identity.navigation.IndividualDestination
import com.stripe.android.identity.navigation.PassportScanDestination
import com.stripe.android.identity.navigation.PassportUploadDestination
import com.stripe.android.identity.navigation.SelfieDestination
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal enum class Requirement {
@SerialName("biometric_consent")
BIOMETRICCONSENT,
@SerialName("id_document_back")
IDDOCUMENTBACK,
@SerialName("id_document_front")
IDDOCUMENTFRONT,
@SerialName("id_document_type")
IDDOCUMENTTYPE,
@SerialName("face")
FACE,
@SerialName("id_number")
IDNUMBER,
@SerialName("dob")
DOB,
@SerialName("name")
NAME,
@SerialName("address")
ADDRESS;
internal companion object {
private val SCAN_UPLOAD_ROUTE_SET = setOf(
DriverLicenseUploadDestination.ROUTE,
IDUploadDestination.ROUTE,
PassportUploadDestination.ROUTE,
DriverLicenseScanDestination.ROUTE,
IDScanDestination.ROUTE,
PassportScanDestination.ROUTE
)
val INDIVIDUAL_REQUIREMENT_SET = setOf(
NAME,
DOB,
ADDRESS,
IDNUMBER
)
/**
* Checks whether the Requirement matches the route the error occurred from.
*/
fun Requirement.matchesFromRoute(fromRoute: String) =
when (this) {
BIOMETRICCONSENT -> {
fromRoute == ConsentDestination.ROUTE.route
}
IDDOCUMENTBACK -> {
SCAN_UPLOAD_ROUTE_SET.any {
it.route == fromRoute
}
}
IDDOCUMENTFRONT -> {
SCAN_UPLOAD_ROUTE_SET.any {
it.route == fromRoute
}
}
IDDOCUMENTTYPE -> {
fromRoute == DocSelectionDestination.ROUTE.route
}
FACE -> {
fromRoute == SelfieDestination.ROUTE.route
}
DOB, NAME, IDNUMBER, ADDRESS -> {
fromRoute == IndividualDestination.ROUTE.route
}
}
}
}
| 86 | null | 584 | 1,078 | 74bf7263f56d53aff2d0035127d84dd40609403d | 2,834 | stripe-android | MIT License |
KotlinMail/goodscenter/src/main/java/cn/xwj/goods/ui/widget/GoodsSkuPopView.kt | jxiaow | 123,389,640 | false | {"Java": 270055, "Kotlin": 243645} | package cn.xwj.goods.ui.widget
import android.content.Context
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import cn.xwj.baselibrary.ext.loadUrl
import cn.xwj.baselibrary.widget.DefaultTextWatcher
import cn.xwj.goods.R
import cn.xwj.goods.common.GoodsConstants
import cn.xwj.goods.data.protocol.GoodsSku
import cn.xwj.goods.event.SkuChangedEvent
import cn.xwj.baselibrary.utils.YuanFenConverter
import com.eightbitlab.rxbus.Bus
import kotlinx.android.synthetic.main.layout_sku_pop.view.*
import org.jetbrains.anko.editText
/**
* Author: xw
* Date: 2018-06-05 16:31:36
* Description: GoodsSkuPopView: .
*/
/*
商品SKU弹层
*/
class GoodsSkuPopView(context: Context) : PopupWindow(context), View.OnClickListener {
//根视图
private val mRootView: View
private val mContext: Context = context
private val mSkuViewList = arrayListOf<SkuView>()
init {
mRootView = LayoutInflater.from(mContext).inflate(R.layout.layout_sku_pop, null)
initView()
// 设置SelectPicPopupWindow的View
this.contentView = mRootView
// 设置SelectPicPopupWindow弹出窗体的宽
this.width = ViewGroup.LayoutParams.MATCH_PARENT
// 设置SelectPicPopupWindow弹出窗体的高
this.height = ViewGroup.LayoutParams.MATCH_PARENT
// 设置SelectPicPopupWindow弹出窗体可点击
this.isFocusable = true
// 设置SelectPicPopupWindow弹出窗体动画效果
this.animationStyle = R.style.AnimBottom
background.alpha = 150
// mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
mRootView.setOnTouchListener { _, event ->
val height = mRootView.findViewById<View>(R.id.mPopView).top
val y = event.y.toInt()
if (event.action == MotionEvent.ACTION_UP) {
if (y < height) {
dismiss()
}
}
true
}
}
/*
初始化视图
*/
private fun initView() {
mRootView.mCloseIv.setOnClickListener(this)
mRootView.mAddCartBtn.setOnClickListener(this)
mRootView.mSkuCountBtn.setCurrentNumber(1)
mRootView.mSkuCountBtn.editText().addTextChangedListener(
object : DefaultTextWatcher() {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Bus.send(SkuChangedEvent())
}
}
)
mRootView.mAddCartBtn.setOnClickListener {
dismiss()
}
}
/*
设置商品图标
*/
fun setGoodsIcon(text: String) {
mRootView.mGoodsIconIv.loadUrl(text)
}
/*
设置商品价格
*/
fun setGoodsPrice(text: Long) {
mRootView.mGoodsPriceTv.text = YuanFenConverter.changeF2YWithUnit(text)
}
/*
设置商品编号
*/
fun setGoodsCode(text: String) {
mRootView.mGoodsCodeTv.text = "商品编号:" + text
}
/*
设置商品SKU
*/
fun setSkuData(list: List<GoodsSku>) {
for (goodSku in list) {
val skuView = SkuView(mContext)
skuView.setSkuData(goodSku)
mSkuViewList.add(skuView)
mRootView.mSkuView.addView(skuView)
}
}
/*
获取选中的SKU
*/
fun getSelectSku(): String {
var skuInfo = ""
for (skuView in mSkuViewList) {
skuInfo += skuView.getSkuInfo().split(GoodsConstants.SKU_SEPARATOR)[1] + GoodsConstants.SKU_SEPARATOR
}
return skuInfo.take(skuInfo.length - 1)//刪除最后一个分隔
}
/*
获取商品数量
*/
fun getSelectCount() = mRootView.mSkuCountBtn.number
override fun onClick(v: View) {
when (v.id) {
R.id.mCloseIv -> dismiss()
R.id.mAddCartBtn -> {
dismiss()
}
}
}
}
| 1 | null | 1 | 1 | 2796496ebb7d279ad0f405102c107db9085545e7 | 3,884 | AndroidProjectStudio | Apache License 2.0 |
import-export/android/src/main/kotlin/studio/lunabee/onesafe/importexport/settings/AutoBackupSettingsUiState.kt | LunabeeStudio | 624,544,471 | false | null | /*
* Copyright (c) 2023-2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 10/17/2023 - for the oneSafe6 SDK.
* Last modified 10/17/23, 3:41 PM
*/
package studio.lunabee.onesafe.importexport.settings
import android.content.Intent
import studio.lunabee.onesafe.importexport.model.Backup
import java.net.URI
data class AutoBackupSettingsUiState(
val isBackupEnabled: Boolean,
val autoBackupFrequency: AutoBackupFrequency,
val latestBackup: Backup?,
val isCloudBackupEnabled: Boolean,
val isKeepLocalBackupEnabled: Boolean,
val toggleKeepLocalBackup: () -> Unit,
val driveUri: URI?,
val driveAccount: String?,
) {
companion object {
fun disabled(): AutoBackupSettingsUiState = AutoBackupSettingsUiState(
isBackupEnabled = false,
autoBackupFrequency = AutoBackupFrequency.DAILY,
latestBackup = null,
isCloudBackupEnabled = false,
isKeepLocalBackupEnabled = false,
toggleKeepLocalBackup = {},
driveUri = null,
driveAccount = null,
)
}
}
data class AutoBackupSettingsDriveAuth(
val authorizeIntent: Intent,
val onAuthorize: (Boolean) -> Unit,
)
| 1 | null | 1 | 2 | 26deecf44e0bec9944a2bf231da1dff1ec829745 | 1,772 | oneSafe6_SDK_Android | Apache License 2.0 |
library/src/main/java/cloud/pace/sdk/appkit/model/App.kt | pace | 303,641,261 | false | null | package cloud.pace.sdk.appkit.model
import android.graphics.Bitmap
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class App(
var name: String,
var shortName: String,
var description: String? = null,
var url: String,
var logo: Bitmap? = null,
var iconBackgroundColor: String? = null,
var textBackgroundColor: String? = null,
var textColor: String? = null,
var display: String? = null,
var poiId: String? = null
) : Parcelable {
override fun equals(other: Any?): Boolean {
return when {
(other is App) -> {
url == other.url
}
else -> false
}
}
override fun hashCode(): Int {
return url.hashCode()
}
}
| 0 | Kotlin | 1 | 5 | c459c30690f3c2c480986312a3d837698ce028bc | 773 | cloud-sdk-android | MIT License |
ui/morealbums/src/main/kotlin/app/surgo/ui/morealbums/MoreAlbums.kt | tsukiymk | 382,220,719 | false | {"Kotlin": 889558, "Shell": 553, "CMake": 252, "C++": 166} | package app.surgo.ui.morealbums
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.surgo.common.compose.LocalContentPadding
import app.surgo.common.compose.NavArguments.SubRoutes
import app.surgo.common.compose.utils.copy
import app.surgo.common.resources.R
import app.surgo.common.ui.AlbumColumn
import app.surgo.ui.morealbums.MoreAlbumsAction.OpenAlbumDetails
@Composable
fun MoreAlbumsScreen(
toAlbumDetails: (Long, Boolean) -> Unit,
navigateUp: () -> Unit
) {
val viewModel = hiltViewModel<MoreAlbumsViewModel>()
MoreAlbumsContent(
viewModel = viewModel,
navigateUp = navigateUp
) { action ->
when (action) {
is OpenAlbumDetails -> {
toAlbumDetails(action.albumId, action.fromLocal)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MoreAlbumsContent(
viewModel: MoreAlbumsViewModel,
navigateUp: () -> Unit,
emit: (MoreAlbumsAction) -> Unit,
) {
val viewState by viewModel.state.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
when (viewModel.subRoute) {
SubRoutes.FAVORITE -> stringResource(R.string.title_favorite_albums)
SubRoutes.RECENTLY_ADDED -> stringResource(R.string.title_recently_added_albums)
SubRoutes.RECENTLY_PLAYED -> stringResource(R.string.title_recently_played_albums)
else -> stringResource(R.string.text_more)
}
)
},
navigationIcon = {
IconButton(navigateUp) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = null
)
}
},
scrollBehavior = scrollBehavior
)
}
) { innerPadding ->
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = innerPadding.copy(
bottom = LocalContentPadding.current.calculateBottomPadding()
)
) {
when {
viewState.albums.isNotEmpty() -> {
items(viewState.albums) { album ->
AlbumColumn(
name = album.name ?: "",
imageUri = album.artwork,
subtitle = album.albumArtist ?: "",
onClick = { emit(OpenAlbumDetails(album.id, album.fromLocal)) }
)
}
}
else -> {
item {
Column(
modifier = Modifier
.fillParentMaxSize()
.wrapContentSize(Alignment.Center)
.padding(16.dp)
) {
Text("There's nothing here.")
}
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a364fa99ea63c6b18268ad26b3bb4c0a0603a98f | 4,240 | surgo | Apache License 2.0 |
persistence/src/main/java/com/anytypeio/anytype/persistence/common/Provider.kt | anyproto | 647,371,233 | false | {"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334} | package com.anytypeio.anytype.core_utils.common
abstract class ParametrizedProvider<in P, out T> {
private var original: T? = null
abstract fun create(param: P): T
fun get(param: P): T = original ?: create(param).apply { original = this }
fun clear() {
original = null
}
} | 45 | Kotlin | 43 | 528 | c708958dcb96201ab7bb064c838ffa8272d5f326 | 304 | anytype-kotlin | RSA Message-Digest License |
qloud-spring-boot-starter/src/main/kotlin/network/qloud/integrations/boot/api/QloudApi.kt | QloudNetwork | 311,349,999 | false | {"Kotlin": 30715, "TypeScript": 15900, "JavaScript": 5448, "Python": 4981} | package network.qloud.integrations.boot.api
import network.qloud.integrations.boot.api.dto.QloudApiUser
import java.util.concurrent.CompletableFuture
interface QloudApi {
fun getUser(id: String): CompletableFuture<QloudApiUser>
fun deleteUser(id: String): CompletableFuture<Void>
}
| 11 | Kotlin | 0 | 2 | 905d025be3eaf3f7a816cf27aa2debed0f4a3a48 | 292 | qloud-integrations | MIT License |
src/main/kotlin/com/doist/gradle/androidtranslationscheck/AndroidTranslationsCheckExtension.kt | Doist | 317,819,000 | false | null | package com.doist.gradle.androidtranslationscheck
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.kotlin.dsl.property
@Suppress("UnstableApiUsage")
open class AndroidTranslationsCheckExtension(project: Project) {
val argumentRegex: Property<String> =
project.objects.property<String>().convention("""(?:%(?:[1-9]\$)?[sd%])""")
}
| 0 | Kotlin | 0 | 1 | f99c4596e9549363d2cbf1078c047bd4f4a58034 | 383 | android-translations-check | MIT License |
src/main/kotlin/com/doist/gradle/androidtranslationscheck/AndroidTranslationsCheckExtension.kt | Doist | 317,819,000 | false | null | package com.doist.gradle.androidtranslationscheck
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.kotlin.dsl.property
@Suppress("UnstableApiUsage")
open class AndroidTranslationsCheckExtension(project: Project) {
val argumentRegex: Property<String> =
project.objects.property<String>().convention("""(?:%(?:[1-9]\$)?[sd%])""")
}
| 0 | Kotlin | 0 | 1 | f99c4596e9549363d2cbf1078c047bd4f4a58034 | 383 | android-translations-check | MIT License |
src/test/java/examples/java/noreceiver/assertvrequire/Correct0.kt | cs125-illinois | 584,154,962 | false | {"Kotlin": 264477, "Java": 142525} | package examples.java.noreceiver.assertvrequire
fun positive(value: Int): Int {
require(value > 0)
return value
}
| 0 | Kotlin | 0 | 2 | 91ddb6431e7af559bab7843e8911fa9ac374ca08 | 123 | jenisol | MIT License |
src/main/kotlin/anonymous_inner_class_object_expression/AnonymousClassAndObjectExpression.kt | nazk420testing | 339,854,352 | false | {"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Kotlin": 24, "Java": 1, "XML": 12} | package anonymous_inner_class_object_expression
interface SessionInfoProvider {
fun print() {
println("Printing SessionInfoProvider")
}
}
open class SimpleProvider : SessionInfoProvider {
open val providerInfo: String
get() = "Simple Provider"
override fun print() {
println("Overriding in concrete class")
}
}
fun main() {
//Using object expression to create an anonymous class and add functionality to an existing class
val simpleProvider = object : SimpleProvider() {
override val providerInfo: String
get() = "New Info Provider"
fun getSimpleProvider(): String {
return "Property simple provider"
}
}
println(simpleProvider.getSimpleProvider())
println(simpleProvider.providerInfo)
} | 0 | Kotlin | 0 | 0 | 51ed7ef0f2c7ba9a328d703ceaa1c33be2eafc85 | 809 | kotlin | MIT License |
src/main/kotlin/icu/windea/pls/script/codeInsight/hints/ParadoxDefinitionReferenceInfoHintsProvider.kt | DragonKnightOfBreeze | 328,104,626 | false | {"Kotlin": 3162618, "Java": 164812, "Lex": 42980, "HTML": 24956, "Shell": 2741} | package icu.windea.pls.script.codeInsight.hints
import com.intellij.codeInsight.hints.*
import com.intellij.codeInsight.hints.presentation.*
import com.intellij.openapi.editor.*
import com.intellij.psi.*
import com.intellij.ui.dsl.builder.*
import icu.windea.pls.*
import icu.windea.pls.config.expression.*
import icu.windea.pls.core.*
import icu.windea.pls.model.*
import icu.windea.pls.model.constraints.*
import icu.windea.pls.script.codeInsight.hints.ParadoxDefinitionReferenceInfoHintsProvider.*
import icu.windea.pls.script.psi.*
import javax.swing.*
/**
* 定义引用信息的内嵌提示(对应定义的名字和类型、本地化名字)。
*/
@Suppress("UnstableApiUsage")
class ParadoxDefinitionReferenceInfoHintsProvider : ParadoxScriptHintsProvider<Settings>() {
data class Settings(
var showSubtypes: Boolean = true
)
private val settingsKey = SettingsKey<Settings>("ParadoxDefinitionReferenceInfoHintsSettingsKey")
private val expressionTypes = mutableSetOf(
CwtDataTypes.Definition,
CwtDataTypes.AliasName, //需要兼容alias
CwtDataTypes.AliasKeysField, //需要兼容alias
CwtDataTypes.AliasMatchLeft, //需要兼容alias
CwtDataTypes.SingleAliasRight, //需要兼容single_alias
)
override val name: String get() = PlsBundle.message("script.hints.definitionReferenceInfo")
override val description: String get() = PlsBundle.message("script.hints.definitionReferenceInfo.description")
override val key: SettingsKey<Settings> get() = settingsKey
override fun createSettings() = Settings()
override fun createConfigurable(settings: Settings): ImmediateConfigurable {
return object : ImmediateConfigurable {
override fun createComponent(listener: ChangeListener): JComponent = panel {
row {
checkBox(PlsBundle.message("script.hints.settings.showSubtypes")).bindSelected(settings::showSubtypes)
}
}
}
}
override fun PresentationFactory.collect(element: PsiElement, file: PsiFile, editor: Editor, settings: Settings, sink: InlayHintsSink): Boolean {
if(element !is ParadoxScriptExpressionElement) return true
if(!ParadoxResolveConstraint.Definition.canResolveReference(element)) return true
val reference = element.reference ?: return true
if(!ParadoxResolveConstraint.Definition.canResolve(reference)) return true
val resolved = reference.resolve() ?: return true
if(resolved is ParadoxScriptDefinitionElement) {
val definitionInfo = resolved.definitionInfo
if(definitionInfo != null) {
val presentation = doCollect(definitionInfo, settings)
val finalPresentation = presentation.toFinalPresentation(this, file.project)
val endOffset = element.endOffset
sink.addInlineElement(endOffset, true, finalPresentation, false)
}
}
return true
}
private fun PresentationFactory.doCollect(definitionInfo: ParadoxDefinitionInfo, settings: Settings): InlayPresentation {
val presentations: MutableList<InlayPresentation> = mutableListOf()
presentations.add(smallText(": "))
val typeConfig = definitionInfo.typeConfig
presentations.add(psiSingleReference(smallText(typeConfig.name)) { typeConfig.pointer.element })
if(settings.showSubtypes) {
val subtypeConfigs = definitionInfo.subtypeConfigs
for(subtypeConfig in subtypeConfigs) {
presentations.add(smallText(", "))
presentations.add(psiSingleReference(smallText(subtypeConfig.name)) { subtypeConfig.pointer.element })
}
}
return SequencePresentation(presentations)
}
}
| 12 | Kotlin | 5 | 29 | 8899a43db12b8c1e4edaa7e66b93143dcbd5ba68 | 3,758 | Paradox-Language-Support | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.