path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/ishanvohra2/findr/Util.kt | ishanvohra2 | 741,300,475 | false | {"Kotlin": 51796} | package com.ishanvohra2.findr
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
fun <T1, T2, R> combineState(
flow1: StateFlow<T1>,
flow2: StateFlow<T2>,
scope: CoroutineScope,
sharingStarted: SharingStarted = SharingStarted.Eagerly,
transform: (T1, T2) -> R
): StateFlow<R> = combine(flow1, flow2) {
o1, o2 -> transform.invoke(o1, o2)
}.stateIn(scope, sharingStarted, transform.invoke(flow1.value, flow2.value)) | 0 | Kotlin | 0 | 0 | 88b7755aeb83e9dcc2204013ed654222551d2448 | 598 | findr | Apache License 2.0 |
frontend/modules/core/src/jsMain/kotlin/io/github/andrewk2112/kjsbox/frontend/core/designtokens/reference/Opacities.kt | andrew-k-21-12 | 497,585,003 | false | null | package io.github.andrewk2112.kjsbox.frontend.designtokens.reference
/**
* All opacity values to be used in styles.
*/
class Opacities {
val full get() = 1
val p8 get() = 0.8
val p5 get() = 0.5
val p4 get() = 0.4
val transparent get() = 0
}
| 0 | Kotlin | 0 | 2 | f8bf02df72890ddcc7741aed992afad87f7d3c4f | 298 | kjs-box | MIT License |
android/src/com/android/tools/idea/avdmanager/ColdBootNowAction.kt | benjiesinzore | 576,548,172 | true | {"Text": 355, "EditorConfig": 2, "Markdown": 64, "Shell": 32, "Ignore List": 193, "XML": 13507, "Starlark": 142, "Kotlin": 6746, "Java": 8085, "Gradle": 2753, "Proguard": 169, "INI": 72, "JSON": 80, "Graphviz (DOT)": 1, "Ant Build System": 2, "Protocol Buffer": 8, "Java Properties": 166, "HTML": 67, "Batchfile": 20, "Gradle Kotlin DSL": 1655, "CMake": 19, "C": 29, "Checksums": 339, "C++": 14, "TOML": 2, "Smali": 5, "SVG": 1329, "AIDL": 9, "JFlex": 8, "Prolog": 6, "QMake": 2, "RenderScript": 1, "NSIS": 4, "GraphQL": 5, "Python": 10, "Makefile": 8, "YAML": 1, "HAProxy": 1, "Org": 2, "JavaScript": 3} | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.avdmanager
import com.android.tools.analytics.UsageTracker
import com.android.tools.idea.log.LogWrapper
import com.android.tools.idea.progress.StudioLoggerProgressIndicator
import com.android.tools.idea.sdk.AndroidSdks
import com.google.common.util.concurrent.Futures
import com.google.wireless.android.sdk.stats.AndroidStudioEvent
import com.google.wireless.android.sdk.stats.DeviceManagerEvent
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.concurrency.EdtExecutorService
import java.awt.event.ActionEvent
/**
* Launch the emulator now, forcing a cold boot.
* This does not change the general Cold/Fast selection.
*/
internal class ColdBootNowAction(avdInfoProvider: AvdInfoProvider,
private val logDeviceManagerEvents: Boolean) : AvdUiAction(avdInfoProvider,
"Cold Boot Now",
"Force one cold boot",
AllIcons.Actions.MenuOpen) {
override fun actionPerformed(actionEvent: ActionEvent) {
if (logDeviceManagerEvents) {
val deviceManagerEvent = DeviceManagerEvent.newBuilder()
.setKind(DeviceManagerEvent.EventKind.VIRTUAL_COLD_BOOT_NOW_ACTION)
.build()
val builder = AndroidStudioEvent.newBuilder()
.setKind(AndroidStudioEvent.EventKind.DEVICE_MANAGER)
.setDeviceManagerEvent(deviceManagerEvent)
UsageTracker.log(builder)
}
val project = myAvdInfoProvider.project
val avd = avdInfo ?: return
val deviceFuture = AvdManagerConnection.getDefaultAvdManagerConnection().startAvdWithColdBoot(project, avd)
Futures.addCallback(deviceFuture, AvdManagerUtils.newCallback(project), EdtExecutorService.getInstance())
}
override fun isEnabled(): Boolean {
return avdInfo != null
&& EmulatorAdvFeatures.emulatorSupportsFastBoot(AndroidSdks.getInstance().tryToChooseSdkHandler(),
StudioLoggerProgressIndicator(ColdBootNowAction::class.java),
LogWrapper(Logger.getInstance(AvdManagerConnection::class.java)))
}
}
| 0 | null | 0 | 0 | b373163869f676145341d60985cdbdaca3565c0b | 3,040 | android | Apache License 2.0 |
app/src/main/java/com/star/wars/landing/presentation/SplashActivity.kt | aldefy | 377,213,065 | false | {"Gradle": 11, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 2, "INI": 6, "Proguard": 7, "XML": 91, "Kotlin": 158, "Java": 2, "JSON": 9} | package com.star.wars.landing.presentation
import android.os.Bundle
import androidx.activity.viewModels
import androidx.navigation.findNavController
import com.star.wars.R
import com.star.wars.landing.presentation.SplashEvent.*
import com.star.wars.common.addTo
import com.star.wars.common.base.FullScreenActivity
import com.star.wars.common.viewBinding
import com.star.wars.databinding.ActivitySplashBinding
import com.star.wars.landing.domain.SplashViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SplashActivity : FullScreenActivity<SplashState>() {
private val binding by viewBinding(ActivitySplashBinding::inflate)
private val screen by lazy { SplashScreenImpl() }
private val vm: SplashViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.rootLayout)
setUpHandlers()
vm.load()
}
private fun setUpHandlers() {
vm.state.observe(
this,
{
it?.let {
_state.onNext(it)
}
}
)
screen.bind(binding, state.share())
.addTo(compositeBag)
screen.event.observe(
this,
{ event ->
when (event) {
is StartTimerEvent -> {
vm.startTimer()
}
is NavigateToNextScreenEvent -> {
findNavController(R.id.navHost).navigate(R.id.nav_spalash_search)
finish()
}
}
}
)
}
}
| 1 | null | 1 | 1 | 581db6c4af7547f3adb960980bf9fa8d973b6962 | 1,689 | StarWarsApp | Apache License 2.0 |
testsrc2/com/TTTTSSA.kt | shoukaiseki | 109,730,926 | false | null | package com
class TTTTSSA {
fun asuss(){
println("sss")
}
} | 1 | null | 1 | 1 | efdcbc4c4f67196c4c5936d20763c8be4f2f5a48 | 64 | snowmaximomobile | Apache License 2.0 |
stphotomap/src/main/java/com/streetography/stphotomap/scenes/stphotomap/location_level/STPhotoMapLocationLevelHandler.kt | mikelanza | 191,293,030 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 27, "Kotlin": 69, "JSON": 3, "XML": 15} | package com.streetography.stphotomap.scenes.stphotomap.location_level
import java.util.concurrent.CopyOnWriteArrayList
class STPhotoMapLocationLevelHandler() {
var activeDownloads: CopyOnWriteArrayList<String>
init {
this.activeDownloads = CopyOnWriteArrayList()
}
fun hasActiveDownload(url: String): Boolean {
return this.activeDownloads.contains(url)
}
fun addActiveDownload(url: String) {
this.activeDownloads.add(url)
}
fun removeActiveDownload(url: String) {
this.activeDownloads.remove(url)
}
fun removeAllActiveDownloads() {
this.activeDownloads.clear()
}
} | 0 | Kotlin | 0 | 2 | cff318d3b651751f338c94d3ddabe35be29c7174 | 655 | st-photo-map-android | MIT License |
integration-tests/src/test/kotlin/org/stellar/anchor/platform/test/Sep24End2EndTests.kt | stellar | 452,893,461 | false | null | package org.stellar.anchor.platform.test
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.fail
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions
import org.stellar.anchor.platform.CLIENT_WALLET_SECRET
import org.stellar.anchor.platform.TestConfig
import org.stellar.anchor.util.Sep1Helper
import org.stellar.walletsdk.ApplicationConfiguration
import org.stellar.walletsdk.StellarConfiguration
import org.stellar.walletsdk.Wallet
import org.stellar.walletsdk.anchor.DepositTransaction
import org.stellar.walletsdk.anchor.TransactionStatus
import org.stellar.walletsdk.anchor.TransactionStatus.*
import org.stellar.walletsdk.anchor.WithdrawalTransaction
import org.stellar.walletsdk.asset.IssuedAssetId
import org.stellar.walletsdk.auth.AuthToken
import org.stellar.walletsdk.horizon.SigningKeyPair
import org.stellar.walletsdk.horizon.sign
import org.stellar.walletsdk.horizon.transaction.toStellarTransfer
class Sep24End2EndTest(
private val config: TestConfig,
private val toml: Sep1Helper.TomlContent,
private val jwt: String
) {
private val walletSecretKey = System.getenv("WALLET_SECRET_KEY") ?: CLIENT_WALLET_SECRET
private val keypair = SigningKeyPair.fromSecret(walletSecretKey)
private val wallet =
Wallet(
StellarConfiguration.Testnet,
ApplicationConfiguration { defaultRequest { url { protocol = URLProtocol.HTTP } } }
)
private val USDC =
IssuedAssetId("USDC", "GDQOE23CFSUMSVQK4Y5JHPPYK73VYCNHZHA7ENKCV37P6SUEO6XQBKPP")
private val asset = USDC
private val client =
HttpClient() {
install(HttpTimeout) {
requestTimeoutMillis = 300000
connectTimeoutMillis = 300000
socketTimeoutMillis = 300000
}
}
private val anchor = wallet.anchor(config.env["anchor.domain"]!!)
private val maxTries = 40
private fun `typical deposit end-to-end flow`() = runBlocking {
val token = anchor.auth().authenticate(keypair)
val txId = makeDeposit(token)
// Wait for the status to change to COMPLETED
waitStatus(txId, COMPLETED, token)
}
private suspend fun makeDeposit(token: AuthToken, keyPair: SigningKeyPair = keypair): String {
// Start interactive deposit
val deposit =
anchor.interactive().deposit(keyPair.address, asset, token, mapOf("amount" to "5"))
// Get transaction status and make sure it is INCOMPLETE
val transaction = anchor.getTransaction(deposit.id, token)
assertEquals(INCOMPLETE, transaction.status)
// Make sure the interactive url is valid. This will also start the reference server's
// withdrawal process.
val resp = client.get(deposit.url)
print("accessing ${deposit.url}...")
assertEquals(200, resp.status.value)
return transaction.id
}
private fun `typical withdraw end-to-end flow`() {
`typical withdraw end-to-end flow`(mapOf())
`typical withdraw end-to-end flow`(mapOf("amount" to "5"))
}
private fun `typical withdraw end-to-end flow`(extraFields: Map<String, String>) = runBlocking {
val token = anchor.auth().authenticate(keypair)
// TODO: Add the test where the amount is not specified
// val withdrawal = anchor.interactive().withdraw(keypair.address, asset, token)
// Start interactive withdrawal
val withdrawal = anchor.interactive().withdraw(keypair.address, asset, token, extraFields)
// Get transaction status and make sure it is INCOMPLETE
val transaction = anchor.getTransaction(withdrawal.id, token)
assertEquals(INCOMPLETE, transaction.status)
// Make sure the interactive url is valid. This will also start the reference server's
// withdrawal process.
val resp = client.get(withdrawal.url)
print("accessing ${withdrawal.url}...")
assertEquals(200, resp.status.value)
// Wait for the status to change to PENDING_USER_TRANSFER_START
waitStatus(withdrawal.id, PENDING_USER_TRANSFER_START, token)
// Submit transfer transaction
val transfer =
(anchor.getTransaction(withdrawal.id, token) as WithdrawalTransaction).toStellarTransfer(
wallet.stellar(),
asset
)
transfer.sign(keypair)
wallet.stellar().submitTransaction(transfer)
// Wait for the status to change to PENDING_USER_TRANSFER_END
waitStatus(withdrawal.id, COMPLETED, token)
}
private suspend fun waitStatus(id: String, expectedStatus: TransactionStatus, token: AuthToken) {
var status: TransactionStatus? = null
for (i in 0..maxTries) {
// Get transaction info
val transaction = anchor.getTransaction(id, token)
if (status != transaction.status) {
status = transaction.status
println("Deposit transaction status changed to $status. Message: ${transaction.message}")
}
delay(1.seconds)
if (transaction.status == expectedStatus) {
return
}
}
fail("Transaction wasn't $expectedStatus in $maxTries tries, last status: $status")
}
private fun listAllTransactionWorks() = runBlocking {
val newAcc = wallet.stellar().account().createKeyPair()
val tx =
wallet
.stellar()
.transaction(keypair)
.sponsoring(keypair, newAcc) {
createAccount(newAcc)
addAssetSupport(USDC)
}
.build()
.sign(keypair)
.sign(newAcc)
wallet.stellar().submitTransaction(tx)
val token = anchor.auth().authenticate(newAcc)
val deposits = (0..5).map { makeDeposit(token, newAcc).also { delay(7.seconds) } }
deposits.forEach { waitStatus(it, COMPLETED, token) }
val history = anchor.getHistory(USDC, token)
Assertions.assertThat(history).allMatch { deposits.contains(it.id) }
}
private fun `list by stellar transaction id works`() = runBlocking {
val token = anchor.auth().authenticate(keypair)
val txId = makeDeposit(token)
waitStatus(txId, COMPLETED, token)
val transaction = anchor.getTransaction(txId, token) as DepositTransaction
val transactionByStellarId =
anchor.getTransactionBy(token, stellarTransactionId = transaction.stellarTransactionId)
assertEquals(transaction.id, transactionByStellarId.id)
}
fun testAll() {
println("Running SEP-24 end-to-end tests...")
`typical deposit end-to-end flow`()
`typical withdraw end-to-end flow`()
listAllTransactionWorks()
`list by stellar transaction id works`()
}
}
| 188 | null | 21 | 23 | bd0859aeadf11a353f19d92f2a5a242d4621e351 | 6,593 | java-stellar-anchor-sdk | Apache License 2.0 |
transcriber/transcriber-226/src/main/kotlin/net/rsprox/transcriber/impl/NpcInfoTranscriber.kt | blurite | 822,339,098 | false | {"Kotlin": 5997123, "HCL": 3626} | package net.rsprox.transcriber.impl
import net.rsprox.protocol.game.outgoing.model.info.npcinfo.NpcInfoV5
public fun interface NpcInfoTranscriber {
public fun npcInfoV5(message: NpcInfoV5)
}
| 9 | Kotlin | 12 | 31 | 78fb08c23ec5bedd194371627586005b50b01ada | 197 | rsprox | MIT License |
src/com/fytuu/list/KtArray.kt | StudyNoteOfTu | 632,443,930 | false | null | package com.fytuu.list
import java.io.File
/**
* Kt中的数组
* IntArray intArrayOf
* ByteArray byteArrayOf
* ...
* Array arrayOf 对象数组
*
* 越界保护
* 操作符重载
* List 与 Array 的转换
* 对象数组
*/
fun main() {
//1. intArrayOf 常规操作的越界崩溃
val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5)//Java中的int[]数组
println(intArray[0])
println(intArray.get(0))//get被重载为[0]
//这样的设计让数组和List集合的操作进行了统一,同时提供了越界保护!!!
println(intArray.getOrNull(100) ?: "out of boundary")//内部原理:帮我们做了下标越界判断
println(intArray.getOrElse(100) {
-1
})//内部原理:帮我们做了下标越界判断,越界返回内置函数(直接返回内置函数return的结果)
//---------集合转数组
val list = listOf("a","b","c")
//String被认为是引用类型,所以返回的是一个泛型数组
val strArray = list.toTypedArray()
println(strArray.javaClass) //class [Ljava.lang.String;
//对象数组
val array = arrayOf(File("a"),"a",1)
val array2 = arrayOf(File("a"))
println(array.javaClass) //class [Ljava.lang.Object;
println(array2.javaClass) //class [Ljava.io.File;
} | 0 | Kotlin | 0 | 0 | 73b0030ee89e267569371a819844fc5429877c3c | 982 | KotlinStudy | Apache License 2.0 |
src/commonMain/kotlin/com/codellyrandom/hassle/core/boot/statehandling/EntityStateInitializer.kt | efirestone | 379,712,425 | false | {"Kotlin": 271909} | package com.codellyrandom.hassle.core.boot.statehandling
import co.touchlab.kermit.Logger
import com.codellyrandom.hassle.HomeAssistantApiClientImpl
import com.codellyrandom.hassle.WebSocketSession
import com.codellyrandom.hassle.communicating.GetStatesCommand
import com.codellyrandom.hassle.entities.ActuatorStateUpdater
import com.codellyrandom.hassle.entities.EntityRegistrationValidation
import com.codellyrandom.hassle.entities.SensorStateUpdater
import com.codellyrandom.hassle.values.EntityId
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import kotlin.reflect.typeOf
internal class EntityStateInitializer(
private val apiClient: HomeAssistantApiClientImpl,
private val session: WebSocketSession,
private val sensorStateUpdater: SensorStateUpdater,
private val actuatorStateUpdater: ActuatorStateUpdater,
private val entityRegistrationValidation: EntityRegistrationValidation,
) {
private val logger = Logger
private val statesRequest = GetStatesCommand()
suspend fun initialize() {
val id = sendStatesRequest()
logger.i { "Requested initial entity states" }
setInitialEntityState(consumeStatesResponse(id))
}
private suspend fun sendStatesRequest() = apiClient.send(statesRequest)
private suspend fun consumeStatesResponse(id: Int) = session.consumeSingleMessage<StatesResponse>(id)
private fun setInitialEntityState(stateResponse: StatesResponse) {
if (stateResponse.success) {
val statesByEntityId: Map<EntityId, JsonObject> = stateResponse.result.associateBy { state ->
session.objectMapper.fromJson(state["entity_id"]!!, typeOf<EntityId>())
}
entityRegistrationValidation.validate(statesByEntityId.map { it.key })
for (state in statesByEntityId) {
sensorStateUpdater(flattenStateAttributes(state.value), state.key)
actuatorStateUpdater(flattenStateAttributes(state.value), state.key)
}
}
}
}
internal fun flattenStateAttributes(stateResponse: JsonObject): JsonObject {
val attributesAsJsonObject: JsonObject = stateResponse["attributes"]!!.jsonObject
return JsonObject(
mapOf(
"value" to stateResponse["state"]!!,
"last_updated" to stateResponse["last_updated"]!!,
"last_changed" to stateResponse["last_changed"]!!,
"user_id" to stateResponse["context"]!!.jsonObject["user_id"]!!,
).plus(attributesAsJsonObject.toMap()),
)
}
| 0 | Kotlin | 0 | 2 | 7423f41c01fff8c16651e0d4ebceb9a805744166 | 2,567 | hassle | MIT License |
app/src/main/java/com/oi/hata/common/reminder/data/local/model/ReminderWeekNum.kt | indurs | 354,514,038 | false | null | package com.oi.hata.common.reminder.data.local.model
import androidx.room.*
@Entity(
tableName = "reminder_weeknum",
foreignKeys = [
ForeignKey(
entity = ReminderMaster::class,
parentColumns = ["reminder_id"],
childColumns = ["weeknum_reminder_id"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index(value = ["weeknum_reminder_id"])]
)
data class ReminderWeekNum(
@ColumnInfo(name = "weeknum_id") @PrimaryKey(autoGenerate = true) var id: Long = 0,
@ColumnInfo(name = "weeknum_reminder_id") var weekNumReminderId: Long,
@ColumnInfo(name = "reminder_weeknum") var reminderWeekNum: Int
)
| 0 | Kotlin | 0 | 2 | 8442a9770ddef1dc93fa81c097091fcae93f20a2 | 681 | Hata | Apache License 2.0 |
src/main/kotlin/dp/BoxDepth.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
typealias Square = Tuple4<Int, Int, Int, Int>
// given n squares of size 10 as (X, Y) where X is the x-coordinate of its bottom
// left corner and Y is the y-coordinate of its bottom left corner
// find the largest subset of such squares : there is a common point in them
// and report the size of such set
fun OneArray<Tuple2<Int, Int>>.commonPoint(): Int {
val S = this
val n = size
// consider the input as a stack of squares piled from bottom to top (even
// though they don't overlap between each other, but just floating around)
// dp(i): largest such set that starts @ i-th square
val dp = OneArray(n) { 0 tu 0 tu 0 tu 0 tu 0 }
dp[n] = 1 tu S[n].toSquare()
for (i in n - 1 downTo 1) {
dp[i] = 1 tu S[i].toSquare()
for (j in i + 1..n) {
val area = dp[j].second tu dp[j].third tu dp[j].fourth tu dp[j].fifth
val overlap = S[i].overlap(area)
if (overlap.isValid() && dp[j].first + 1 > dp[i].first) {
dp[i] = dp[j].first + 1 tu overlap
}
}
}
return dp.maxBy { it.first }?.first ?: 0
}
private fun Tuple2<Int, Int>.toSquare() = this tu first + 10 tu second + 10
private fun Tuple2<Int, Int>.overlap(s: Square): Square {
// O(1) comparing
// r1 is the rectangle 1 that has smaller bottom right x coordinate
val (r1brx, r1bry, r1tlx, r1tly) = if (first < s.first) toSquare() else s
val (r2brx, r2bry, r2tlx, r2tly) = if (first < s.first) s else toSquare()
if (r1tlx < r2brx || r2tlx < r1brx || r1tly < r2bry || r2tly < r1bry) {
return 0 tu 0 tu 0 tu 0
}
return max(r1brx, r2brx) tu max(r1bry, r2bry) tu min(r1tlx, r2tlx) tu min(r1tly, r2tly)
}
private fun Square.isValid() = third > first && fourth > second
fun main(args: Array<String>) {
val s = oneArrayOf(
0 tu 0,
1 tu 1,
9 tu 9,
10 tu 10,
100 tu 200,
105 tu 190)
println(s.commonPoint())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,843 | AlgoKt | MIT License |
tupi-sample/src/main/kotlin/main.kt | gibran | 157,600,856 | false | null | package tupi.sample
import tupi.annotations.*
import tupi.annotations.enumerators.OperationType
import tupi.annotations.enumerators.ParameterType
fun main(args: Array<String>) {
println("Gerando...")
}
@SwaggerRoute("/accounts")
class Teste {
@SwaggerOperation(OperationType.GET, "/{id}", "Show data for a given account.")
@SwaggerResponses([SwaggerResponse(200, "Successful operation", Order::class)])
@SwaggerParameters(
[SwaggerParameter(ParameterType.PATH, "id", User::class, true, "Dados do usuário")]
)
// SwaggerResponse(400, "NotFound")])
fun Obter( id: User): String {
return "ok"
}
@SwaggerOperation(OperationType.GET, "", "O objetivo desta rota é retornar uma lista de ordens")
@SwaggerResponses([SwaggerResponse(400, "ERROS", Int::class)])
fun Listar(): Int {
return 1
}
}
| 3 | Kotlin | 0 | 4 | 4622128cf790636a55a94a8d3974b01035668088 | 868 | tupi | MIT License |
app/src/main/java/io/github/casl0/jvnlookup/ui/components/SnackbarLaunchedEffect.kt | CASL0 | 532,187,728 | false | {"Kotlin": 180644} | /*
* Copyright 2022 CASL0
*
* 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.github.casl0.jvnlookup.ui.components
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.flow.Flow
@Composable
fun Flow<Int>.SnackbarLaunchedEffect(
snackbarHostState: SnackbarHostState,
actionLabel: Int? = null,
actionCallback: ((SnackbarResult) -> Unit)? = null,
) {
val flow = this
val context = LocalContext.current
LaunchedEffect(snackbarHostState) {
flow.collect { message ->
val result = snackbarHostState.showSnackbar(
message = context.getString(message),
duration = SnackbarDuration.Short,
actionLabel = if (actionLabel != null) context.getString(actionLabel) else null
)
actionCallback?.let { actionCallback(result) }
}
}
} | 0 | Kotlin | 0 | 0 | ddb6e3509e6d20478a24ae96d0c13e3845ef6abd | 1,628 | jvnlookup | Apache License 2.0 |
server/src/main/kotlin/net/horizonsend/ion/server/features/starship/modules/RewardsProvider.kt | HorizonsEndMC | 461,042,096 | false | {"Kotlin": 2549911, "Java": 14047, "Shell": 1414, "JavaScript": 78} | package net.horizonsend.ion.server.features.starship.modules
import net.horizonsend.ion.server.features.starship.damager.Damager
interface RewardsProvider {
open fun onDamaged(damager: Damager) {}
fun onSink()
}
| 10 | Kotlin | 26 | 9 | 6977907e29a6b19f2b5c224c0ff9ead0d79b5395 | 217 | Ion | MIT License |
block-tlb/src/OldMcBlocksInfo.kt | ton-community | 448,983,229 | false | {"Kotlin": 1194581} | package org.ton.block
import kotlinx.serialization.Serializable
import org.ton.cell.CellBuilder
import org.ton.cell.CellSlice
import org.ton.hashmap.HashmapAugE
import org.ton.tlb.TlbCodec
import org.ton.tlb.TlbObject
import org.ton.tlb.TlbPrettyPrinter
import kotlin.jvm.JvmInline
@Serializable
@JvmInline
public value class OldMcBlocksInfo(
public val value: HashmapAugE<KeyExtBlkRef, KeyMaxLt>
) : TlbObject {
override fun print(printer: TlbPrettyPrinter): TlbPrettyPrinter {
return value.print(printer)
}
override fun toString(): String = print().toString()
public companion object : TlbCodec<OldMcBlocksInfo> by OldMcBlocksInfoTlbCodec
}
private object OldMcBlocksInfoTlbCodec : TlbCodec<OldMcBlocksInfo> {
private val codec = HashmapAugE.tlbCodec(32, KeyExtBlkRef, KeyMaxLt)
override fun storeTlb(cellBuilder: CellBuilder, value: OldMcBlocksInfo) {
codec.storeTlb(cellBuilder, value.value)
}
override fun loadTlb(cellSlice: CellSlice): OldMcBlocksInfo {
return OldMcBlocksInfo(codec.loadTlb(cellSlice))
}
}
| 21 | Kotlin | 24 | 80 | 7eb82e9b04a2e518182ebfc56c165fbfcc916be9 | 1,084 | ton-kotlin | Apache License 2.0 |
core/utils/platform/src/test/java/com/core/utils/platform/EitherCallTest.kt | LStudioO | 653,597,932 | false | null | package com.core.utils.platform
import com.core.utils.functional.Either
import com.core.utils.functional.leftValue
import com.core.utils.platform.network.ApiError
import com.core.utils.platform.network.EitherCall
import com.core.utils.platform.network.NetworkError
import com.core.utils.platform.network.UnknownApiError
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import okhttp3.Request
import okio.Timeout
import org.junit.Test
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
import java.lang.reflect.Type
import kotlin.test.assertEquals
import kotlin.test.assertNotSame
import kotlin.test.assertSame
import kotlin.test.assertTrue
class EitherCallTest {
@Test
fun `returns Either Right for a successful response`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val successResponse: Response<Any> = mockk(relaxed = true)
val responseBody: Any = mockk()
val sut = createSut(delegate)
every { successResponse.isSuccessful } returns true
every { successResponse.body() } returns responseBody
every { delegate.execute() } returns successResponse
// Act
val response = sut.execute()
// Assert
assertTrue(response.isSuccessful)
assertEquals(responseBody, response.body()?.orNull())
}
@Test
fun `returns Either Left for non-successful response`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val failureResponse: Response<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
every { failureResponse.isSuccessful } returns false
every { failureResponse.errorBody() } returns mockk()
every { failureResponse.errorBody()?.string() } returns "error"
every { delegate.execute() } returns failureResponse
// Act
val response = sut.execute()
// Assert
assertTrue(response.isSuccessful)
assertTrue(response.body()?.isLeft() ?: false)
}
@Test
fun `maps IOException to NetworkError`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val callback: Callback<Either<ApiError, Any>> = mockk(relaxed = true)
val throwable: Throwable = mockk<IOException>()
val sut = createSut(delegate)
every { delegate.enqueue(any()) } answers {
val capturedCallback = firstArg<Callback<Any>>()
capturedCallback.onFailure(delegate, throwable)
}
// Act
sut.enqueue(callback)
// Assert
val eitherResponse = slot<Response<Either<ApiError, Any>>>()
verify { callback.onResponse(any(), capture(eitherResponse)) }
assertTrue(eitherResponse.captured.isSuccessful)
assertTrue(eitherResponse.captured.body()?.isLeft() ?: false)
assertTrue(eitherResponse.captured.body()?.leftValue() is NetworkError)
}
@Test
fun `maps non-IOException to UnknownApiError`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val callback: Callback<Either<ApiError, Any>> = mockk(relaxed = true)
val throwable: Throwable = mockk()
val sut = createSut(delegate)
every { delegate.enqueue(any()) } answers {
val capturedCallback = firstArg<Callback<Any>>()
capturedCallback.onFailure(delegate, throwable)
}
// Act
sut.enqueue(callback)
// Assert
val eitherResponse = slot<Response<Either<ApiError, Any>>>()
verify { callback.onResponse(any(), capture(eitherResponse)) }
assertTrue(eitherResponse.captured.isSuccessful)
assertTrue(eitherResponse.captured.body()?.isLeft() ?: false)
assertTrue(eitherResponse.captured.body()?.leftValue() is UnknownApiError)
}
@Test
fun `clones instance of EitherCall`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val successType: Type = mockk()
val sut = EitherCall(delegate, successType)
every { delegate.clone() } returns delegate
// Act
val clonedCall = sut.clone() as EitherCall
// Assert
assertNotSame(sut, clonedCall)
assertSame(delegate, clonedCall.delegate)
assertSame(successType, clonedCall.successType)
}
@Test
fun `delegates isExecuted`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
every { delegate.isExecuted } returns true
// Act
val isExecuted = sut.isExecuted
// Assert
assertTrue(isExecuted)
}
@Test
fun `delegates cancel`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
// Act
sut.cancel()
// Assert
verify { delegate.cancel() }
}
@Test
fun `delegates isCanceled`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
every { delegate.isCanceled } returns true
// Act
val isCanceled = sut.isCanceled
// Assert
assertTrue(isCanceled)
}
@Test
fun `delegates request`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
val request: Request = mockk()
every { delegate.request() } returns request
// Act
val result = sut.request()
// Assert
assertSame(request, result)
}
@Test
fun `delegates timeout`() {
// Arrange
val delegate: Call<Any> = mockk(relaxed = true)
val sut = createSut(delegate)
val timeout: Timeout = mockk()
every { delegate.timeout() } returns timeout
// Act
val result = sut.timeout()
// Assert
assertSame(timeout, result)
}
private fun createSut(delegate: Call<Any>) =
EitherCall(delegate, Any::class.java)
}
| 0 | Kotlin | 0 | 2 | 4b7ad630dbd4838b66e560f463b025e79327bebd | 6,140 | CodeWarsChallengeViewer | Apache License 2.0 |
spring-boot/messaging-rabbitmq/src/main/kotlin/example/spring/boot/rabbitmq/messaging/MessagingConfiguration.kt | NovatecConsulting | 140,194,578 | false | {"Kotlin": 359621, "TypeScript": 46882, "HTML": 9446, "SCSS": 4665, "JavaScript": 1991, "Vim Snippet": 37} | package example.spring.boot.rabbitmq.messaging
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter
import org.springframework.amqp.support.converter.MessageConverter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class MessagingConfiguration {
@Bean
fun rabbitTemplate(connectionFactory: ConnectionFactory): RabbitTemplate =
RabbitTemplate(connectionFactory).apply { messageConverter = messageConverter() } // for sending
@Bean
fun jackson2JsonMessageConverter(): MessageConverter = messageConverter() // for receiving
private fun messageConverter() = Jackson2JsonMessageConverter(jacksonObjectMapper())
}
| 0 | Kotlin | 1 | 9 | 18bc2107f86560fd5a824b3933c8af45ae345d2f | 935 | ws-cloud-native-testing | Apache License 2.0 |
mentor/src/main/kotlin/com/sourceplusplus/mentor/task/GetService.kt | chess-equality | 297,668,044 | false | null | package com.sourceplusplus.mentor.task
import com.sourceplusplus.mentor.MentorJob
import com.sourceplusplus.mentor.MentorTask
import com.sourceplusplus.monitor.skywalking.track.ServiceTracker.Companion.getActiveServices
import com.sourceplusplus.monitor.skywalking.track.ServiceTracker.Companion.getCurrentService
import monitor.skywalking.protocol.metadata.GetAllServicesQuery
import java.util.*
/**
* todo: description.
*
* @since 0.0.1
* @author [<NAME>](mailto:<EMAIL>)
*/
class GetService(
private val byId: String? = null,
private val byName: String? = null,
private val current: Boolean = true
) : MentorTask() {
companion object {
val SERVICE: ContextKey<GetAllServicesQuery.Result> = ContextKey()
}
override suspend fun executeTask(job: MentorJob, context: TaskContext) {
if (current) {
val service = getCurrentService(job.vertx)
if (service != null && isMatch(service)) {
context.put(SERVICE, service)
}
} else {
for (service in getActiveServices(job.vertx)) {
if (isMatch(service)) {
context.put(SERVICE, service)
break
}
}
}
}
private fun isMatch(result: GetAllServicesQuery.Result): Boolean {
return when {
byId != null && byName != null && byId == result.id && byName == result.name -> true
byId != null && byId == result.id -> true
byName != null && byName == result.name -> true
else -> false
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GetService) return false
if (byId != other.byId) return false
if (byName != other.byName) return false
if (current != other.current) return false
return true
}
override fun hashCode(): Int {
return Objects.hash(byId, byName, current)
}
}
| 0 | Kotlin | 0 | 0 | 7c157711d11b4836d38209daf32d4ee3b3d831de | 2,005 | SourceMarker-Alpha | Apache License 2.0 |
spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/client/ClientResponseExtensionsTests.kt | bliblidotcom | 91,250,037 | true | {"Java": 34557826, "Kotlin": 99079, "CSS": 50279, "Groovy": 49020, "HTML": 46333, "AspectJ": 31912, "FreeMarker": 15895, "GAP": 6137, "Shell": 4187, "Batchfile": 4170, "XSLT": 2945, "Ruby": 2106, "JavaScript": 916, "Smarty": 700, "Protocol Buffer": 265, "Python": 254} | package org.springframework.web.reactive.function.client
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Answers
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
/**
* Mock object based tests for [ClientResponse] Kotlin extensions
*
* @author <NAME>
*/
@RunWith(MockitoJUnitRunner::class)
class ClientResponseExtensionsTests {
@Mock(answer = Answers.RETURNS_MOCKS)
lateinit var response: ClientResponse
@Test
fun `bodyToMono with reified type parameters`() {
response.bodyToMono<Foo>()
verify(response, times(1)).bodyToMono(Foo::class.java)
}
@Test
fun `bodyToFlux with reified type parameters`() {
response.bodyToFlux<Foo>()
verify(response, times(1)).bodyToFlux(Foo::class.java)
}
class Foo
}
| 0 | Java | 0 | 2 | 38a12ed4ba54b6929db0f114a5fa439677e441ac | 795 | spring-framework | Apache License 2.0 |
src/main/kotlin/CMapObject.kt | argcc | 777,572,651 | false | {"Kotlin": 665702} | package org.example
open class CMapObject : CTransform() {
var template = ""
var field_0xc0 = 0
var field_0xc4 = 0f
var field_0xc8 = 0
var CObject3DSpecific: CObject3DSpecific? = null
open fun SetSpecific(obj: CBaseObject?) {
if (obj != null
&& obj.instance_type_id == SpecificInstanceTypeId.OBJECT_3D_x46
&& obj is CObject3DSpecific
) {
CObject3DSpecific?.CMapObject = null
CObject3DSpecific = obj
obj.CMapObject = this
}
}
} | 0 | Kotlin | 0 | 0 | 8edd9403e6efd3dd402bd9efdec36c34fe73780f | 540 | ei_reverse_consp | MIT License |
dashkit/src/main/kotlin/io/horizontalsystems/dashkit/models/CoinbaseTransactionSerializer.kt | horizontalsystems | 147,199,533 | false | null | package io.horizontalsystems.dashkit.models
import io.horizontalsystems.bitcoincore.io.BitcoinOutput
import io.horizontalsystems.bitcoincore.serializers.TransactionSerializer
class CoinbaseTransactionSerializer {
fun serialize(coinbaseTransaction: CoinbaseTransaction): ByteArray {
val output = BitcoinOutput()
output.write(TransactionSerializer.serialize(coinbaseTransaction.transaction))
output.writeVarInt(coinbaseTransaction.coinbaseTransactionSize)
output.writeUnsignedShort(coinbaseTransaction.version)
output.writeUnsignedInt(coinbaseTransaction.height)
output.write(coinbaseTransaction.merkleRootMNList)
if (coinbaseTransaction.version >= 2) {
output.write(coinbaseTransaction.merkleRootQuorums)
}
return output.toByteArray()
}
}
| 20 | null | 55 | 96 | 110018d54d82bb4e3c2a1d6b0ddd1bb9eeff9167 | 837 | bitcoin-kit-android | MIT License |
src/main/kotlin/com/wimank/craft_master_server/db/entity/DbVersionEntity.kt | WiMank | 210,549,361 | false | null | package com.wimank.craft_master_server.db.entity
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "db_vers")
data class DbVersionEntity(
@Id
@Column(name = "db_version")
val dbVersion: Int
)
| 0 | Kotlin | 0 | 0 | a0e8e87a8dceafba42ce25a80d981dc5302b1325 | 315 | Craft-Master-Server | MIT License |
bubbles/src/main/kotlin/studio/lunabee/onesafe/bubbles/ui/contact/form/frominvitation/CreateContactFromInvitationDestination.kt | LunabeeStudio | 624,544,471 | false | null | /*
* Copyright (c) 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 - 7/17/2023 - for the oneSafe6 SDK.
* Last modified 17/07/2023 10:31
*/
package studio.lunabee.onesafe.bubbles.ui.contact.form.frominvitation
import android.net.Uri
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import studio.lunabee.onesafe.commonui.OSDestination
object CreateContactFromInvitationDestination : OSDestination {
const val MessageString: String = "messageString"
override val route: String = "create_contact_from_invitation/{$MessageString}/"
fun getRoute(
messageString: String,
): String = route.replace("{$MessageString}", Uri.encode(messageString))
}
context(CreateContactFromInvitationNavScope)
fun NavGraphBuilder.createContactFromInvitationScreen() {
composable(
route = CreateContactFromInvitationDestination.route,
) {
CreateContactFromInvitationRoute()
}
}
| 0 | null | 1 | 2 | a34f0ddaf9dc649c2f2082dc2526921bb1a491df | 1,520 | oneSafe6_SDK_Android | Apache License 2.0 |
api/src/main/java/com/stocksexchange/api/exceptions/rest/InboxException.kt | nscoincommunity | 277,168,471 | true | {"Kotlin": 2814235} | package com.stocksexchange.api.exceptions.rest
import com.stocksexchange.api.exceptions.ApiException
class InboxException(
val error: Error,
message: String = "",
cause: Throwable? = null
) : ApiException(message, cause) {
companion object {
fun invalidToken(message: String): InboxException {
return InboxException(
error = Error.INVALID_TOKEN,
message = message
)
}
fun unknown(message: String): InboxException {
return InboxException(
error = Error.UNKNOWN,
message = message
)
}
}
enum class Error {
INVALID_TOKEN,
UNKNOWN
}
} | 0 | null | 0 | 0 | 52766afab4f96506a2d9ed34bf3564b6de7af8c3 | 732 | Android-app | MIT License |
app/src/main/java/com/kshitijpatil/tazabazar/domain/SearchProductsUseCase.kt | Kshitij09 | 395,308,440 | false | null | package com.kshitijpatil.tazabazar.domain
import com.kshitijpatil.tazabazar.data.ProductRepository
import com.kshitijpatil.tazabazar.model.Product
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class SearchProductsUseCase(
ioDispatcher: CoroutineDispatcher,
private val productRepository: ProductRepository
) : FlowUseCase<SearchProductsUseCase.Params, MediatorResult<List<Product>>>(
ioDispatcher,
conflateParams = false
) {
data class Params(
val query: String? = null,
val category: String? = null,
val forceRefresh: Boolean = false
)
override fun createObservable(params: Params): Flow<MediatorResult<List<Product>>> {
return flow {
emit(MediatorResult.Loading(ResponseOrigin.LOCAL))
val localProducts = productRepository.getProductListBy(params.category, params.query)
emit(MediatorResult.Success(localProducts, ResponseOrigin.LOCAL))
// refresh if asked for or couldn't find any results
// in the local source
val refresh = params.forceRefresh || localProducts.isEmpty()
if (refresh) {
emit(MediatorResult.Loading(ResponseOrigin.REMOTE))
runCatching {
productRepository.getProductListBy(
category = params.category,
query = params.query,
forceRefresh = refresh
)
}.onSuccess {
emit(MediatorResult.Success(it, ResponseOrigin.REMOTE))
}.onFailure {
emit(MediatorResult.Error(it, ResponseOrigin.REMOTE))
}
}
}
}
} | 8 | Kotlin | 2 | 1 | d709b26d69cf46c3d6123a217190f098b79a6562 | 1,790 | TazaBazar | Apache License 2.0 |
app/src/main/java/com/ahmad/aghazadeh/noteita/model/Note.kt | ahmadaghazadeh | 673,721,504 | false | null | package com.ahmad.aghazadeh.noteita.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.time.Instant
import java.time.LocalDateTime
import java.util.Date
import java.util.UUID
@Entity(tableName = "note_table")
data class Note (
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo(name = "title")
val title: String,
@ColumnInfo(name = "description")
val description: String,
)
| 0 | Kotlin | 1 | 0 | c8349b27484b2f9b4ff1d59200729f6188ba67bf | 473 | Noteita | Apache License 2.0 |
lib/src/commonMain/kotlin/xyz/mcxross/kaptos/serialize/MoveBoolSerializer.kt | mcxross | 702,366,239 | false | {"Kotlin": 434019, "Shell": 5540} | /*
* Copyright 2024 McXross
*
* 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 xyz.mcxross.kaptos.serialize
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import xyz.mcxross.kaptos.model.Bool
object BoolSerializer : KSerializer<Bool> {
override val descriptor = PrimitiveSerialDescriptor("Bool", PrimitiveKind.BOOLEAN)
override fun serialize(encoder: Encoder, value: Bool) {
encoder.encodeBoolean(value.value)
encoder.encodeBoolean(value.value)
}
override fun deserialize(decoder: Decoder): Bool {
return Bool(decoder.decodeBoolean())
}
}
| 2 | Kotlin | 3 | 0 | 3e50e5fa554ee5a9973f2bef2d41f90c9a377ef2 | 1,293 | kaptos | Apache License 2.0 |
app/src/main/java/com/forcetower/uefs/core/storage/repository/SIECOMPRepository.kt | marcelobiao | 184,821,890 | true | {"Kotlin": 1857200, "Java": 257698, "Shell": 376} | /*
* Copyright (c) 2019.
* João Paulo Sena <[email protected]>
*
* This file is part of the UNES Open Source Project.
*
* UNES is licensed under the MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.forcetower.uefs.core.storage.repository
import android.content.Context
import androidx.lifecycle.LiveData
import com.forcetower.uefs.AppExecutors
import com.forcetower.uefs.core.model.siecomp.ServerSession
import com.forcetower.uefs.core.model.siecomp.Speaker
import com.forcetower.uefs.core.model.unes.AccessToken
import com.forcetower.uefs.core.storage.eventdatabase.EventDatabase
import com.forcetower.uefs.core.storage.eventdatabase.accessors.SessionWithData
import com.forcetower.uefs.core.storage.network.UService
import com.forcetower.uefs.core.storage.resource.NetworkBoundResource
import com.forcetower.uefs.service.NotificationCreator
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SIECOMPRepository @Inject constructor(
private val database: EventDatabase,
private val executors: AppExecutors,
private val service: UService,
private val context: Context
) {
fun getSessionsFromDayLocal(day: Int) = database.eventDao().getSessionsFromDay(day)
fun getAllSessions() =
object : NetworkBoundResource<List<SessionWithData>, List<ServerSession>>(executors) {
override fun loadFromDb() = database.eventDao().getAllSessions()
override fun shouldFetch(it: List<SessionWithData>?) = true
override fun createCall() = service.siecompSessions()
override fun saveCallResult(value: List<ServerSession>) {
database.eventDao().insertServerSessions(value)
}
}.asLiveData()
fun getSessionDetails(id: Long): LiveData<SessionWithData> {
return database.eventDao().getSessionWithId(id)
}
fun getSpeaker(speakerId: Long): LiveData<Speaker> {
return database.eventDao().getSpeakerWithId(speakerId)
}
fun markSessionStar(sessionId: Long, star: Boolean) {
executors.diskIO().execute {
database.eventDao().markSessionStar(sessionId, star)
}
}
fun loginToService(username: String, password: String) {
executors.networkIO().execute {
try {
val response = service.login(username, password).execute()
if (response.isSuccessful) {
val token = response.body()!!
Timber.d("Token: $token")
database.accessTokenDao().deleteAll()
database.accessTokenDao().insert(token)
NotificationCreator.showSimpleNotification(context, "Login Concluido", "Você agr tem acesso a funções exclusivas")
} else {
NotificationCreator.showSimpleNotification(context, "Login falhou", "O login retornou com o código ${response.code()}")
Timber.e(response.message())
}
} catch (t: Throwable) {
Timber.e("Exception@${t.message}")
}
}
}
fun sendSpeaker(speaker: Speaker, create: Boolean) {
executors.networkIO().execute {
try {
Timber.d("Speaker $speaker")
val response = if (create) {
service.createSpeaker(speaker).execute()
} else {
service.updateSpeaker(speaker).execute()
}
if (response.isSuccessful) {
NotificationCreator.showSimpleNotification(context, "Operação concluida", "A requisição concluiu com sucesso")
} else {
NotificationCreator.showSimpleNotification(context, "Operação falhou", "A operação falhou com o código ${response.code()}")
Timber.e(response.message())
}
} catch (t: Throwable) {
Timber.e("Connection failed")
}
}
}
fun getAccess(): LiveData<AccessToken?> {
return database.accessTokenDao().getAccess()
}
}
| 0 | Kotlin | 0 | 0 | 8c27cac95ffde6aae6a07156be0aad3d6039767e | 5,207 | Melon | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/FileEps.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.FileEps: ImageVector
get() {
if (_fileEps != null) {
return _fileEps!!
}
_fileEps = Builder(name = "FileEps", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 512.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(148.523f, 124.117f)
curveToRelative(7.364f, 0.0f, 13.333f, -5.97f, 13.333f, -13.333f)
reflectiveCurveToRelative(-5.97f, -13.333f, -13.333f, -13.333f)
horizontalLineToRelative(-46.933f)
curveToRelative(-7.364f, 0.0f, -13.333f, 5.97f, -13.333f, 13.333f)
verticalLineToRelative(111.232f)
curveToRelative(0.0f, 7.364f, 5.97f, 13.333f, 13.333f, 13.333f)
horizontalLineToRelative(46.933f)
curveToRelative(7.364f, 0.0f, 13.333f, -5.97f, 13.333f, -13.333f)
curveToRelative(0.0f, -7.364f, -5.97f, -13.333f, -13.333f, -13.333f)
horizontalLineToRelative(-33.515f)
verticalLineToRelative(-28.949f)
horizontalLineToRelative(30.059f)
curveToRelative(7.364f, 0.0f, 13.333f, -5.97f, 13.333f, -13.333f)
curveToRelative(0.0f, -7.364f, -5.97f, -13.333f, -13.333f, -13.333f)
horizontalLineToRelative(-30.059f)
verticalLineToRelative(-28.949f)
horizontalLineTo(148.523f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(188.821f, 110.272f)
verticalLineToRelative(112.256f)
curveToRelative(0.0f, 7.364f, 5.97f, 13.333f, 13.333f, 13.333f)
curveToRelative(7.364f, 0.0f, 13.333f, -5.97f, 13.333f, -13.333f)
verticalLineToRelative(-35.477f)
horizontalLineToRelative(17.899f)
curveToRelative(24.86f, 0.0f, 45.013f, -20.153f, 45.013f, -45.013f)
reflectiveCurveToRelative(-20.153f, -45.013f, -45.013f, -45.013f)
lineToRelative(-0.021f, -0.085f)
horizontalLineToRelative(-31.232f)
curveToRelative(-0.775f, -0.021f, -6.198f, -0.076f, -10.095f, 4.32f)
curveTo(188.757f, 104.96f, 188.79f, 109.298f, 188.821f, 110.272f)
close()
moveTo(233.365f, 160.299f)
horizontalLineToRelative(-17.749f)
verticalLineTo(123.52f)
horizontalLineToRelative(17.856f)
curveToRelative(10.133f, 0.0f, 18.347f, 8.214f, 18.347f, 18.347f)
curveToRelative(0.0f, 10.133f, -8.214f, 18.347f, -18.347f, 18.347f)
lineTo(233.365f, 160.299f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(405.333f, 0.0f)
horizontalLineTo(106.667f)
curveTo(47.786f, 0.071f, 0.071f, 47.786f, 0.0f, 106.667f)
verticalLineToRelative(298.667f)
curveTo(0.071f, 464.214f, 47.786f, 511.93f, 106.667f, 512.0f)
horizontalLineToRelative(241.984f)
curveToRelative(28.307f, 0.081f, 55.47f, -11.165f, 75.435f, -31.232f)
lineToRelative(56.661f, -56.704f)
curveToRelative(20.069f, -19.956f, 31.323f, -47.111f, 31.253f, -75.413f)
verticalLineTo(106.667f)
curveTo(511.93f, 47.786f, 464.214f, 0.071f, 405.333f, 0.0f)
close()
moveTo(42.667f, 405.333f)
verticalLineTo(106.667f)
curveToRelative(0.0f, -35.346f, 28.654f, -64.0f, 64.0f, -64.0f)
horizontalLineToRelative(298.667f)
curveToRelative(35.346f, 0.0f, 64.0f, 28.654f, 64.0f, 64.0f)
verticalLineTo(320.0f)
horizontalLineTo(384.0f)
curveToRelative(-35.346f, 0.0f, -64.0f, 28.654f, -64.0f, 64.0f)
verticalLineToRelative(85.333f)
horizontalLineTo(106.667f)
curveTo(71.32f, 469.333f, 42.667f, 440.68f, 42.667f, 405.333f)
close()
moveTo(393.92f, 450.603f)
curveToRelative(-8.576f, 8.555f, -19.42f, 14.477f, -31.253f, 17.067f)
verticalLineTo(384.0f)
curveToRelative(0.0f, -11.782f, 9.551f, -21.333f, 21.333f, -21.333f)
horizontalLineToRelative(83.733f)
curveToRelative(-2.639f, 11.808f, -8.554f, 22.633f, -17.067f, 31.232f)
lineTo(393.92f, 450.603f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(359.616f, 154.773f)
curveToRelative(-5.824f, -1.984f, -11.861f, -3.072f, -17.813f, -4.629f)
curveToRelative(-4.723f, -0.953f, -9.101f, -3.164f, -12.672f, -6.4f)
curveToRelative(-3.566f, -3.382f, -4.833f, -8.533f, -3.243f, -13.184f)
curveToRelative(2.023f, -4.008f, 5.998f, -6.663f, 10.475f, -6.997f)
curveToRelative(4.401f, -0.274f, 8.812f, 0.373f, 12.949f, 1.899f)
curveToRelative(5.948f, 1.854f, 11.782f, 4.055f, 17.472f, 6.592f)
curveToRelative(6.293f, 2.752f, 13.675f, 4.395f, 18.752f, -1.579f)
curveToRelative(3.73f, -4.494f, 4.009f, -10.922f, 0.683f, -15.723f)
curveToRelative(-2.212f, -3.213f, -5.198f, -5.818f, -8.683f, -7.573f)
curveToRelative(-15.617f, -9.169f, -34.252f, -11.712f, -51.755f, -7.061f)
curveToRelative(-9.245f, 2.926f, -17.056f, 9.214f, -21.888f, 17.621f)
curveToRelative(-2.266f, 3.988f, -3.764f, 8.366f, -4.416f, 12.907f)
curveToRelative(-1.19f, 8.167f, 0.581f, 16.491f, 4.992f, 23.467f)
curveToRelative(4.978f, 7.288f, 12.164f, 12.784f, 20.501f, 15.68f)
curveToRelative(8.725f, 3.584f, 17.429f, 7.061f, 26.283f, 10.304f)
curveToRelative(3.812f, 1.199f, 7.319f, 3.207f, 10.283f, 5.888f)
curveToRelative(3.342f, 3.166f, 4.584f, 7.962f, 3.2f, 12.352f)
curveToRelative(-1.799f, 4.203f, -5.37f, 7.391f, -9.749f, 8.704f)
curveToRelative(-6.66f, 2.504f, -13.956f, 2.766f, -20.779f, 0.747f)
curveToRelative(-6.64f, -2.403f, -12.774f, -6.02f, -18.091f, -10.667f)
curveToRelative(-0.555f, -0.448f, -2.368f, -1.813f, -2.709f, -2.133f)
curveToRelative(-4.971f, -3.554f, -11.762f, -3.099f, -16.213f, 1.088f)
curveToRelative(-5.455f, 4.947f, -5.867f, 13.379f, -0.921f, 18.834f)
curveToRelative(0.001f, 0.001f, 0.002f, 0.002f, 0.003f, 0.004f)
curveToRelative(12.728f, 13.515f, 30.503f, 21.127f, 49.067f, 21.013f)
curveToRelative(22.001f, 0.967f, 41.551f, -13.924f, 46.464f, -35.392f)
curveToRelative(2.071f, -12.991f, -2.781f, -26.121f, -12.8f, -34.645f)
curveTo(373.343f, 160.936f, 366.752f, 157.158f, 359.616f, 154.773f)
close()
}
}
.build()
return _fileEps!!
}
private var _fileEps: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 8,706 | icons | MIT License |
bot/connector-messenger/src/main/kotlin/model/send/CallButton.kt | theopenconversationkit | 84,538,053 | false | null | /*
* Copyright (C) 2017/2020 e-voyageurs technologies
*
* 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 ai.tock.bot.connector.messenger.model.send
import ai.tock.bot.engine.action.SendChoice
import ai.tock.bot.engine.message.Choice
data class CallButton(
val title: String,
val payload: String
) : Button(ButtonType.phone_number) {
override fun toChoice(): Choice {
return Choice(
SendChoice.PHONE_CALL_INTENT,
mapOf(
SendChoice.TITLE_PARAMETER to title,
SendChoice.PHONE_CALL_INTENT to payload
)
)
}
} | 163 | null | 127 | 475 | 890f69960997ae9146747d082d808d92ee407fcb | 1,123 | tock | Apache License 2.0 |
app/src/main/java/com/example/myapplicationnew/curdrice.kt | Krishnan14 | 496,488,504 | false | null | package com.example.myapplicationnew
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
class curdrice : AppCompatActivity() {
lateinit var editName:EditText
lateinit var editButton:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_curdrice)
editName=findViewById(R.id.username)
editButton=findViewById(R.id.login)
editButton.setOnClickListener {
val sharedPref:SharedPreferences=getSharedPreferences("Name", MODE_PRIVATE)
val sharedEdit:SharedPreferences.Editor=sharedPref.edit()
sharedEdit.putString("Rollno",editName.text.toString())
sharedEdit.apply()
val secondIntent=Intent(this,lemonrice::class.java)
startActivity(secondIntent)
}
}
} | 0 | Kotlin | 0 | 0 | d7f6632690c389f24d727d207056ba7eeb9d6120 | 1,010 | LearningAndriod | MIT License |
commons/src/main/java/com/unatxe/commons/data/exceptions/NoDataException.kt | BaturaMobile | 383,122,377 | false | {"Gradle Kotlin DSL": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "Kotlin": 73, "XML": 32, "GraphQL": 1, "JSON": 1, "INI": 3, "Java": 3, "Gradle": 2} | package com.unatxe.commons.data.exceptions
class NoDataException : Throwable()
| 1 | null | 1 | 1 | 07c8a7920277a10c6177c3b1a1c61d6d96793713 | 80 | android-basics | Apache License 2.0 |
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/identity/IdentityTaskHelper.kt | aalzehla | 287,565,471 | 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.session.identity
import im.vector.matrix.android.api.session.identity.IdentityServiceError
import im.vector.matrix.android.internal.network.executeRequest
import im.vector.matrix.android.internal.session.identity.model.IdentityAccountResponse
internal suspend fun getIdentityApiAndEnsureTerms(identityApiProvider: IdentityApiProvider, userId: String): IdentityAPI {
val identityAPI = identityApiProvider.identityApi ?: throw IdentityServiceError.NoIdentityServerConfigured
// Always check that we have access to the service (regarding terms)
val identityAccountResponse = executeRequest<IdentityAccountResponse>(null) {
apiCall = identityAPI.getAccount()
}
assert(userId == identityAccountResponse.userId)
return identityAPI
}
| 1 | null | 1 | 1 | ee1d5faf0d59f9cc1c058d45fae3e811d97740fd | 1,409 | element-android | Apache License 2.0 |
src/main/kotlin/jp/nephy/vrchakt/core/VRChaKtRequest.kt | StarryBlueSky | 141,704,292 | false | {"Kotlin": 66578} | @file:Suppress("UNUSED")
package jp.nephy.vrchakt.core
import jp.nephy.vrchakt.models.Empty
import jp.nephy.vrchakt.models.VRChaKtModel
class VRChaKtRequest(val session: Session, val builder: VRChaKtRequestBuilder) {
inline fun <reified M: VRChaKtModel> jsonObject(): VRChaKtJsonObjectAction<M> {
return VRChaKtJsonObjectAction(this, M::class)
}
fun empty(): VRChaKtJsonObjectAction<Empty> {
return VRChaKtJsonObjectAction(this, Empty::class)
}
inline fun <reified M: VRChaKtModel> jsonArray(): VRChaKtJsonArrayAction<M> {
return VRChaKtJsonArrayAction(this, M::class)
}
fun text(): VRChaKtTextAction {
return VRChaKtTextAction(this)
}
}
| 0 | Kotlin | 0 | 2 | 1a4b512367e7000268b13a4636f69ca7d5ef233b | 708 | VRChaKt | MIT License |
randomgenkt/src/test/java/com/mitteloupe/randomgenkt/fielddataprovider/IntFieldDataProviderTest.kt | EranBoudjnah | 154,015,466 | false | null | package com.mitteloupe.randomgenkt.fielddataprovider
import com.nhaarman.mockitokotlin2.given
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import java.util.Random
/**
* Created by Eran Boudjnah on 10/08/2018.
*/
@RunWith(MockitoJUnitRunner::class)
class IntFieldDataProviderTest {
private lateinit var cut: IntFieldDataProvider<Any>
@Mock
private lateinit var random: Random
@Test
fun givenRandomDoubleValueWhenGenerateThenReturnsIntegerValue() {
// Given
cut = IntFieldDataProvider(random)
given(random.nextDouble()).willReturn(0.0)
// When
var result = cut.invoke()
// Then
assertEquals(Int.MIN_VALUE, result)
// Given
given(random.nextDouble()).willReturn(0.99999999999)
// When
result = cut.invoke()
// Then
assertEquals(Int.MAX_VALUE, result)
}
@Test
fun givenRandomFloatValueAndRangeWhenGenerateThenReturnsCorrectValue() {
// Given
cut = IntFieldDataProvider(random, 0, 100)
given(random.nextDouble()).willReturn(0.0)
// When
var result = cut.invoke()
// Then
assertEquals(0, result)
// Given
given(random.nextDouble()).willReturn(0.99999999999)
// When
result = cut.invoke()
// Then
assertEquals(100, result)
}
} | 0 | Kotlin | 0 | 28 | c5db0d07a3dda1b9215f767acde7f51d7c958070 | 1,494 | RandomGenKt | MIT License |
app/src/main/java/com/corphish/quicktools/ui/theme/Color.kt | corphish | 680,429,782 | false | {"Kotlin": 159426} | package com.corphish.quicktools.ui.theme
import androidx.compose.ui.graphics.Color
val BlueForeground = Color(0xFF0099FF)
val BlueBackground = Color(0xFFCCEBFF) | 8 | Kotlin | 2 | 72 | e1edb5683b5ed60b040f5cff30fa281d45134899 | 162 | TextTools | Apache License 2.0 |
src/main/kotlin/org/cdb/labwitch/models/Box.kt | CodeDrillBrigade | 714,769,385 | false | {"Kotlin": 69741} | package org.cdb.labwitch.models
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.cdb.labwitch.models.embed.BoxUnit
import org.cdb.labwitch.models.embed.UsageLog
import org.cdb.labwitch.models.identifiers.EntityId
import org.cdb.labwitch.models.identifiers.HierarchicalId
import org.cdb.labwitch.serialization.DateSerializer
import java.util.Date
import java.util.SortedSet
@Serializable
data class Box(
@SerialName("_id") override val id: EntityId = EntityId.generate(),
val material: EntityId,
val quantity: BoxUnit,
val position: HierarchicalId,
@Serializable(with = DateSerializer::class) val expirationDate: Date? = null,
val description: String? = null,
val usageLog: SortedSet<UsageLog> = sortedSetOf(),
) : StoredEntity
| 2 | Kotlin | 0 | 0 | f1a741379d6648eb623dffcbacb77ed40cb0cce5 | 780 | LabWitchery-backend | MIT License |
xframe/src/main/java/com/yinhao/commonmodule/base/repository/dao/BaseDao.kt | sdwfhjq123 | 276,372,979 | false | {"Kotlin": 226215, "Java": 54873} | package com.yinhao.commonmodule.base.repository.dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Update
/**
* author: SHIGUANG
* date: 2019/4/18
* version: v1.0
* ### description: 基础Dao,提供 insert update delete 的基本方法
*/
interface BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrReplace(vararg beans: T)
@Update
fun update(vararg beans: T): Int
@Delete
fun delete(vararg beans: T): Int
}
| 0 | Kotlin | 0 | 0 | a16806ea0fef94416bd899f776f04596bf317148 | 522 | wanandroid | Apache License 2.0 |
src/main/kotlin/com/tractive/mongobee/MongobeeSpring.kt | Tractive | 158,389,070 | false | null | package com.tractive.mongobee
import com.github.mongobee.dao.ChangeEntryDao
import com.github.mongobee.exception.MongobeeChangeSetException
import com.github.mongobee.exception.MongobeeConfigurationException
import com.github.mongobee.exception.MongobeeConnectionException
import com.github.mongobee.exception.MongobeeException
import com.github.mongobee.utils.ChangeService
import com.mongodb.MongoClient
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.InitializingBean
import org.springframework.boot.autoconfigure.mongo.MongoProperties
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.core.env.Environment
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
class MongobeeSpring(private val environment: Environment,
val mongoClient: MongoClient,
private val dao: ChangeEntryDao,
private val mongbeeProperties: MongobeeProperties,
mongoProperties: MongoProperties) : ApplicationContextAware, InitializingBean {
companion object {
private val LOGGER = LoggerFactory.getLogger(MongobeeSpring::class.java)
}
private val database = mongbeeProperties.database ?: mongoProperties.database
private lateinit var applicationContext: ApplicationContext
override fun setApplicationContext(applicationContext: ApplicationContext) {
this.applicationContext = applicationContext
}
override fun afterPropertiesSet() = execute()
@Throws(MongobeeException::class)
fun execute() {
validateConfig()
dao.connectMongoDb(this.mongoClient, database)
if (!dao.acquireProcessLock()) {
LOGGER.error("Mongobee did not acquire process lock. Exiting.")
return
}
LOGGER.info("Mongobee acquired process lock, starting the data migration sequence..")
try {
executeMigration()
} finally {
LOGGER.info("Mongobee is releasing process lock.")
dao.releaseProcessLock()
}
LOGGER.info("Mongobee has finished his job.")
}
@Throws(MongobeeConnectionException::class, MongobeeException::class)
private fun executeMigration() {
val service = ChangeService(mongbeeProperties.changeLogsScanPackage, environment)
val changelogs = service.fetchChangeLogs()
if (changelogs.isEmpty()) {
LOGGER.info("No change logs found in scan package ${mongbeeProperties.changeLogsScanPackage}")
return
}
for (changelogClass in changelogs) {
try {
val changelogInstance = changelogClass.getConstructor().newInstance()
val changesetMethods = service.fetchChangeSets(changelogInstance!!.javaClass)
for (changesetMethod in changesetMethods) {
val changeEntry = service.createChangeEntry(changesetMethod)
try {
when {
dao.isNewChange(changeEntry) -> {
executeChangeSetMethod(changesetMethod, changelogInstance)
dao.save(changeEntry)
LOGGER.info("$changeEntry applied")
}
service.isRunAlwaysChangeSet(changesetMethod) -> {
executeChangeSetMethod(changesetMethod, changelogInstance)
LOGGER.info("$changeEntry reapplied")
}
else -> LOGGER.info("$changeEntry passed over")
}
} catch (e: MongobeeChangeSetException) {
LOGGER.error("Failed to execute changeset ${changeEntry.changeId}: ${e.message}", e)
throw e
}
}
} catch (e: NoSuchMethodException) {
throw MongobeeException("Failed to execute changelog: ${e.message}", e)
} catch (e: IllegalAccessException) {
throw MongobeeException("Failed to execute changelog: ${e.message}", e)
} catch (e: InvocationTargetException) {
val targetException = e.targetException
throw MongobeeException("Failed to execute changelog: ${targetException.message}", e)
} catch (e: InstantiationException) {
throw MongobeeException("Failed to execute changelog: ${e.message}", e)
}
}
}
@Throws(IllegalAccessException::class, InvocationTargetException::class, MongobeeChangeSetException::class)
private fun executeChangeSetMethod(changeSetMethod: Method, changeLogInstance: Any) {
try {
return changeSetMethod.parameterTypes
.map {
applicationContext.getBean(it)
}
.run {
changeSetMethod.invoke(changeLogInstance, *this.toTypedArray())
}
} catch (e: Throwable) {
LOGGER.error("Exception during change set execution: ${e.message}", e)
throw MongobeeChangeSetException("Exception during change set execution")
}
}
@Throws(MongobeeConfigurationException::class)
private fun validateConfig() {
if (database.isNullOrEmpty()) {
throw MongobeeConfigurationException("Database is not set, please specify mongobee.database or spring.data.mongodb.database property")
}
}
}
| 1 | Kotlin | 0 | 1 | f5bec91cf1bbdbc039b5a769b96d3e3422c35cdc | 5,654 | mongobee-spring | Apache License 2.0 |
lua_processor/src/main/java/io/github/lee/lua/processor/MyClass.kt | 291700351 | 669,441,086 | false | null | package io.github.lee.lua.processor
class MyClass {
} | 0 | Kotlin | 0 | 0 | 45c3c581e2818579d4dca36897a76997f785afc8 | 54 | AndroidLua | MIT License |
composeApp/src/commonMain/kotlin/com/emenike/randompassword/screens/randompassword/RandomPasswordScreen.kt | duongkhaineverdie | 787,186,006 | false | {"Kotlin": 69072, "Swift": 709} | package com.emenike.randompassword.screens.randompassword
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cafe.adriel.voyager.koin.getScreenModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.emenike.randompassword.screens.component.DialogOk
import com.emenike.randompassword.screens.tab.HomeTab
import io.github.alexzhirkevich.cupertino.AlertActionStyle
import io.github.alexzhirkevich.cupertino.CupertinoBorderedTextField
import io.github.alexzhirkevich.cupertino.CupertinoButtonDefaults
import io.github.alexzhirkevich.cupertino.CupertinoIcon
import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveAlertDialogNative
import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveButton
import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveScaffold
import io.github.alexzhirkevich.cupertino.adaptive.AdaptiveSwitch
import io.github.alexzhirkevich.cupertino.adaptive.ExperimentalAdaptiveApi
import kmp_random_password.composeapp.generated.resources.Res
import kmp_random_password.composeapp.generated.resources.copied
import kmp_random_password.composeapp.generated.resources.generate_password_title_button
import kmp_random_password.composeapp.generated.resources.home_screen_message_dialog_delete
import kmp_random_password.composeapp.generated.resources.home_screen_ok_dialog
import kmp_random_password.composeapp.generated.resources.img_copy
import kmp_random_password.composeapp.generated.resources.img_download
import kmp_random_password.composeapp.generated.resources.input_error_message
import kmp_random_password.composeapp.generated.resources.lower_text_label
import kmp_random_password.composeapp.generated.resources.number_label
import kmp_random_password.composeapp.generated.resources.password_length
import kmp_random_password.composeapp.generated.resources.saved
import kmp_random_password.composeapp.generated.resources.saved_title_dialog_delete
import kmp_random_password.composeapp.generated.resources.special_char
import kmp_random_password.composeapp.generated.resources.upper_text_label
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.getString
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
data object RandomPasswordScreen : HomeTab {
@OptIn(ExperimentalResourceApi::class, ExperimentalAdaptiveApi::class)
@Composable
override fun Content() {
val navigator = LocalNavigator.currentOrThrow
val homeViewModel: RandomPasswordViewModel = getScreenModel()
val uiState by homeViewModel.uiState.collectAsState()
val clipboardManager = LocalClipboardManager.current
val scope = rememberCoroutineScope()
val snackBarHostState = remember { SnackbarHostState() }
AdaptiveScaffold(
snackbarHost = {
SnackbarHost(hostState = snackBarHostState)
}
) {
HomeScreen(
modifier = Modifier.fillMaxSize(),
onValueLengthChange = homeViewModel::onValueChangeLength,
onClickGeneratePassword = homeViewModel::generatePassword,
actionIncludeDigits = homeViewModel::actionIncludeDigits,
actionIncludeUppercase = homeViewModel::actionIncludeUppercase,
actionIncludeLowercase = homeViewModel::actionIncludeLowercase,
actionIncludeSpecialChars = homeViewModel::actionIncludeSpecialChars,
includeLowercase = uiState.includeLowercase,
includeUppercase = uiState.includeUppercase,
includeDigits = uiState.includeDigits,
includeSpecialChars = uiState.includeSpecialChars,
lengthPassword = uiState.passwordLength?.toString() ?: "",
isErrorField = uiState.isErrorInput,
generatedPassword = uiState.passwordGenerated,
onClickCopy = {
clipboardManager.setText(AnnotatedString(it))
scope.launch {
snackBarHostState.showSnackbar(getString(Res.string.copied))
}
},
onClickSavePassword = homeViewModel::savePassword,
onDismissDialogAtLeast = homeViewModel::onDismissDialogAtLeast,
onDismissSavedDialog = homeViewModel::onDismissSavedDialog,
showDialogAtLeast = uiState.showDialogNotificationAtLeast,
isSaved = uiState.isSavedPassword,
isShowSaved = uiState.isShowSavedDialog,
layoutVersion = uiState.layoutVersion,
)
}
}
}
@OptIn(
ExperimentalResourceApi::class,
ExperimentalAdaptiveApi::class
)
@Composable
fun HomeScreen(
modifier: Modifier = Modifier,
lengthPassword: String = "",
onClickGeneratePassword: () -> Unit,
onValueLengthChange: (String) -> Unit,
actionIncludeLowercase: (Boolean) -> Unit,
actionIncludeUppercase: (Boolean) -> Unit,
actionIncludeDigits: (Boolean) -> Unit,
actionIncludeSpecialChars: (Boolean) -> Unit,
includeLowercase: Boolean = true,
includeUppercase: Boolean = true,
includeDigits: Boolean = true,
includeSpecialChars: Boolean = true,
isErrorField: Boolean = true,
generatedPassword: String = "",
onClickSavePassword: (String) -> Unit,
onClickCopy: (String) -> Unit,
onDismissDialogAtLeast: () -> Unit,
onDismissSavedDialog: () -> Unit,
showDialogAtLeast: Boolean = false,
isSaved: Boolean = false,
isShowSaved: Boolean = false,
layoutVersion: String?,
) {
val localFocusManager = LocalFocusManager.current
val titleActionDialogAtLeast = stringResource(Res.string.home_screen_ok_dialog).uppercase()
Column(
modifier = modifier
.systemBarsPadding()
.pointerInput(Unit) {
detectTapGestures(onTap = {
localFocusManager.clearFocus()
})
},
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 30.dp)
) {
Column {
CupertinoBorderedTextField(
modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
value = lengthPassword,
onValueChange = onValueLengthChange,
placeholder = {
Box(
modifier = Modifier.fillMaxHeight(),
contentAlignment = Alignment.Center
) {
Text(
text = stringResource(Res.string.password_length),
fontSize = 16.sp,
color = Color.Gray.copy(0.8f)
)
}
},
isError = isErrorField,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
)
if (isErrorField) {
Text(
text = stringResource(Res.string.input_error_message),
color = MaterialTheme.colors.error,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(start = 16.dp)
)
}
}
}
Column(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 30.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(Res.string.lower_text_label),
style = MaterialTheme.typography.h6
)
AdaptiveSwitch(
checked = includeLowercase,
onCheckedChange = actionIncludeLowercase,
)
}
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(Res.string.upper_text_label),
style = MaterialTheme.typography.h6
)
AdaptiveSwitch(
checked = includeUppercase,
onCheckedChange = actionIncludeUppercase,
)
}
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(Res.string.number_label),
style = MaterialTheme.typography.h6
)
AdaptiveSwitch(
checked = includeDigits,
onCheckedChange = actionIncludeDigits,
)
}
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(Res.string.special_char),
style = MaterialTheme.typography.h6
)
AdaptiveSwitch(
checked = includeSpecialChars,
onCheckedChange = actionIncludeSpecialChars,
)
}
}
AdaptiveButton(onClick = onClickGeneratePassword) {
Icon(
Icons.Filled.Check,
contentDescription = stringResource(Res.string.generate_password_title_button)
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = stringResource(Res.string.generate_password_title_button))
}
AnimatedVisibility(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp)
.weight(1f),
visible = generatedPassword.isNotBlank()
) {
AdaptiveButton(
modifier = Modifier,
onClick = {
onClickCopy(generatedPassword)
},
adaptation = {
this.cupertino {
this.shape = RoundedCornerShape(20.dp)
this.colors = CupertinoButtonDefaults.plainButtonColors(
containerColor = Color.LightGray.copy(0.2f)
)
}
}
) {
// Display the generated password (consider security implications)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier
.padding(horizontal = 10.dp, vertical = 5.dp),
text = generatedPassword,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
fontSize = 48.sp
)
}
}
}
if (generatedPassword.isNotBlank()) {
Row(
modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)
.padding(bottom = 20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
AdaptiveButton(
modifier = Modifier
.fillMaxHeight(),
onClick = {
onClickSavePassword(generatedPassword)
},
enabled = !isSaved
) {
CupertinoIcon(
painter = painterResource(Res.drawable.img_download),
contentDescription = null,
modifier = Modifier.size(24.dp)
)
}
if (layoutVersion == "v1"){
AdaptiveButton(
modifier = Modifier
.fillMaxHeight(),
onClick = { onClickCopy(generatedPassword) }) {
CupertinoIcon(
painter = painterResource(Res.drawable.img_copy),
contentDescription = null,
modifier = Modifier.size(24.dp)
)
}
}
}
}
}
if (showDialogAtLeast) {
AdaptiveAlertDialogNative(
onDismissRequest = onDismissDialogAtLeast,
title = stringResource(Res.string.saved_title_dialog_delete),
message = stringResource(Res.string.home_screen_message_dialog_delete),
buttons = {
action(
onClick = onDismissDialogAtLeast,
title = titleActionDialogAtLeast,
style = AlertActionStyle.Cancel
)
}
)
}
DialogOk(
title = stringResource(Res.string.saved),
isShow = isShowSaved,
onDismissRequest = onDismissSavedDialog
)
} | 0 | Kotlin | 0 | 0 | ea80b96faff9b207bf1f1679b29d1123fbf09cf9 | 16,134 | KMPRandomPassword | Apache License 2.0 |
jdk_17_maven/cs/rest/familie-tilbake/src/main/kotlin/no/nav/familie/tilbake/datavarehus/saksstatistikk/vedtak/Vedtaksoppsummering.kt | WebFuzzing | 94,008,854 | false | null | package no.nav.familie.tilbake.datavarehus.saksstatistikk.vedtak
import jakarta.validation.constraints.Size
import no.nav.familie.kontrakter.felles.tilbakekreving.Ytelsestype
import no.nav.familie.tilbake.behandling.domain.Behandlingstype
import java.time.OffsetDateTime
import java.util.UUID
class Vedtaksoppsummering(
@Size(min = 1, max = 20)
val saksnummer: String,
val ytelsestype: Ytelsestype,
val behandlingUuid: UUID,
val behandlingstype: Behandlingstype,
val erBehandlingManueltOpprettet: Boolean = false,
val behandlingOpprettetTidspunkt: OffsetDateTime,
val vedtakFattetTidspunkt: OffsetDateTime,
val referertFagsaksbehandling: String,
val forrigeBehandling: UUID? = null,
val ansvarligSaksbehandler: String,
val ansvarligBeslutter: String,
val behandlendeEnhet: String,
@Size(min = 1, max = 100)
val perioder: List<VedtakPeriode>
)
| 4 | null | 16 | 26 | 1777aafb22c6fc7c1bc7db96c86b6ea70e38a36e | 905 | EMB | Apache License 2.0 |
app/src/main/java/com/combros/vendingmachine/features/home/presentation/composables/WithdrawMoneyDialogComposable.kt | leduytuanvu | 793,457,019 | false | {"Kotlin": 1036982, "C++": 19531, "Makefile": 277, "CMake": 229} | package com.combros.vendingmachine.features.home.presentation.composables
import android.provider.CalendarContract.Colors
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.combros.vendingmachine.R
@Composable
fun WithdrawMoneyDialogComposable(isReturning: Boolean) {
val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp
val screenHeight = configuration.screenHeightDp.dp
if (isReturning) {
Dialog(
onDismissRequest = { /*TODO*/ },
properties = DialogProperties(dismissOnClickOutside = false)
) {
Box(modifier = Modifier
.height(screenHeight*0.5f)
.width(screenHeight*0.42f)
.background(Color.White),
) {
Column(
modifier = Modifier,
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Spacer(modifier = Modifier.height(screenHeight*0.08f))
Image(
modifier = Modifier
.height(screenHeight*0.28f)
.width(screenHeight*0.28f),
alignment = Alignment.Center,
painter = painterResource(id = R.drawable.image_put_money),
contentDescription = ""
)
Spacer(modifier = Modifier.height(screenHeight*0.054f).width(screenHeight*0.5f))
Text(text = "Vui lòng nhận tiền ở hộp thối", fontSize = 20.sp)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 00d5bc50ea03526cbf75487e0662f6cc6160b3ed | 2,606 | vendingmachine | MIT License |
src/main/kotlin/org/usfirst/frc/team4099/robot/subsystems/Wrist.kt | team4099 | 116,313,798 | false | null | package org.usfirst.frc.team4099.robot.subsystems
import com.ctre.phoenix.motorcontrol.ControlMode
import com.ctre.phoenix.motorcontrol.FeedbackDevice
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard
import org.usfirst.frc.team4099.lib.util.CANMotorControllerFactory
import org.usfirst.frc.team4099.lib.util.conversions.WristConversion
import org.usfirst.frc.team4099.robot.Constants
import org.usfirst.frc.team4099.robot.loops.Loop
/**
* @author Team 4099
*
* This class is the constructor for the Wrist subsystem
*
* @constructor Creates the Wrist subsystem
*
*/
class Wrist private constructor(): Subsystem {
private val talon = CANMotorControllerFactory.createDefaultTalon(Constants.Wrist.WRIST_TALON_ID)
// private val arm = Arm.instance
var wristState = WristState.HORIZONTAL
private var wristPower = 0.0
private var wristAngle = 0.0
// private var outOfBounds: Boolean = true
// get() = talon.motorOutputPercent > 0 && talon.sensorCollection.quadraturePosition < 0 ||
// talon.motorOutputPercent < 0 && talon.sensorCollection.quadraturePosition > 1600
private var tooHigh = false
private var tooLow = false
enum class WristState(val targetAngle: Double) {
HORIZONTAL(0.0),
STOWED_UP(Math.PI / 2),
SHOOT_UP(Math.PI / 4),
OPEN_LOOP(Double.NaN),
VELOCITY_CONTROL(Double.NaN)
//TODO Calibrate values
}
init {
talon.set(ControlMode.PercentOutput, 0.0)
talon.inverted = true
talon.setSensorPhase(true)
talon.configSelectedFeedbackSensor(FeedbackDevice.CTRE_MagEncoder_Relative, 0, 0)
talon.configNominalOutputForward(0.0, 0)
talon.configNominalOutputReverse(0.0, 0)
talon.configPeakOutputReverse(-1.0, 0)
talon.configPeakOutputForward(1.0, 0)
talon.config_kP(0, Constants.Wrist.WRIST_UP_KP, 0)
talon.config_kI(0, Constants.Wrist.WRIST_UP_KI, 0)
talon.config_kD(0, Constants.Wrist.WRIST_UP_KD, 0)
talon.config_kF(0, Constants.Wrist.WRIST_UP_KF, 0)
talon.config_kP(1, Constants.Wrist.WRIST_DOWN_KP, 0)
talon.config_kI(1, Constants.Wrist.WRIST_DOWN_KI, 0)
talon.config_kD(1, Constants.Wrist.WRIST_DOWN_KD, 0)
talon.config_kF(1, Constants.Wrist.WRIST_DOWN_KF, 0)
talon.configMotionCruiseVelocity(0, 0)
talon.configMotionAcceleration(0, 0)
talon.configForwardSoftLimitEnable(false, 0)
talon.configForwardSoftLimitThreshold(100, 0)
talon.configReverseSoftLimitEnable(false, 0)
talon.configReverseSoftLimitThreshold(0, 0)
talon.overrideSoftLimitsEnable(false)
talon.overrideLimitSwitchesEnable(true)
}
/**
* Outputs the angle of the wrist
*/
override fun outputToSmartDashboard() {
SmartDashboard.putNumber("wrist/wristAngle", wristAngle)
SmartDashboard.putBoolean("wrist/wristUp", wristAngle > Math.PI / 4)
SmartDashboard.putNumber("wrist/wristSpeed", talon.sensorCollection.quadratureVelocity.toDouble())
}
@Synchronized override fun stop() {
// setWristMode(WristState.HORIZONTAL)
}
/**
* Sets the state of the Arm
*
* @param state is the wrist state
*/
fun setWristMode(state: WristState) {
wristState = state
}
fun getWristPosition() : Double {
return WristConversion.pulsesToRadians(talon.sensorCollection.quadraturePosition.toDouble())
}
fun setOpenLoop(power: Double) {
wristState = WristState.OPEN_LOOP
wristPower = power
talon.set(ControlMode.PercentOutput, wristPower)
// println("wrist speed: ${talon.sensorCollection.quadratureVelocity}")
}
fun setWristVelocity(radiansPerSecond: Double) {
// if ((radiansPerSecond <= 0 || Utils.around(radiansPerSecond, 0.0, .1)) && talon.sensorCollection.quadraturePosition < 2.5) {
// setOpenLoop(0.0)
// println("wrist exiting at 0 power, $radiansPerSecond")
// return
// }
wristState = WristState.VELOCITY_CONTROL
if(radiansPerSecond > 0) {
talon.selectProfileSlot(1, 0)
} else {
talon.selectProfileSlot(0, 0)
}
talon.set(ControlMode.Velocity, radiansPerSecond)
println("nativeVel: $radiansPerSecond, observedVel: ${talon.sensorCollection.quadratureVelocity}, error: ${talon.sensorCollection.quadratureVelocity - radiansPerSecond}")
}
val loop: Loop = object : Loop {
override fun onStart() {
zeroSensors()
}
override fun onLoop() {
synchronized(this@Wrist) {
wristAngle = WristConversion.pulsesToRadians(talon.sensorCollection.quadraturePosition.toDouble())
if (wristState == WristState.OPEN_LOOP || wristState == WristState.VELOCITY_CONTROL) {
return
}
// if (outOfBounds()) {
// wristPower = 0.0
// talon.set(ControlMode.PercentOutput, 0.0)
// return
// }
talon.set(ControlMode.MotionMagic, WristConversion.radiansToPulses(wristState.targetAngle).toDouble())
}
}
override fun onStop() = stop()
}
override fun zeroSensors() {
talon.sensorCollection.setQuadraturePosition(0, 0)
}
companion object {
val instance = Wrist()
}
}
| 9 | Kotlin | 0 | 1 | 3d549045a1c487d9a3b387deff43be5666a609a4 | 5,493 | PowerUp-2018 | MIT License |
app/src/main/java/com/puntogris/smartwear/feature_weather/domain/repository/LocationRepository.kt | puntogris | 267,340,936 | false | null | package com.puntogris.smartwear.feature_weather.domain.repository
import com.puntogris.smartwear.core.utils.SimpleResult
import com.puntogris.smartwear.feature_weather.domain.model.Location
import kotlinx.coroutines.flow.Flow
interface LocationRepository {
fun getLocalLastLocation(): Flow<Location?>
suspend fun updateLastLocation(): SimpleResult
suspend fun insertLastLocation(location: Location)
suspend fun getLocationCoordinates(query: String): List<Location>
} | 0 | Kotlin | 0 | 1 | 53cd6bafdc79226140c65f556b5d8bad540f2f0b | 484 | what-do-i-wear | MIT License |
app/src/main/java/com/gsm/bee_assistant_android/retrofit/network/ClassroomApi.kt | Im-Tae | 265,436,336 | false | null | package com.gsm.bee_assistant_android.retrofit.network
import com.gsm.bee_assistant_android.retrofit.domain.classroom.*
import io.reactivex.Single
import retrofit2.Call
import retrofit2.http.*
interface ClassroomApi {
@GET("classroom")
fun getClassroomLink(): Call<ClassroomLink>
@FormUrlEncoded
@POST("classroom")
fun getClassroomToken(@Field("code") code: String): Single<ClassroomToken>
@POST("classroom/class")
fun getClassList(@Body requestClassroomList: RequestClassList): Single<ResponseClassList>
@POST("classroom/work")
fun getClassWork(@Body requestClassWork: RequestClassWork): Single<ResponseClassWork>
} | 0 | Kotlin | 1 | 0 | 28457fdecdc1935e1d97b5a8ac0de6fdff7fbaf4 | 658 | Bee-Android | Apache License 2.0 |
MultiModuleApp2/module2/src/main/java/com/github/yamamotoj/module2/package40/Foo04024.kt | yamamotoj | 163,851,411 | false | {"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2} | package com.github.yamamotoj.module2.package40
class Foo04024 {
fun method0() {
Foo04023().method5()
}
fun method1() {
method0()
}
fun method2() {
method1()
}
fun method3() {
method2()
}
fun method4() {
method3()
}
fun method5() {
method4()
}
}
| 0 | Kotlin | 0 | 9 | 2a771697dfebca9201f6df5ef8441578b5102641 | 347 | android_multi_module_experiment | Apache License 2.0 |
src/main/kotlin/apibuilder/backendmaster/CommandBackendApi.kt | BAC2-Graf-Rohatynski | 208,084,076 | false | null | package apibuilder.backendmaster
import apibuilder.backendmaster.interfaces.ICommandBackendApi
import enumstorage.update.UpdateCommand
import enumstorage.update.UpdateCommandValues
import org.json.JSONObject
object CommandBackendApi: ICommandBackendApi {
@Synchronized
override fun usbUpdate(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.UsbUpdate.name)
@Synchronized
override fun onlineUpdate(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.OnlineUpdate.name)
@Synchronized
override fun availableOnlineUpdates(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.AvailableOnlineUpdates.name)
@Synchronized
override fun enableAutoOnlineUpdate(isEnabled: Boolean): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.EnableAutoOnlineUpdate.name)
.put(UpdateCommandValues.Enabled.name, isEnabled)
@Synchronized
override fun enableAutoOfflineUpdate(isEnabled: Boolean): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.EnableAutoOfflineUpdate.name)
.put(UpdateCommandValues.Enabled.name, isEnabled)
@Synchronized
override fun isAutoOnlineUpdateEnabled(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.IsAutoOnlineUpdateEnabled.name)
@Synchronized
override fun isAutoOfflineUpdateEnabled(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.IsAutoOfflineUpdateEnabled.name)
@Synchronized
override fun shutdown(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.Shutdown.name)
@Synchronized
override fun restart(): JSONObject = JSONObject()
.put(UpdateCommandValues.Command.name, UpdateCommand.Restart.name)
} | 0 | Kotlin | 0 | 0 | 1521a5c7bdd4fc2d6c021d4c28a292f1f1347529 | 1,967 | ApiBuilder | MIT License |
src/main/java/com/arman/kotboy/core/sound/SoundChannel2.kt | coenvk | 182,844,893 | false | {"Kotlin": 327296, "Batchfile": 143} | package com.arman.kotboy.core.sound
import com.arman.kotboy.core.cpu.util.at
import com.arman.kotboy.core.io.IoReg
class SoundChannel2 : SoundChannel(IoReg.NR_21.address, IoReg.NR_24.address) {
override var nr0: Int
get() = 0xFF
set(value) {}
override var nr1: Int
get() {
return super.get(IoReg.NR_21.address)
}
set(value) {
super.set(IoReg.NR_21.address, value)
}
override var nr2: Int
get() {
return super.get(IoReg.NR_22.address)
}
set(value) {
super.set(IoReg.NR_22.address, value)
}
override var nr3: Int
get() {
return super.get(IoReg.NR_23.address)
}
set(value) {
super.set(IoReg.NR_23.address, value)
}
override var nr4: Int
get() {
return super.get(IoReg.NR_24.address)
}
set(value) {
super.set(IoReg.NR_24.address, value)
}
override val period: Int
get() = this.frequency * 4
override fun start() {
// TODO
}
override fun stop() {
// TODO
}
override fun trigger() {
// TODO
}
override fun reset() {
super.reset()
this.nr1 = 0x3F
this.nr2 = 0x00
this.nr3 = 0x00
this.nr4 = 0xBF
}
override fun set(address: Int, value: Int): Boolean {
var v = value
when (address) {
IoReg.NR_24.address -> {
v = v and 0xC7
if (v.at(7)) trigger()
}
}
return super.set(address, v)
}
override fun get(address: Int): Int {
var value = 0x00
when (address) {
IoReg.NR_21.address -> value = value or 0x3F
IoReg.NR_22.address -> value = value or 0x00
IoReg.NR_23.address -> value = value or 0xFF
IoReg.NR_24.address -> value = value or 0xBF
}
return value
}
} | 0 | Kotlin | 2 | 3 | 709efa50a0b176d7ed8aefe4db0f35f173472de2 | 2,006 | KotBoy | MIT License |
samples/solivagant-wasm-sample/src/wasmJsMain/kotlin/com/hoc081098/solivagant/sample/wasm/start/StartViewModel.kt | hoc081098 | 736,617,487 | false | {"Kotlin": 284952, "Shell": 371} | package com.hoc081098.solivagant.sample.wasm.second
import com.hoc081098.flowext.interval
import com.hoc081098.kmp.viewmodel.SavedStateHandle
import com.hoc081098.kmp.viewmodel.ViewModel
import com.hoc081098.solivagant.navigation.requireRoute
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
internal class SecondViewModel(
savedStateHandle: SavedStateHandle,
) : ViewModel() {
internal val route = savedStateHandle.requireRoute<SecondScreenRoute>()
internal val timerFlow: StateFlow<Long?> = interval(Duration.ZERO, 1.seconds)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(@Suppress("MagicNumber") 5_000),
initialValue = null,
)
init {
println(">>> $this::init")
addCloseable { println(">>> $this::close") }
}
}
| 6 | Kotlin | 3 | 63 | ffc979a6be267c64d1684f9aa96ad7de33e916ff | 941 | solivagant | Apache License 2.0 |
app/src/main/java/com/kieronquinn/app/darq/ui/screens/settings/apppicker/SettingsAppPickerViewModel.kt | KieronQuinn | 194,549,688 | false | null | package com.kieronquinn.app.darq.ui.screens.settings.apppicker
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kieronquinn.app.darq.BuildConfig
import com.kieronquinn.app.darq.components.settings.DarqSharedPreferences
import com.kieronquinn.app.darq.model.settings.AppPickerItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
abstract class SettingsAppPickerViewModel : ViewModel() {
abstract val loadState: Flow<LoadState>
abstract val showSearchClearButton: Flow<Boolean>
abstract fun onPackageEnabledChanged(app: AppPickerItem.App)
abstract fun setSearchTerm(searchTerm: String)
abstract fun getSearchTerm(): String
abstract fun setShowAllApps(showAllApps: Boolean)
abstract fun getShowAllApps(): Boolean
sealed class LoadState {
object Loading : LoadState()
data class Loaded(val apps: List<AppPickerItem.App>) : LoadState()
}
}
class SettingsAppPickerViewModelImpl(
context: Context,
private val settings: DarqSharedPreferences
) : SettingsAppPickerViewModel() {
private val packageManager by lazy {
context.packageManager
}
private val allApps = MutableSharedFlow<List<InstalledApp>>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
).apply {
viewModelScope.launch(Dispatchers.IO) {
emit(packageManager.getInstalledApplications(0).mapNotNull {
if(it.packageName == BuildConfig.APPLICATION_ID) return@mapNotNull null
InstalledApp(it.packageName, it.loadLabel(packageManager))
})
}
}
private val launchableApps = MutableSharedFlow<List<InstalledApp>>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
).apply {
viewModelScope.launch(Dispatchers.IO){
val apps = allApps.map {
it.filter { app -> packageManager.getLaunchIntentForPackage(app.packageName) != null }
}.first()
emit(apps)
}
}
private val selectedApps = MutableStateFlow<MutableList<String>?>(null).apply {
viewModelScope.launch(Dispatchers.IO) {
emit(settings.enabledApps.toMutableList())
}
}
private val _loadState = MutableStateFlow<LoadState>(LoadState.Loading)
override val loadState = _loadState.asStateFlow()
private val searchTerm = MutableStateFlow("")
override val showSearchClearButton: Flow<Boolean> = searchTerm.map { it.isNotEmpty() }
private val showAllApps = MutableStateFlow(false).apply {
viewModelScope.launch {
collect {
loadApps()
}
}
}
private suspend fun loadApps() {
_loadState.emit(LoadState.Loading)
val apps = combine(
allApps,
launchableApps,
selectedApps.filterNotNull(),
searchTerm
) { all, launchable, selected, search ->
withContext(Dispatchers.IO) {
if (showAllApps.value) all.map {
AppPickerItem.App(
it.packageName,
it.label,
selected.contains(it.packageName)
)
}
else launchable.map {
AppPickerItem.App(
it.packageName,
it.label,
selected.contains(it.packageName)
)
}
}.sortedBy { it.label.toString().toLowerCase(Locale.getDefault()) }.run {
if (search.isNotEmpty()) filter {
it.label.toString().toLowerCase(Locale.getDefault()).contains(
search.toLowerCase(
Locale.getDefault()
)
)
}else this
}
}.first()
_loadState.emit(LoadState.Loaded(apps))
}
override fun onPackageEnabledChanged(app: AppPickerItem.App) {
viewModelScope.launch(Dispatchers.IO) {
val currentSelectedApps = selectedApps.value ?: return@launch
if (app.enabled) {
if (!currentSelectedApps.contains(app.packageName)) {
currentSelectedApps.add(app.packageName)
}
} else {
if (currentSelectedApps.contains(app.packageName)) {
currentSelectedApps.remove(app.packageName)
}
}
settings.enabledApps = currentSelectedApps.toTypedArray()
}
}
override fun setSearchTerm(searchTerm: String) {
viewModelScope.launch {
[email protected](searchTerm)
loadApps()
}
}
override fun getSearchTerm(): String {
return searchTerm.value
}
override fun setShowAllApps(showAllApps: Boolean) {
viewModelScope.launch {
[email protected](showAllApps)
}
}
override fun getShowAllApps(): Boolean {
return showAllApps.value
}
private data class InstalledApp(val packageName: String, val label: CharSequence)
} | 8 | null | 39 | 915 | e058b4230575288ac06f7c7fd2a6c4cc6daae108 | 5,456 | DarQ | Apache License 2.0 |
app/src/main/java/com/kelompok7/rpl/movietrailer/adapter/SearchAdapter.kt | wahyuWs | 432,215,828 | false | null | package com.kelompok7.rpl.movietrailer.adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.kelompok7.rpl.movietrailer.databinding.ItemSearchBinding
import com.kelompok7.rpl.movietrailer.model.Movies
import com.kelompok7.rpl.movietrailer.ui.halamandetail.DetailActivity
class SearchAdapter: RecyclerView.Adapter<SearchAdapter.SearchViewHolder>(), Filterable {
val dataMovie = ArrayList<Movies>()
private val dataMovieFiltered = ArrayList<Movies>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder {
val itemSearchBinding = ItemSearchBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return SearchViewHolder(itemSearchBinding)
}
override fun onBindViewHolder(holder: SearchViewHolder, position: Int) {
holder.bind(dataMovieFiltered[position])
}
override fun getItemCount(): Int = dataMovieFiltered.size
class SearchViewHolder(private val binding: ItemSearchBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(data: Movies) {
Glide.with(itemView.context)
.load(data.movieImage)
.transform(RoundedCorners(18))
.into(binding.imagePoster)
binding.titleMovie.text = data.movieTitle
binding.kategoriFilm.text = data.movieGenre
binding.duration.text = data.movieDuration
itemView.setOnClickListener {
val intent = Intent(itemView.context, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_DATA, data)
itemView.context.startActivity(intent)
}
}
}
override fun getFilter(): Filter {
return object : Filter() {
override fun performFiltering(p0: CharSequence?): FilterResults {
val filtered = ArrayList<Movies>()
for (movie in dataMovie) {
if (movie.toString().toLowerCase().contains(p0.toString().toLowerCase())) {
filtered.add(movie)
}
}
val filterResult = FilterResults()
filterResult.values = filtered
return filterResult
}
override fun publishResults(p0: CharSequence?, p1: FilterResults?) {
dataMovieFiltered.clear()
dataMovieFiltered.addAll(p1?.values as Collection<Movies>)
notifyDataSetChanged()
}
}
}
} | 0 | Kotlin | 0 | 0 | e76fa0b02b91cefca5521b23d5d516ed64c85345 | 2,778 | Movie-Trailer | Apache License 2.0 |
app/src/main/java/com/mateusz113/financemanager/presentation/payments/payment_details/PaymentDetailsState.kt | Mateusz113 | 723,729,693 | false | {"Kotlin": 190799} | package com.mateusz113.financemanager.presentation.payments.payment_details
import com.mateusz113.financemanager.domain.model.PaymentDetails
data class PaymentDetailsState<T>(
var paymentDetails: PaymentDetails? = null,
var error: String? = null,
var isLoading: Boolean = false,
var isRefreshing: Boolean = false,
var isPhotoDialogOpen: Boolean = false,
var dialogPhoto: T? = null
) | 0 | Kotlin | 0 | 1 | 70d2af5d00a57d965a574f8e582f6dca8e2f1ee2 | 408 | Finance-Manager | The Unlicense |
android/feature/content-viewer/src/main/kotlin/io/github/reactivecircus/kstreamlined/android/feature/contentviewer/SchemeAwareWebViewClient.kt | ReactiveCircus | 513,535,591 | false | {"Kotlin": 535646} | package io.github.reactivecircus.kstreamlined.android.feature.contentviewer
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.webkit.WebResourceRequest
import android.webkit.WebView
import co.touchlab.kermit.Logger
internal class SchemeAwareWebViewClient : AccompanistWebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.let {
var url = it.url.toString()
if (url.startsWith("http://") || url.startsWith("https://")) {
return false
}
if (url.contains("youtube.com")) {
url = url.replaceFirst("intent://", "vnd.youtube:")
}
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
view?.context?.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Logger.e(e) { "No Activity was found to handle the Intent." }
}
}
return true
}
}
| 2 | Kotlin | 0 | 4 | 6bda77402bac5e6e1ffaaf1513a3d837ac383451 | 1,112 | kstreamlined-mobile | Apache License 2.0 |
compose/src/main/java/com/aaron/compose/paging/Common.kt | aaronzzx | 519,802,264 | false | null | package com.aaron.compose.paging
import kotlinx.coroutines.delay
internal suspend fun makeSureTime(startTime: Long, minDelayTime: Long) {
val costTime = System.currentTimeMillis() - startTime
delay(costTime.coerceAtLeast(minDelayTime))
}
class AppPagingException(
val code: Int,
val msg: String
) : Exception("AppPagingException: $code, $msg") | 0 | Kotlin | 0 | 1 | 9017759dcd0e8092e4c6157143d763421432ecf4 | 362 | Fast-Compose | Apache License 2.0 |
LargeDynamicProject/common/commonA/src/main/java/com/devrel/experiment/large/dynamic/feature/common/a/Foo3266.kt | skimarxall | 212,285,318 | false | null | package com.devrel.experiment.large.dynamic.feature.common.a
annotation class Foo3266Fancy
@Foo3266Fancy
class Foo3266 {
fun foo0(){
Foo3265().foo8()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
fun foo7(){
foo6()
}
fun foo8(){
foo7()
}
} | 1 | null | 1 | 1 | e027d45a465c98c5ddbf33c68deb09a6e5975aab | 403 | app-bundle-samples | Apache License 2.0 |
zoomable-image/sub-sampling-image/src/main/kotlin/me/saket/telephoto/subsamplingimage/internal/BitmapLoader.kt | saket | 593,020,002 | false | null | package me.saket.telephoto.subsamplingimage.internal
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.util.fastForEach
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import me.saket.telephoto.subsamplingimage.internal.BitmapLoader.LoadingState.InFlight
import me.saket.telephoto.subsamplingimage.internal.BitmapLoader.LoadingState.Loaded
internal class BitmapLoader(
private val decoder: ImageRegionDecoder,
private val scope: CoroutineScope,
) {
private val cachedBitmaps = MutableStateFlow(emptyMap<BitmapRegionTile, LoadingState>())
private sealed interface LoadingState {
data class Loaded(val bitmap: ImageBitmap) : LoadingState
data class InFlight(val job: Job) : LoadingState
}
fun cachedBitmaps(): Flow<Map<BitmapRegionTile, ImageBitmap>> {
return cachedBitmaps.map { map ->
buildMap(capacity = map.size) {
map.forEach { (region, state) ->
if (state is Loaded) {
put(region, state.bitmap)
}
}
}
}.distinctUntilChanged()
}
fun loadOrUnloadForTiles(tiles: List<BitmapRegionTile>) {
val regionsToLoad = tiles
.filter { it !in cachedBitmaps.value }
val regionsToUnload = cachedBitmaps.value.keys
.filter { it !in tiles }
regionsToLoad.fastForEach { region ->
val job = scope.launch {
val bitmap = decoder.decodeRegion(region)
cachedBitmaps.update { it + (region to Loaded(bitmap)) }
}
cachedBitmaps.update { it + (region to InFlight(job)) }
}
regionsToUnload.fastForEach { region ->
val inFlight = cachedBitmaps.value[region] as? InFlight
inFlight?.job?.cancel()
}
cachedBitmaps.update { it - regionsToUnload.toSet() }
}
}
| 15 | Kotlin | 12 | 624 | f65522feff29da069665760f66e5078a937bbfe7 | 2,007 | telephoto | Apache License 2.0 |
warehouse-service/src/main/kotlin/ru/romanow/inst/services/warehouse/web/ExceptionController.kt | Romanow | 304,987,654 | false | {"Kotlin": 117029, "JavaScript": 2720, "Dockerfile": 2127, "HCL": 1533, "Shell": 1444} | package ru.romanow.inst.services.warehouse.web
import io.swagger.v3.oas.annotations.Hidden
import jakarta.persistence.EntityNotFoundException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RestControllerAdvice
import ru.romanow.inst.services.common.model.ErrorResponse
import ru.romanow.inst.services.warehouse.exceptions.ItemNotAvailableException
import ru.romanow.inst.services.warehouse.exceptions.WarrantyProcessException
@Hidden
@RestControllerAdvice(annotations = [RestController::class])
class ExceptionController {
private val logger = LoggerFactory.getLogger(ExceptionController::class.java)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException::class)
fun badRequest(exception: MethodArgumentNotValidException): ErrorResponse {
val validationErrors = prepareValidationErrors(exception.bindingResult.fieldErrors)
if (logger.isDebugEnabled) {
logger.debug("Bad Request: {}", validationErrors)
}
return ErrorResponse(validationErrors)
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(EntityNotFoundException::class)
fun notFound(exception: EntityNotFoundException): ErrorResponse {
return ErrorResponse(exception.message)
}
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(ItemNotAvailableException::class)
fun conflict(exception: ItemNotAvailableException): ErrorResponse {
return ErrorResponse(exception.message)
}
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(WarrantyProcessException::class)
fun conflict(exception: WarrantyProcessException): ErrorResponse {
return ErrorResponse(exception.message)
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(RuntimeException::class)
fun handleException(exception: RuntimeException): ErrorResponse {
logger.error("", exception)
return ErrorResponse(exception.message)
}
private fun prepareValidationErrors(errors: List<FieldError>): String {
return errors.joinToString(";") { "Field " + it.field + " has wrong value: [" + it.defaultMessage + "]" }
}
}
| 0 | Kotlin | 4 | 3 | db8614bb98049e8abed6b70e4dc49de9313dba27 | 2,567 | micro-services-v2 | MIT License |
src/dorkbox/kloudflareApi/api/zone/PlanPending.kt | dorkbox | 193,524,185 | false | {"Kotlin": 105882} | /*
* Copyright 2019 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.kloudflareApi.api.zone
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* https://api.cloudflare.com/#zone-properties
*/
@JsonClass(generateAdapter = true)
class Plan {
/**
* Plan identifier tag
*/
@field:[Json(name = "id")]
var id = ""
/**
* The plan name
*/
@field:[Json(name = "name")]
var name: String? = null
/**
* The price of the subscription that will be billed, in US dollars
*/
@field:[Json(name = "price")]
var price = 0
/**
* The monetary unit in which pricing information is displayed
*/
@field:[Json(name = "currency")]
var currency = "USD"
/**
* The frequency at which you will be billed for this plan
* weekly, monthly, quarterly, yearly
*/
@field:[Json(name = "frequency")]
var frequency = "weekly"
/**
* A 'friendly' identifier to indicate to the UI what plan the object is
* free, pro, business, enterprise
*/
@field:[Json(name = "legacy_id")]
var legacyId = "free"
/**
* If the zone is subscribed to this plan
*/
@field:[Json(name = "is_subscribed")]
var isSubscribed = false
/**
* If the zone is allowed to subscribe to this plan
*/
@field:[Json(name = "can_subscribe")]
var canSubscribe = false
override fun toString(): String {
return "Plan(id='$id', name=$name, price=$price, currency='$currency', frequency='$frequency', legacyId='$legacyId', isSubscribed=$isSubscribed, canSubscribe=$canSubscribe)"
}
}
| 1 | Kotlin | 2 | 4 | d4e2341158ed150f1ef515b9737540f079e0f69b | 2,178 | KloudflareAPI | Apache License 2.0 |
src/test/java/io/vertx/kotlin/core/json/json.kt | vert-x3 | 27,142,145 | false | null | package io.vertx.kotlin.core.json
import io.vertx.core.json.*
object Json
// JsonObject creation
fun JsonObject(vararg fields: Pair<String, Any?>): JsonObject = JsonObject(linkedMapOf(*fields))
fun Json.obj(vararg fields: Pair<String, Any?>): JsonObject = JsonObject(*fields)
fun Json.obj(fields: Iterable<Pair<String, Any?>>): JsonObject = JsonObject(*fields.toList().toTypedArray())
fun Json.obj(fields: Map<String, Any?>): JsonObject = JsonObject(fields)
fun Json.obj(block: JsonObject.() -> Unit): JsonObject = JsonObject().apply(block)
// JsonArray creation
fun JsonArray(vararg values: Any?): JsonArray = io.vertx.core.json.JsonArray(arrayListOf(*values))
fun Json.array(vararg values: Any?): JsonArray = JsonArray(*values)
fun Json.array(values: Iterable<Any?>): JsonArray = JsonArray(*values.toList().toTypedArray())
fun Json.array(value: JsonObject): JsonArray = JsonArray(value)
fun Json.array(value: JsonArray): JsonArray = JsonArray(value)
fun Json.array(values: List<Any?>): JsonArray = io.vertx.core.json.JsonArray(values)
fun Json.array(block: JsonArray.() -> Unit): JsonArray = JsonArray().apply(block)
inline fun <T> json(block: Json.() -> T): T = Json.block()
/**
* The postscript operator for [JsonObject].
*/
@Suppress("UNCHECKED_CAST") operator fun <T> JsonObject.get(key: String): T = getValue(key) as T
/**
* The postscript operator for [JsonArray].
*/
@Suppress("UNCHECKED_CAST") operator fun <T> JsonArray.get(index: Int): T = getValue(index) as T
| 2 | null | 19 | 19 | 9974aa90d1891940405ab58697f0bf4a31c457db | 1,486 | vertx-codetrans | Apache License 2.0 |
modules/system/src/main/kotlin/com/blank/system/service/ISysDataScopeService.kt | qq781846712 | 705,955,843 | false | {"Kotlin": 848578, "Vue": 376959, "TypeScript": 137544, "Java": 45954, "HTML": 29445, "SCSS": 19657, "JavaScript": 3399, "Batchfile": 2056, "Shell": 1786, "Dockerfile": 1306} | package com.blank.system.service
/**
* 通用 数据权限 服务
*/
interface ISysDataScopeService {
/**
* 获取角色自定义权限
*
* @param roleId 角色id
* @return 部门id组
*/
fun getRoleCustom(roleId: Long): String?
/**
* 获取部门及以下权限
*
* @param deptId 部门id
* @return 部门id组
*/
fun getDeptAndChild(deptId: Long): String?
}
| 1 | Kotlin | 0 | 0 | e7ce0812d564f79ef655788829d983c25e51592a | 358 | Ruoyi-Vue-Plus-Kotlin | Apache License 2.0 |
app/src/main/java/com/ilab/yougetmobiledl/utils/LogUtils.kt | zhushenwudi | 384,865,719 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Kotlin": 72, "XML": 29, "Java": 6, "Python": 1, "HTML": 1, "SVG": 1, "CSS": 4, "JavaScript": 13} | package com.ilab.yougetmobiledl.utils
import android.text.TextUtils
import android.util.Log
import com.ilab.yougetmobiledl.ext.enableLog
object LogUtils {
private const val DEFAULT_TAG = "JetpackMvvm"
fun debugInfo(tag: String?, msg: String?) {
if (!enableLog || TextUtils.isEmpty(msg)) {
return
}
Log.d(tag, msg!!)
}
fun debugInfo(msg: String?) {
debugInfo(
DEFAULT_TAG,
msg
)
}
fun warnInfo(tag: String?, msg: String?) {
if (!enableLog || TextUtils.isEmpty(msg)) {
return
}
Log.w(tag, msg!!)
}
fun warnInfo(msg: String?) {
warnInfo(
DEFAULT_TAG,
msg
)
}
fun loge(tag: String?, msg: String?) {
if (!enableLog || TextUtils.isEmpty(msg)) {
return
}
Log.e(tag, msg!!)
}
fun loge(msg: String?) {
if (!enableLog || TextUtils.isEmpty(msg)) {
return
}
Log.e("=test=", msg!!)
}
/**
* 这里使用自己分节的方式来输出足够长度的 message
*
* @param tag 标签
* @param msg 日志内容
*/
fun debugLongInfo(tag: String?, msg: String) {
var msg = msg
if (!enableLog || TextUtils.isEmpty(msg)) {
return
}
msg = msg.trim { it <= ' ' }
var index = 0
val maxLength = 3500
var sub: String
while (index < msg.length) {
sub = if (msg.length <= index + maxLength) {
msg.substring(index)
} else {
msg.substring(index, index + maxLength)
}
index += maxLength
Log.d(tag, sub.trim { it <= ' ' })
}
}
fun debugLongInfo(msg: String) {
debugLongInfo(
DEFAULT_TAG,
msg
)
}
} | 1 | null | 1 | 1 | 1755a1e5971a017b0f44c4df3e9491ae46a8d2fc | 1,859 | YougetMobileDL | MIT License |
confluence-plugin/src/main/java/com/networkedassets/git4c/core/business/ExtractionHandler.kt | rpaasche | 321,741,515 | true | {"Kotlin": 798728, "JavaScript": 351426, "Java": 109291, "Groovy": 55451, "CSS": 37375, "ANTLR": 19544, "Gherkin": 15007, "HTML": 14268, "Shell": 4490, "Ruby": 1378, "Batchfile": 1337, "PowerShell": 716} | package com.networkedassets.git4c.core.business
import com.networkedassets.git4c.core.datastore.extractors.ExtractorData
interface ExtractionHandler<in T> where T: ExtractorData {
fun extract(content: String, data: T): ExtractionResult
} | 0 | Kotlin | 0 | 0 | e55391b33cb70d66bbf5f36ba570fb8822f10953 | 243 | git4c | Apache License 2.0 |
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/spec/TestSuiteScheduler.kt | chag6720 | 401,943,815 | true | {"Kotlin": 3103126, "CSS": 352, "Java": 145} | package io.kotest.engine.spec
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.Spec
import io.kotest.engine.TestSuite
import io.kotest.engine.extensions.TestSuiteSchedulerExtension
import kotlin.reflect.KClass
/**
* A [TestSuiteScheduler] is responsible for launching the specs from a [TestSuite] into coroutines.
*
* Register a [TestSuiteSchedulerExtension] to provide a custom implementation.
*/
@ExperimentalKotest
interface TestSuiteScheduler {
suspend fun schedule(suite: TestSuite, f1: suspend (Spec) -> Unit, f2: suspend (KClass<out Spec>) -> Unit)
}
| 0 | null | 0 | 0 | 07ded8ab26a99da872b058f6747dcbc5527d1f71 | 588 | kotest | Apache License 2.0 |
src/main/kotlin/com/softwareascraft/eventingswitchlist/models/RollingStock.kt | MyTurnyet | 786,587,760 | false | {"Kotlin": 15823} | package com.softwareascraft.eventingswitchlist.models
interface FreightCar {
val roadMarkings: String
fun isAarType(expectedType: CarType): Boolean
}
interface CarriesLoad {
fun load()
fun isLoaded(): Boolean
}
abstract class RollingStock(private val roadName: String, private val roadNumber: Int, private val carType: CarType) :
FreightCar {
override val roadMarkings: String
get() = "$roadName $roadNumber"
override fun isAarType(expectedType: CarType): Boolean {
return this.carType == expectedType
}
}
class Boxcar(roadName: String, roadNumber: Int) : CarriesLoad,
RollingStock(roadName, roadNumber, CarType.Boxcar) {
private var loaded: Boolean = false
override fun load() {
this.loaded = true
}
override fun isLoaded(): Boolean {
return this.loaded
}
} | 0 | Kotlin | 0 | 0 | 29ffd8ac5013fa18909cedaa0ff9c923738af2d5 | 856 | eventing-switchlist | MIT License |
kotlin/goi/src/main/kotlin/net/paploo/goi/pipeline/furiganatemplate/exporter/CSVFuriganaTemplateExporter.kt | paploo | 526,415,165 | false | {"Kotlin": 573023, "Ruby": 153592, "Java": 50703, "ANTLR": 2904, "CSS": 1961, "PLpgSQL": 274} | package net.paploo.goi.pipeline.furiganatemplate.exporter
import net.paploo.goi.common.extensions.mapFailure
import net.paploo.goi.domain.data.common.FuriganaString
import net.paploo.goi.domain.tools.furiganatemplate.FuriganaTemplate
import net.paploo.goi.domain.tools.furiganatemplate.transformers.AnkiTemplateTransformer
import net.paploo.goi.pipeline.core.Context
import net.paploo.goi.pipeline.core.Exporter
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.file.Path
class CSVFuriganaTemplateExporter (
val config: Config
) : Exporter<List<FuriganaString>> {
data class Config(
val filePath: Path,
val format: Format
) {
enum class Format(val delimiter: Char) {
CSV(','),
TSV('\t')
}
}
override suspend fun invoke(furiganaStrings: List<FuriganaString>, context: Context): Result<Unit> =
Result.runCatching {
PrintWriter(config.filePath.toFile()).use { writer ->
writer.print(writeRow(headers))
furiganaStrings.mapIndexed { index, furiganaString ->
println(furiganaString)
val rowValues = toRow(furiganaString).mapFailure { th ->
IllegalArgumentException("Error on entry number ${index+1}: $th", th)
}.getOrThrow()
writer.print(writeRow(rowValues))
}
}
}
private val headers: List<String> =
listOf("template", "preferred", "phonetic", "anki")
private fun toRow(furiganaString: FuriganaString): Result<List<String?>> =
when(val template = furiganaString.furiganaTemplate) {
is FuriganaTemplate.Text -> template.preferred
is FuriganaTemplate.Ruby -> "{${template.preferred}|${template.phonetic}}"
is FuriganaTemplate.CurlyBraces -> template.templateString
is FuriganaTemplate.Anki -> template.templateString
}.let { template ->
Result.runCatching {
listOf(
template,
furiganaString.preferredSpelling.value,
furiganaString.phoneticSpelling?.value,
furiganaString.transform(AnkiTemplateTransformer.default).getOrNull()?.templateString
)
}
}
private fun toRowUnsafe(furiganaString: FuriganaString): List<String?> =
when(val template = furiganaString.furiganaTemplate) {
is FuriganaTemplate.Text -> template.preferred
is FuriganaTemplate.Ruby -> "{${template.preferred}|${template.phonetic}}"
is FuriganaTemplate.CurlyBraces -> template.templateString
is FuriganaTemplate.Anki -> template.templateString
}.let { template ->
listOf(
template,
furiganaString.preferredSpelling.value,
furiganaString.phoneticSpelling?.value,
furiganaString.transform(AnkiTemplateTransformer.default).getOrNull()?.templateString
)
}
private fun writeRow(values: List<String?>): String =
StringWriter().use { writer ->
CSVPrinter(writer, csvFormat).use { csvPrinter ->
csvPrinter.printRecord(values)
}
writer.toString()
}
private val csvFormat: CSVFormat = CSVFormat.Builder
.create(CSVFormat.RFC4180)
.setRecordSeparator("\n") //Use UNIX LF instead of RFC4180 specified CRLF
.setDelimiter(config.format.delimiter) //The field delimeter (comma for CSV)
.setNullString("") //Make sure nulls render as empty fields.
.build()
} | 3 | Kotlin | 0 | 0 | 8edef8afa574097d66b2a4f89d75d1e4c69bd219 | 3,787 | goi | MIT License |
app/src/main/java/ru/holofox/anicoubs/ui/timeline/list/TimelineListBindings.kt | Holofox | 199,176,207 | false | null | package ru.holofox.anicoubs.ui.timeline.list
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import ru.holofox.anicoubs.features.data.network.api.coub.models.timeline.Tag
import ru.holofox.anicoubs.features.data.network.api.coub.models.timeline.Versions
import ru.holofox.anicoubs.internal.bindings.bindImageUrl
object TimelineListBindings {
/**
* Binding adapter used to display images from Avatar[Versions] using Glide
*/
@BindingAdapter("imageUrlFromAvatarVersions")
@JvmStatic
fun bindImageFromAvatarVersions(imageView: ImageView, versions: Versions) {
bindImageUrl(
imageView,
versions.getImageUrl("profile_pic_new")
)
}
/**
* Binding adapter used to display images from FirstFrame[Versions] using Glide
*/
@BindingAdapter("imageUrlFromFirstFrameVersions")
@JvmStatic
fun bindImageFromFirstFrameVersions(imageView: ImageView, versions: Versions) {
bindImageUrl(imageView, versions.getImageUrl("med"))
}
/**
* Binding adapter used to display tags in [ChipGroup] from [Tag]
*/
@BindingAdapter("tags")
@JvmStatic
fun bindTags(chipGroup: ChipGroup, tags: List<Tag>?) {
tags?.let {
for (index in it.indices) {
val chip = Chip(chipGroup.context)
chip.text = tags[index].title
chip.isClickable = true
chipGroup.addView(chip)
}
}
}
} | 0 | Kotlin | 0 | 0 | 70dec75d35f7b044c2817c07c5e37e687bb1c9cc | 1,599 | android-anicoubs | MIT License |
app/src/main/java/com/kl3jvi/animity/utils/Preferences.kt | kl3jvi | 286,457,139 | false | null | package com.kl3jvi.animity.utils
import android.content.SharedPreferences
import androidx.annotation.StringRes
import androidx.core.content.edit
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.kl3jvi.animity.settings.toJson
fun <T : Preference> PreferenceFragmentCompat.configurePreference(
@StringRes preferenceId: Int,
preferences: SharedPreferences,
clickListener: Preference.OnPreferenceClickListener? = null,
block: T.() -> Unit = {}
): T {
val preference = requirePreference<T>(preferenceId)
preference.block()
preference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val key = getPreferenceKey(preferenceId)
preferences.edit {
when (newValue) {
is Boolean -> putBoolean(key, newValue)
is Int -> putLong(key, newValue.toLong() * 1000)
is String -> putString(key, newValue.toJson())
}
}
true
}
preference.onPreferenceClickListener = clickListener
return preference
}
private fun <T : Preference> PreferenceFragmentCompat.requirePreference(
@StringRes preferenceId: Int
) = requireNotNull(findPreference<T>(getPreferenceKey(preferenceId)))
| 5 | null | 31 | 729 | 6be5b8406f673dbfc3b4c454d0c9542564143bfb | 1,286 | animity | MIT License |
src/main/kotlin/br/com/zup/edu/pix/banco/PixKeyDetailsResponse.kt | joaldotavares | 394,387,471 | true | {"Kotlin": 61827} | package br.com.zup.edu.pix.banco
import br.com.zup.edu.pix.chave.consulta.ChavePixInfo
import br.com.zup.edu.pix.conta.ContaAssociada
import br.com.zup.edu.pix.conta.TipoDeConta
import java.time.LocalDateTime
data class PixKeyDetailsResponse(
val keyType: PixKeyType,
val key: String,
val bankAccount: BankAccount,
val owner: Owner,
val createdAt: LocalDateTime
) {
fun toModel(): ChavePixInfo {
return ChavePixInfo(
tipoDeChave = keyType.domainType!!,
chave = key,
tipoDeConta =when(this.bankAccount.accountType){
BankAccount.AccountType.CACC -> TipoDeConta.CONTA_CORRENTE
BankAccount.AccountType.SVGS -> TipoDeConta.CONTA_POUPANCA
}, conta = ContaAssociada(
instituicao = bankAccount.participant,
nomeDoTitular = owner.name,
cpfDoTitular = owner.taxIdNumber,
agencia = bankAccount.branch,
numeroDaConta = bankAccount.accountNumber
),
criadaEm = createdAt,
pixId = null,
clienteId = null
)
}
}
| 0 | Kotlin | 0 | 0 | 8c5818aabd85e38f36614145a96a749ac89d5e44 | 1,149 | orange-talents-06-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/app/legend/kanfanba/main/presenter/MovieFragmentPresenter.kt | liuzhushaonian | 222,131,204 | false | null | package com.app.legend.kanfanba.main.presenter
import com.app.legend.ruminasu.presenters.BasePresenter
class MovieFragmentPresenter(fragment: IMovieFragment):BasePresenter<IMovieFragment>() {
private lateinit var fragment: IMovieFragment
init {
attachView(fragment)
this.fragment=getView()!!
}
}
| 0 | Kotlin | 0 | 0 | b77f1f7be4f20b42fe319bd62c004db2a8e73872 | 330 | KanFanBa | MIT License |
app/src/main/java/com/example/cryptocurrencyapp/domain/use_case/get_coins/GetCoinsUseCase.kt | TortasMcFly | 410,043,410 | false | {"Kotlin": 29250} | package com.example.cryptocurrencyapp.domain.use_case.get_coins
import com.example.cryptocurrencyapp.common.Resource
import com.example.cryptocurrencyapp.data.remote.dto.coin.toCoin
import com.example.cryptocurrencyapp.domain.model.Coin
import com.example.cryptocurrencyapp.domain.repository.CoinRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
class GetCoinsUseCase @Inject constructor(
private val repository: CoinRepository
) {
operator fun invoke(): Flow<Resource<List<Coin>>> = flow {
try {
emit(Resource.Loading())
val coins = repository.getCoins().map { it.toCoin() }
emit(Resource.Success(coins))
} catch (e: HttpException) {
emit(Resource.Error<List<Coin>>(e.localizedMessage ?: "An unexpected error occured"))
} catch (e: IOException) {
emit(Resource.Error<List<Coin>>("Couldn't reach server. Check your internet connection"))
}
}
} | 0 | Kotlin | 0 | 0 | 7361feb8423e6e7f8a7fd9f365ea3d158e18d028 | 1,068 | CryptoCurrencyApp | MIT License |
core/src/main/kotlin/org/jetbrains/kotlinx/dataframe/api/all.kt | Kotlin | 259,256,617 | false | null | package org.jetbrains.kotlinx.dataframe.api
import org.jetbrains.kotlinx.dataframe.AnyRow
import org.jetbrains.kotlinx.dataframe.DataColumn
import org.jetbrains.kotlinx.dataframe.DataFrame
import org.jetbrains.kotlinx.dataframe.Predicate
import org.jetbrains.kotlinx.dataframe.RowFilter
import org.jetbrains.kotlinx.dataframe.columns.size
import org.jetbrains.kotlinx.dataframe.columns.values
import org.jetbrains.kotlinx.dataframe.impl.owner
import org.jetbrains.kotlinx.dataframe.index
// region DataColumn
public fun <T> DataColumn<T>.all(predicate: Predicate<T>): Boolean = values.all(predicate)
public fun <C> DataColumn<C>.allNulls(): Boolean = size == 0 || all { it == null }
// endregion
// region DataRow
public fun AnyRow.allNA(): Boolean = owner.columns().all { it[index].isNA }
// endregion
// region DataFrame
public fun <T> DataFrame<T>.all(predicate: RowFilter<T>): Boolean = rows().all { predicate(it, it) }
// endregion
| 24 | Kotlin | 12 | 263 | a746109516c0ad13583ccf2365325e910a39ec1c | 948 | dataframe | Apache License 2.0 |
src/main/java/com/rjs/myshows/domain/Show.kt | MiseryMachine | 131,063,553 | false | null | package com.rjs.myshows.domain
import java.time.LocalDate
interface Show: BaseElement {
var mdbId: String
var imdbId: String?
var title: String
var showRating: String
var contentsArray: Array<String>
var tagline: String
var description: String
var releaseDate: LocalDate?
var releaseDateText: String
var runtime: Int
var showType: String
var genres: MutableSet<String>
var mediaFormat: String
var myNotes: String
var starRating: Int
} | 0 | Kotlin | 0 | 0 | a571e408efece32eacc2caca05dd4d5e5fed46f8 | 451 | myshows-common-kt | MIT License |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/bugreporting/censors/submission/RACoronaTestCensor.kt | rsteam-solutions | 379,531,704 | true | {"Gradle": 4, "JSON": 29, "CODEOWNERS": 1, "Java Properties": 2, "Markdown": 11, "INI": 1, "Shell": 2, "Text": 2, "Ignore List": 3, "Batchfile": 1, "YAML": 5, "EditorConfig": 1, "Proguard": 1, "XML": 676, "Kotlin": 1631, "Java": 3, "HTML": 7, "Checksums": 2, "JAR Manifest": 1, "Protocol Buffer": 55, "Groovy": 1, "SVG": 1} | package de.rki.coronawarnapp.bugreporting.censors.submission
import de.rki.coronawarnapp.bugreporting.censors.BugCensor
import de.rki.coronawarnapp.bugreporting.censors.BugCensor.Companion.toNewLogLineIfDifferent
import de.rki.coronawarnapp.bugreporting.censors.BugCensor.Companion.withValidName
import de.rki.coronawarnapp.bugreporting.debuglog.LogLine
import de.rki.coronawarnapp.bugreporting.debuglog.internal.DebuggerScope
import de.rki.coronawarnapp.coronatest.CoronaTestRepository
import de.rki.coronawarnapp.coronatest.type.rapidantigen.RACoronaTest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import org.joda.time.format.DateTimeFormat
import javax.inject.Inject
class RACoronaTestCensor @Inject constructor(
@DebuggerScope debugScope: CoroutineScope,
private val coronaTestRepository: CoronaTestRepository
) : BugCensor {
private val dayOfBirthFormatter = DateTimeFormat.forPattern("yyyy-MM-dd")
private val coronaTestFlow by lazy {
coronaTestRepository.coronaTests.stateIn(
scope = debugScope,
started = SharingStarted.Lazily,
initialValue = null
).filterNotNull()
}
override suspend fun checkLog(entry: LogLine): LogLine? {
val raCoronaTestFlow = coronaTestFlow.map { tests -> tests.filterIsInstance<RACoronaTest>() }.first()
val raCoronaTest = raCoronaTestFlow.firstOrNull() ?: return null
var newMessage = entry.message
with(raCoronaTest) {
withValidName(firstName) { firstName ->
newMessage = newMessage.replace(firstName, "RATest/FirstName")
}
withValidName(lastName) { lastName ->
newMessage = newMessage.replace(lastName, "RATest/LastName")
}
val dateOfBirthString = dateOfBirth?.toString(dayOfBirthFormatter) ?: return@with
newMessage = newMessage.replace(dateOfBirthString, "RATest/DateOfBirth")
}
return entry.toNewLogLineIfDifferent(newMessage)
}
}
| 0 | Kotlin | 1 | 0 | ee69ea77f5a010e21c94c14b230581cbd88dfb7e | 2,213 | ostanizdrav-demo-android | Apache License 2.0 |
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/KotlinJUnit5ConverterInspectionTest.kt | sapuser2017 | 393,544,264 | true | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInspection.tests.JUnit5ConverterInspectionTestBase
import com.intellij.jvm.analysis.JvmAnalysisKtTestsUtil
class KotlinJUnit5ConverterInspectionTest : JUnit5ConverterInspectionTestBase() {
override val fileExt: String = "kt"
override fun getBasePath() = JvmAnalysisKtTestsUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH + "/codeInspection/junit5converter"
fun `test qualified conversion`() {
doConversionTest("Qualified")
}
fun `test unqualified conversion`() {
doConversionTest("UnQualified")
}
fun `test expected on test annotation`() {
doQfUnavailableTest("ExpectedOnTestAnnotation", JvmAnalysisBundle.message("jvm.inspections.junit5.converter.quickfix"))
}
} | 0 | null | 0 | 0 | 4d9b4f94c08778ebf662968242ab198a6b7da703 | 956 | intellij-community | Apache License 2.0 |
idea/testData/debugger/tinyApp/src/evaluate/singleBreakpoint/extraVariables/evProperty.kt | JakeWharton | 99,388,807 | true | null | package evProperty
class A {
var prop = 1
}
fun main(args: Array<String>) {
val a = A()
//Breakpoint!
if (a.prop == 1) {
}
}
// PRINT_FRAME | 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 163 | kotlin | Apache License 2.0 |
generate-liquibase-kwrapper/src/main/kotlin/commandOptions/LiquibaseCommandOptions.kt | momosetkn | 856,934,701 | false | {"Kotlin": 55602} | package momosetkn.liquibase
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
interface LiquibaseOptions {
fun serialize(): List<String>
}
@Suppress("LargeClass", "TooManyFunctions")
data class LiquibaseInfoOptions0(
val help: Boolean? = null,
val version: Boolean? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
help?.let { "-h=$it" },
version?.let { "-v=$it" },
)
}
}
data class LiquibaseGlobalOptions(
val allowDuplicatedChangesetIdentifiers: Boolean? = null,
val alwaysDropInsteadOfReplace: Boolean? = null,
val alwaysOverrideStoredLogicSchema: String? = null,
val autoReorg: Boolean? = null,
val changelogLockPollRate: Int? = null,
val changelogLockWaitTimeInMinutes: Int? = null,
val changelogParseMode: String? = null,
val classpath: String? = null,
val convertDataTypes: Boolean? = null,
val databaseChangelogLockTableName: String? = null,
val databaseChangelogTableName: String? = null,
val databaseClass: String? = null,
val ddlLockTimeout: Int? = null,
val defaultsFile: String? = null,
val diffColumnOrder: Boolean? = null,
val driver: String? = null,
val driverPropertiesFile: String? = null,
val duplicateFileMode: String? = null,
val errorOnCircularIncludeAll: Boolean? = null,
val fileEncoding: String? = null,
val generateChangesetCreatedValues: Boolean? = null,
val generatedChangesetIdsContainsDescription: String? = null,
val headless: String? = null,
val includeCatalogInSpecification: Boolean? = null,
val includeRelationsForComputedColumns: Boolean? = null,
val includeSystemClasspath: Boolean? = null,
val licenseKey: String? = null,
val liquibaseCatalogName: String? = null,
val liquibaseSchemaName: String? = null,
val liquibaseTablespaceName: String? = null,
val logChannels: String? = null,
val logFile: String? = null,
val logFormat: String? = null,
val logLevel: String? = null,
val mirrorConsoleMessagesToLog: Boolean? = null,
val missingPropertyMode: String? = null,
val monitorPerformance: Boolean? = null,
val onMissingIncludeChangelog: String? = null,
val outputFile: String? = null,
val outputFileEncoding: String? = null,
val outputLineSeparator: String? = null,
val preserveSchemaCase: Boolean? = null,
val proGlobalEndDelimiter: String? = null,
val proGlobalEndDelimiterPrioritized: Boolean? = null,
val proMarkUnusedNotDrop: Boolean? = null,
val proSqlInline: Boolean? = null,
val proStrict: Boolean? = null,
val proSynonymsDropPublic: Boolean? = null,
val promptForNonLocalDatabase: Boolean? = null,
val propertyProviderClass: String? = null,
val searchPath: String? = null,
val secureParsing: Boolean? = null,
val shouldRun: Boolean? = null,
val shouldSnapshotData: Boolean? = null,
val showBanner: Boolean? = null,
val sqlLogLevel: String? = null,
val sqlShowSqlWarnings: Boolean? = null,
val strict: Boolean? = null,
val supportPropertyEscaping: Boolean? = null,
val supportsMethodValidationLevel: String? = null,
val trimLoadDataFileHeader: Boolean? = null,
val uiService: String? = null,
val useProcedureSchema: Boolean? = null,
val validateXmlChangelogFiles: Boolean? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
allowDuplicatedChangesetIdentifiers?.let { "--allow-duplicated-changeset-identifiers=$it" },
alwaysDropInsteadOfReplace?.let { "--always-drop-instead-of-replace=$it" },
alwaysOverrideStoredLogicSchema?.let { "--always-override-stored-logic-schema=$it" },
autoReorg?.let { "--auto-reorg=$it" },
changelogLockPollRate?.let { "--changelog-lock-poll-rate=$it" },
changelogLockWaitTimeInMinutes?.let { "--changelog-lock-wait-time-in-minutes=$it" },
changelogParseMode?.let { "--changelog-parse-mode=$it" },
classpath?.let { "--classpath=$it" },
convertDataTypes?.let { "--convert-data-types=$it" },
databaseChangelogLockTableName?.let { "--database-changelog-lock-table-name=$it" },
databaseChangelogTableName?.let { "--database-changelog-table-name=$it" },
databaseClass?.let { "--database-class=$it" },
ddlLockTimeout?.let { "--ddl-lock-timeout=$it" },
defaultsFile?.let { "--defaults-file=$it" },
diffColumnOrder?.let { "--diff-column-order=$it" },
driver?.let { "--driver=$it" },
driverPropertiesFile?.let { "--driver-properties-file=$it" },
duplicateFileMode?.let { "--duplicate-file-mode=$it" },
errorOnCircularIncludeAll?.let { "--error-on-circular-include-all=$it" },
fileEncoding?.let { "--file-encoding=$it" },
generateChangesetCreatedValues?.let { "--generate-changeset-created-values=$it" },
generatedChangesetIdsContainsDescription?.let { "--generated-changeset-ids-contains-description=$it" },
headless?.let { "--headless=$it" },
includeCatalogInSpecification?.let { "--include-catalog-in-specification=$it" },
includeRelationsForComputedColumns?.let { "--include-relations-for-computed-columns=$it" },
includeSystemClasspath?.let { "--include-system-classpath=$it" },
licenseKey?.let { "--license-key=$it" },
liquibaseCatalogName?.let { "--liquibase-catalog-name=$it" },
liquibaseSchemaName?.let { "--liquibase-schema-name=$it" },
liquibaseTablespaceName?.let { "--liquibase-tablespace-name=$it" },
logChannels?.let { "--log-channels=$it" },
logFile?.let { "--log-file=$it" },
logFormat?.let { "--log-format=$it" },
logLevel?.let { "--log-level=$it" },
mirrorConsoleMessagesToLog?.let { "--mirror-console-messages-to-log=$it" },
missingPropertyMode?.let { "--missing-property-mode=$it" },
monitorPerformance?.let { "--monitor-performance=$it" },
onMissingIncludeChangelog?.let { "--on-missing-include-changelog=$it" },
outputFile?.let { "--output-file=$it" },
outputFileEncoding?.let { "--output-file-encoding=$it" },
outputLineSeparator?.let { "--output-line-separator=$it" },
preserveSchemaCase?.let { "--preserve-schema-case=$it" },
proGlobalEndDelimiter?.let { "--pro-global-end-delimiter=$it" },
proGlobalEndDelimiterPrioritized?.let { "--pro-global-end-delimiter-prioritized=$it" },
proMarkUnusedNotDrop?.let { "--pro-mark-unused-not-drop=$it" },
proSqlInline?.let { "--pro-sql-inline=$it" },
proStrict?.let { "--pro-strict=$it" },
proSynonymsDropPublic?.let { "--pro-synonyms-drop-public=$it" },
promptForNonLocalDatabase?.let { "--prompt-for-non-local-database=$it" },
propertyProviderClass?.let { "--property-provider-class=$it" },
searchPath?.let { "--search-path=$it" },
secureParsing?.let { "--secure-parsing=$it" },
shouldRun?.let { "--should-run=$it" },
shouldSnapshotData?.let { "--should-snapshot-data=$it" },
showBanner?.let { "--show-banner=$it" },
sqlLogLevel?.let { "--sql-log-level=$it" },
sqlShowSqlWarnings?.let { "--sql-show-sql-warnings=$it" },
strict?.let { "--strict=$it" },
supportPropertyEscaping?.let { "--support-property-escaping=$it" },
supportsMethodValidationLevel?.let { "--supports-method-validation-level=$it" },
trimLoadDataFileHeader?.let { "--trim-load-data-file-header=$it" },
uiService?.let { "--ui-service=$it" },
useProcedureSchema?.let { "--use-procedure-schema=$it" },
validateXmlChangelogFiles?.let { "--validate-xml-changelog-files=$it" },
)
}
}
data class LiquibaseDbclhistoryOptions(
// options
val dbclhistoryCaptureExtensions: Boolean? = null,
val dbclhistoryCaptureSql: Boolean? = null,
val dbclhistoryEnabled: Boolean? = null,
val dbclhistorySeverity: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
dbclhistoryCaptureExtensions?.let { "--dbclhistory-capture-extensions=$it" },
dbclhistoryCaptureSql?.let { "--dbclhistory-capture-sql=$it" },
dbclhistoryEnabled?.let { "--dbclhistory-enabled=$it" },
dbclhistorySeverity?.let { "--dbclhistory-severity=$it" },
)
}
}
data class LiquibaseExecutorsOptions(
// options
val psqlArgs: String? = null,
val psqlKeepTemp: Boolean? = null,
val psqlKeepTempName: String? = null,
val psqlKeepTempPath: String? = null,
val psqlLogFile: String? = null,
val psqlPath: String? = null,
val psqlTimeout: Int? = null,
val sqlcmdArgs: String? = null,
val sqlcmdCatalogName: String? = null,
val sqlcmdKeepTemp: Boolean? = null,
val sqlcmdKeepTempName: String? = null,
val sqlcmdKeepTempOverwrite: Boolean? = null,
val sqlcmdKeepTempPath: String? = null,
val sqlcmdLogFile: String? = null,
val sqlcmdPath: String? = null,
val sqlcmdTimeout: Int? = null,
val sqlplusArgs: String? = null,
val sqlplusCreateSpool: Boolean? = null,
val sqlplusKeepTemp: Boolean? = null,
val sqlplusKeepTempName: String? = null,
val sqlplusKeepTempOverwrite: Boolean? = null,
val sqlplusKeepTempPath: String? = null,
val sqlplusPassword: String? = null,
val sqlplusPath: String? = null,
val sqlplusSqlerror: String? = null,
val sqlplusTimeout: Int? = null,
val sqlplusUsername: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
psqlArgs?.let { "--psql-args=$it" },
psqlKeepTemp?.let { "--psql-keep-temp=$it" },
psqlKeepTempName?.let { "--psql-keep-temp-name=$it" },
psqlKeepTempPath?.let { "--psql-keep-temp-path=$it" },
psqlLogFile?.let { "--psql-log-file=$it" },
psqlPath?.let { "--psql-path=$it" },
psqlTimeout?.let { "--psql-timeout=$it" },
sqlcmdArgs?.let { "--sqlcmd-args=$it" },
sqlcmdCatalogName?.let { "--sqlcmd-catalog-name=$it" },
sqlcmdKeepTemp?.let { "--sqlcmd-keep-temp=$it" },
sqlcmdKeepTempName?.let { "--sqlcmd-keep-temp-name=$it" },
sqlcmdKeepTempOverwrite?.let { "--sqlcmd-keep-temp-overwrite=$it" },
sqlcmdKeepTempPath?.let { "--sqlcmd-keep-temp-path=$it" },
sqlcmdLogFile?.let { "--sqlcmd-log-file=$it" },
sqlcmdPath?.let { "--sqlcmd-path=$it" },
sqlcmdTimeout?.let { "--sqlcmd-timeout=$it" },
sqlplusArgs?.let { "--sqlplus-args=$it" },
sqlplusCreateSpool?.let { "--sqlplus-create-spool=$it" },
sqlplusKeepTemp?.let { "--sqlplus-keep-temp=$it" },
sqlplusKeepTempName?.let { "--sqlplus-keep-temp-name=$it" },
sqlplusKeepTempOverwrite?.let { "--sqlplus-keep-temp-overwrite=$it" },
sqlplusKeepTempPath?.let { "--sqlplus-keep-temp-path=$it" },
sqlplusPassword?.let { "--sqlplus-password=$it" },
sqlplusPath?.let { "--sqlplus-path=$it" },
sqlplusSqlerror?.let { "--sqlplus-sqlerror=$it" },
sqlplusTimeout?.let { "--sqlplus-timeout=$it" },
sqlplusUsername?.let { "--sqlplus-username=$it" },
)
}
}
data class LiquibaseCustomLoggingOptions(
// options
val customLogDataFile: String? = null,
val customLogDataFrequency: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
customLogDataFile?.let { "--custom-log-data-file=$it" },
customLogDataFrequency?.let { "--custom-log-data-frequency=$it" },
)
}
}
data class LiquibaseExtensionsOptions(
// options
val dynamodbTrackingTablesBillingMode: String? = null,
val dynamodbTrackingTablesProvisionedThroughputReadCapacityUnits: Int? = null,
val dynamodbTrackingTablesProvisionedThroughputWriteCapacityUnits: Int? = null,
val dynamodbWaitersEnabled: Boolean? = null,
val dynamodbWaitersFailOnTimeout: Boolean? = null,
val dynamodbWaitersLogNotificationEnabled: Boolean? = null,
val dynamodbWaitersLogNotificationInterval: Int? = null,
val dynamodbWaiterCreateFixedDelayBackoffStrategyDuration: Int? = null,
val dynamodbWaiterCreateMaxAttempts: Int? = null,
val dynamodbWaiterCreateTotalTimeout: Int? = null,
val dynamodbWaiterDeleteFixedDelayBackoffStrategyDuration: Int? = null,
val dynamodbWaiterDeleteMaxAttempts: Int? = null,
val dynamodbWaiterDeleteTotalTimeout: Int? = null,
val dynamodbWaiterUpdateFixedDelayBackoffStrategyDuration: Int? = null,
val dynamodbWaiterUpdateMaxAttempts: Int? = null,
val dynamodbWaiterUpdateTotalTimeout: Int? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
dynamodbTrackingTablesBillingMode?.let { "--dynamodb-tracking-tables-billing-mode=$it" },
dynamodbTrackingTablesProvisionedThroughputReadCapacityUnits?.let { "--dynamodb-tracking-tables-provisioned-throughput-read-capacity-units=$it" },
dynamodbTrackingTablesProvisionedThroughputWriteCapacityUnits?.let { "--dynamodb-tracking-tables-provisioned-throughput-write-capacity-units=$it" },
dynamodbWaitersEnabled?.let { "--dynamodb-waiters-enabled=$it" },
dynamodbWaitersFailOnTimeout?.let { "--dynamodb-waiters-fail-on-timeout=$it" },
dynamodbWaitersLogNotificationEnabled?.let { "--dynamodb-waiters-log-notification-enabled=$it" },
dynamodbWaitersLogNotificationInterval?.let { "--dynamodb-waiters-log-notification-interval=$it" },
dynamodbWaiterCreateFixedDelayBackoffStrategyDuration?.let { "--dynamodb-waiter-create-fixed-delay-backoff-strategy-duration=$it" },
dynamodbWaiterCreateMaxAttempts?.let { "--dynamodb-waiter-create-max-attempts=$it" },
dynamodbWaiterCreateTotalTimeout?.let { "--dynamodb-waiter-create-total-timeout=$it" },
dynamodbWaiterDeleteFixedDelayBackoffStrategyDuration?.let { "--dynamodb-waiter-delete-fixed-delay-backoff-strategy-duration=$it" },
dynamodbWaiterDeleteMaxAttempts?.let { "--dynamodb-waiter-delete-max-attempts=$it" },
dynamodbWaiterDeleteTotalTimeout?.let { "--dynamodb-waiter-delete-total-timeout=$it" },
dynamodbWaiterUpdateFixedDelayBackoffStrategyDuration?.let { "--dynamodb-waiter-update-fixed-delay-backoff-strategy-duration=$it" },
dynamodbWaiterUpdateMaxAttempts?.let { "--dynamodb-waiter-update-max-attempts=$it" },
dynamodbWaiterUpdateTotalTimeout?.let { "--dynamodb-waiter-update-total-timeout=$it" },
)
}
}
data class LiquibaseMongoDBOptions(
// options
val adjustTrackingTablesOnStartup: Boolean? = null,
val retryWrites: Boolean? = null,
val supportsValidator: Boolean? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
adjustTrackingTablesOnStartup?.let { "--adjust-tracking-tables-on-startup=$it" },
retryWrites?.let { "--retry-writes=$it" },
supportsValidator?.let { "--supports-validator=$it" },
)
}
}
data class LiquibaseConfigurationOptions(
// options
val liquibaseHome: String? = null,
val liquibaseLauncherDebug: String? = null,
val liquibaseLauncherParentClassloader: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
liquibaseHome?.let { "liquibase.home=$it" },
liquibaseLauncherDebug?.let { "liquibase.launcher.debug=$it" },
liquibaseLauncherParentClassloader?.let { "liquibase.launcher.parent.classloader=$it" },
)
}
}
data class LiquibaseConnectionOptions(
// options
val changelogFile: String? = null,
val driver: String? = null,
val driverPropertiesFile: String? = null,
val password: String? = null,
val referenceDefaultCatalogName: String? = null,
val referenceDefaultSchemaName: String? = null,
val referenceDriver: String? = null,
val referenceDriverPropertiesFile: String? = null,
val referencePassword: String? = null,
val referenceSchemas: String? = null,
val referenceUrl: String? = null,
val referenceUsername: String? = null,
val url: String? = null,
val username: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
changelogFile?.let { "--changelog-file=$it" },
driver?.let { "--driver=$it" },
driverPropertiesFile?.let { "--driver-properties-file=$it" },
password?.let { "--password=$it" },
referenceDefaultCatalogName?.let { "--reference-default-catalog-name=$it" },
referenceDefaultSchemaName?.let { "--reference-default-schema-name=$it" },
referenceDriver?.let { "--reference-driver=$it" },
referenceDriverPropertiesFile?.let { "--reference-driver-properties-file=$it" },
referencePassword?.let { "--reference-password=$it" },
referenceSchemas?.let { "--reference-schemas=$it" },
referenceUrl?.let { "--reference-url=$it" },
referenceUsername?.let { "--reference-username=$it" },
url?.let { "--url=$it" },
username?.let { "--username=$it" },
)
}
}
data class LiquibaseInitOptions(
// options
val recursive: Boolean? = null,
val source: String? = null,
val target: String? = null,
val changelogFile: String? = null,
val format: String? = null,
val keepTempFiles: Boolean? = null,
val projectDefaultsFile: String? = null,
val projectDir: String? = null,
val projectGuide: String? = null,
val url: String? = null,
val bindAddress: String? = null,
val dbPort: String? = null,
val launchBrowser: Boolean? = null,
val password: String? = null,
val username: String? = null,
val webPort: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
recursive?.let { "--recursive=$it" },
source?.let { "--source=$it" },
target?.let { "--target=$it" },
changelogFile?.let { "--changelog-file=$it" },
format?.let { "--format=$it" },
keepTempFiles?.let { "--keep-temp-files=$it" },
projectDefaultsFile?.let { "--project-defaults-file=$it" },
projectDir?.let { "--project-dir=$it" },
projectGuide?.let { "--project-guide=$it" },
url?.let { "--url=$it" },
bindAddress?.let { "--bind-address=$it" },
dbPort?.let { "--db-port=$it" },
launchBrowser?.let { "--launch-browser=$it" },
password?.let { <PASSWORD>" },
username?.let { "--username=$it" },
webPort?.let { "--web-port=$it" },
)
}
}
data class LiquibaseFlowFilesOptions(
// options
val flowFile: String? = null,
val flowFileStrictParsing: Boolean? = null,
val flowShellInterpreter: String? = null,
val flowShellKeepTempFiles: Boolean? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
flowFile?.let { "--flow-file=$it" },
flowFileStrictParsing?.let { "--flow-file-strict-parsing=$it" },
flowShellInterpreter?.let { "--flow-shell-interpreter=$it" },
flowShellKeepTempFiles?.let { "--flow-shell-keep-temp-files=$it" },
)
}
}
data class LiquibasePolicyChecksOptions(
// options
val autoEnableNewChecks: Boolean? = null,
val autoUpdate: String? = null,
val cacheChangelogFileContents: Boolean? = null,
val changelogFile: String? = null,
val changesetFilter: String? = null,
val checkName: String? = null,
val checkRollbacks: String? = null,
val checkStatus: String? = null,
val checksOutput: String? = null,
val checksPackages: String? = null,
val checksScope: String? = null,
val checksSettingsFile: String? = null,
val disable: Boolean? = null,
val enable: Boolean? = null,
val force: Boolean? = null,
val format: String? = null,
val packageContents: String? = null,
val packageFile: String? = null,
val packageName: String? = null,
val propertySubstitutionEnabled: Boolean? = null,
val schemas: String? = null,
val severity: String? = null,
val showCols: String? = null,
val sqlParserFailSeverity: String? = null,
val url: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
autoEnableNewChecks?.let { "--auto-enable-new-checks=$it" },
autoUpdate?.let { "--auto-update=$it" },
cacheChangelogFileContents?.let { "--cache-changelog-file-contents=$it" },
changelogFile?.let { "--changelog-file=$it" },
changesetFilter?.let { "--changeset-filter=$it" },
checkName?.let { "--check-name=$it" },
checkRollbacks?.let { "--check-rollbacks=$it" },
checkStatus?.let { "--check-status=$it" },
checksOutput?.let { "--checks-output=$it" },
checksPackages?.let { "--checks-packages=$it" },
checksScope?.let { "--checks-scope=$it" },
checksSettingsFile?.let { "--checks-settings-file=$it" },
disable?.let { "--disable=$it" },
enable?.let { "--enable=$it" },
force?.let { "--force=$it" },
format?.let { "--format=$it" },
packageContents?.let { "--package-contents=$it" },
packageFile?.let { "--package-file=$it" },
packageName?.let { "--package-name=$it" },
propertySubstitutionEnabled?.let { "--property-substitution-enabled=$it" },
schemas?.let { "--schemas=$it" },
severity?.let { "--severity=$it" },
showCols?.let { "--show-cols=$it" },
sqlParserFailSeverity?.let { "--sql-parser-fail-severity=$it" },
url?.let { "--url=$it" },
)
}
}
data class LiquibaseOperationReportsOptions(
// options
val driftSeverity: String? = null,
val driftSeverityChanged: String? = null,
val driftSeverityMissing: String? = null,
val driftSeverityUnexpected: String? = null,
val openReport: Boolean? = null,
val reportEnabled: Boolean? = null,
val reportName: String? = null,
val reportPath: String? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
driftSeverity?.let { "--drift-severity=$it" },
driftSeverityChanged?.let { "--drift-severity-changed=$it" },
driftSeverityMissing?.let { "--drift-severity-missing=$it" },
driftSeverityUnexpected?.let { "--drift-severity-unexpected=$it" },
openReport?.let { "--open-report=$it" },
reportEnabled?.let { "--report-enabled=$it" },
reportName?.let { "--report-name=$it" },
reportPath?.let { "--report-path=$it" },
)
}
}
data class LiquibaseGeneralOptions(
// options
val addRow: Boolean? = null,
val changeExecListenerClass: String? = null,
val changeExecListenerPropertiesFile: String? = null,
val changesetAuthor: String? = null,
val changesetId: String? = null,
val changesetIdentifier: String? = null,
val changesetPath: String? = null,
val contextFilter: String? = null,
val count: Int? = null,
val dataOutputDirectory: String? = null,
val date: TemporalAccessor? = null,
val dropDbclhistory: Boolean? = null,
val dbms: String? = null,
val defaultCatalogName: String? = null,
val defaultSchemaName: String? = null,
val diffTypes: String? = null,
val dropAllRequireForce: Boolean? = null,
val excludeObjects: String? = null,
val forceOnPartialChanges: Boolean? = null,
val includeCatalog: Boolean? = null,
val includeObjects: String? = null,
val includeSchema: Boolean? = null,
val includeTablespace: Boolean? = null,
val labels: String? = null,
val outputDirectory: String? = null,
val outputSchemas: String? = null,
val overwriteOutputFile: Boolean? = null,
val referenceLiquibaseCatalogName: String? = null,
val referenceLiquibaseSchemaName: String? = null,
val replaceIfExistsTypes: String? = null,
val rollbackOnError: Boolean? = null,
val rollbackScript: String? = null,
val runOnChangeTypes: String? = null,
val schemas: String? = null,
val showSummary: String? = null,
val showSummaryOutput: String? = null,
val skipObjectSorting: Boolean? = null,
val snapshotFilters: String? = null,
val snapshotFormat: String? = null,
val sql: String? = null,
val sqlFile: String? = null,
val tag: String? = null,
val tagVersion: String? = null,
val verbose: Boolean? = null,
) : LiquibaseOptions {
override fun serialize(): List<String> {
return listOfNotNull(
addRow?.let { "--add-row=$it" },
changeExecListenerClass?.let { "--change-exec-listener-class=$it" },
changeExecListenerPropertiesFile?.let { "--change-exec-listener-properties-file=$it" },
changesetAuthor?.let { "--changeset-author=$it" },
changesetId?.let { "--changeset-id=$it" },
changesetIdentifier?.let { "--changeset-identifier=$it" },
changesetPath?.let { "--changeset-path=$it" },
contextFilter?.let { "--context-filter=$it" },
count?.let { "--count=$it" },
dataOutputDirectory?.let { "--data-output-directory=$it" },
date?.let { "--date=${DateTimeFormatter.ISO_DATE_TIME.format(it)}" },
dropDbclhistory?.let { "--drop-dbclhistory=$it" },
dbms?.let { "--dbms=$it" },
defaultCatalogName?.let { "--default-catalog-name=$it" },
defaultSchemaName?.let { "--default-schema-name=$it" },
diffTypes?.let { "--diff-types=$it" },
dropAllRequireForce?.let { "--drop-all-require-force=$it" },
excludeObjects?.let { "--exclude-objects=$it" },
forceOnPartialChanges?.let { "--force-on-partial-changes=$it" },
includeCatalog?.let { "--include-catalog=$it" },
includeObjects?.let { "--include-objects=$it" },
includeSchema?.let { "--include-schema=$it" },
includeTablespace?.let { "--include-tablespace=$it" },
labels?.let { "--labels=$it" },
outputDirectory?.let { "--output-directory=$it" },
outputSchemas?.let { "--output-schemas=$it" },
overwriteOutputFile?.let { "--overwrite-output-file=$it" },
referenceLiquibaseCatalogName?.let { "--reference-liquibase-catalog-name=$it" },
referenceLiquibaseSchemaName?.let { "--reference-liquibase-schema-name=$it" },
replaceIfExistsTypes?.let { "--replace-if-exists-types=$it" },
rollbackOnError?.let { "--rollback-on-error=$it" },
rollbackScript?.let { "--rollback-script=$it" },
runOnChangeTypes?.let { "--run-on-change-types=$it" },
schemas?.let { "--schemas=$it" },
showSummary?.let { "--show-summary=$it" },
showSummaryOutput?.let { "--show-summary-output=$it" },
skipObjectSorting?.let { "--skip-object-sorting=$it" },
snapshotFilters?.let { "--snapshot-filters=$it" },
snapshotFormat?.let { "--snapshot-format=$it" },
sql?.let { "--sql=$it" },
sqlFile?.let { "--sql-file=$it" },
tag?.let { "--tag=$it" },
tagVersion?.let { "--tag-version=$it" },
verbose?.let { "--verbose=$it" },
)
}
}
| 0 | Kotlin | 0 | 0 | e1ef752993c959d4c7b2851854513061d9ca0a86 | 28,441 | develop-liquibase-kotlin | Apache License 2.0 |
common/src/commonMain/kotlin/nl/vanparerensoftwaredevelopment/saltthepassmanager/common/screens/loading/LoadingScreen.kt | EwoudVanPareren | 682,550,040 | false | {"Kotlin": 151184} | package nl.vanparerensoftwaredevelopment.saltthepassmanager.common.screens.loading
import androidx.compose.foundation.Image
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import dev.icerock.moko.resources.compose.painterResource
import nl.vanparerensoftwaredevelopment.saltthepassmanager.common.config.Configuration
import nl.vanparerensoftwaredevelopment.saltthepassmanager.common.config.LocalAppConfiguration
import nl.vanparerensoftwaredevelopment.saltedpassmanager.resources.MR
/**
* A general purpose loading screen.
*
* This is not a Voyager-library style screen, but rather a screen-sized UI component.
*/
@Composable
fun LoadingScreen(overrideDarkMode: Boolean? = null) {
Scaffold { paddingValues ->
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(paddingValues).fillMaxSize(1f)
) {
val useLightIcon = overrideDarkMode ?: when (LocalAppConfiguration.current.theme) {
Configuration.Theme.LIGHT -> false
Configuration.Theme.DARK -> true
Configuration.Theme.SYSTEM -> isSystemInDarkTheme()
}
Image(
painter = painterResource(if (useLightIcon) {
MR.images.icon_tray_light
} else {
MR.images.icon_tray_dark
}),
contentDescription = null,
modifier = Modifier
.fillMaxSize(0.5f)
.aspectRatio(1f)
)
}
}
} | 8 | Kotlin | 0 | 0 | 8a5dc25b80ef52e66fcac928114ffa2a5a2a20e8 | 1,915 | SaltThePassManager | MIT License |
app/src/main/java/app/airsignal/weather/view/dialog/SideMenuBuilder.kt | tekken5953 | 611,614,821 | false | {"Kotlin": 418472, "Java": 2615} | package app.airsignal.weather.view.dialog
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.net.Uri
import android.util.DisplayMetrics
import android.view.*
import android.widget.*
import androidx.core.content.res.ResourcesCompat
import app.airsignal.weather.R
import app.airsignal.weather.db.sp.GetAppInfo
import app.airsignal.weather.db.sp.SetSystemInfo
import app.airsignal.weather.db.sp.SpDao
import com.bumptech.glide.Glide
/**
* @author : <NAME>
* @since : 2023-05-11 오전 11:55
**/
class SideMenuBuilder(private val context: Context) {
private var builder: AlertDialog.Builder =
AlertDialog.Builder(context, R.style.DialogAnimationMenu)
private lateinit var alertDialog: AlertDialog
init { setFontScale() }
/** 다이얼로그 뒤로가기 버튼 리스너 등록 **/
fun setBackPressed(imageView: View): SideMenuBuilder {
imageView.setOnClickListener { dismiss() }
return this
}
/** 다이얼로그 뷰 소멸 **/
fun dismiss() { if (alertDialog.isShowing) alertDialog.dismiss() }
/** 다이얼로그 뷰 갱신 **/
fun show(v: View, cancelable: Boolean): AlertDialog {
v.let {
if (v.parent != null) (v.parent as ViewGroup).removeView(v)
builder.setView(v).setCancelable(cancelable)
alertDialog = builder.create()
attributeDialog()
alertDialog.show()
}
return alertDialog
}
// 로그인 정보 반환
fun setUserData(profile: ImageView, id: TextView): SideMenuBuilder {
Glide.with(context)
.load(Uri.parse(GetAppInfo.getUserProfileImage(context)))
.error(ResourcesCompat.getDrawable(context.resources,R.mipmap.ic_launcher_round,null))
.into(profile)
val email = GetAppInfo.getUserEmail(context)
id.text = if (email != "") email else context.getString(R.string.please_login)
return this
}
// 폰트 크기 반환
private fun setFontScale(): SideMenuBuilder {
when (GetAppInfo.getUserFontScale(context)) {
SpDao.TEXT_SCALE_SMALL -> SetSystemInfo.setTextSizeSmall(builder.context)
SpDao.TEXT_SCALE_BIG -> SetSystemInfo.setTextSizeLarge(builder.context)
else -> SetSystemInfo.setTextSizeDefault(builder.context)
}
return this
}
// 바텀 다이얼로그 가로 비율 설정
private fun attributeDialog() {
val params: WindowManager.LayoutParams? = alertDialog.window?.attributes
params?.let {
it.width = getBottomSheetDialogDefaultWidth(75)
it.gravity = Gravity.START
it.windowAnimations = R.style.DialogAnimationMenuAnim // 열기 & 닫기 시 애니메이션 설정
}
alertDialog.window?.attributes = params
}
// 바텀 다이얼로그 세로 비율 설정
private fun getBottomSheetDialogDefaultWidth(per: Int): Int = getWindowWidth() * per / 100
// 디바이스 넓이 구하기
private fun getWindowWidth(): Int {
val displayMetrics = DisplayMetrics() // 디바이스의 width 를 구한다
@Suppress("DEPRECATION")
if (context is Activity) context.windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics.widthPixels
}
} | 0 | Kotlin | 1 | 1 | 36011d3ad2bdc9e0a7f02007de9b65557639da22 | 3,158 | AS_Cloud_App | Open Market License |
app/src/main/java/app/airsignal/weather/view/dialog/SideMenuBuilder.kt | tekken5953 | 611,614,821 | false | {"Kotlin": 418472, "Java": 2615} | package app.airsignal.weather.view.dialog
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.net.Uri
import android.util.DisplayMetrics
import android.view.*
import android.widget.*
import androidx.core.content.res.ResourcesCompat
import app.airsignal.weather.R
import app.airsignal.weather.db.sp.GetAppInfo
import app.airsignal.weather.db.sp.SetSystemInfo
import app.airsignal.weather.db.sp.SpDao
import com.bumptech.glide.Glide
/**
* @author : <NAME>
* @since : 2023-05-11 오전 11:55
**/
class SideMenuBuilder(private val context: Context) {
private var builder: AlertDialog.Builder =
AlertDialog.Builder(context, R.style.DialogAnimationMenu)
private lateinit var alertDialog: AlertDialog
init { setFontScale() }
/** 다이얼로그 뒤로가기 버튼 리스너 등록 **/
fun setBackPressed(imageView: View): SideMenuBuilder {
imageView.setOnClickListener { dismiss() }
return this
}
/** 다이얼로그 뷰 소멸 **/
fun dismiss() { if (alertDialog.isShowing) alertDialog.dismiss() }
/** 다이얼로그 뷰 갱신 **/
fun show(v: View, cancelable: Boolean): AlertDialog {
v.let {
if (v.parent != null) (v.parent as ViewGroup).removeView(v)
builder.setView(v).setCancelable(cancelable)
alertDialog = builder.create()
attributeDialog()
alertDialog.show()
}
return alertDialog
}
// 로그인 정보 반환
fun setUserData(profile: ImageView, id: TextView): SideMenuBuilder {
Glide.with(context)
.load(Uri.parse(GetAppInfo.getUserProfileImage(context)))
.error(ResourcesCompat.getDrawable(context.resources,R.mipmap.ic_launcher_round,null))
.into(profile)
val email = GetAppInfo.getUserEmail(context)
id.text = if (email != "") email else context.getString(R.string.please_login)
return this
}
// 폰트 크기 반환
private fun setFontScale(): SideMenuBuilder {
when (GetAppInfo.getUserFontScale(context)) {
SpDao.TEXT_SCALE_SMALL -> SetSystemInfo.setTextSizeSmall(builder.context)
SpDao.TEXT_SCALE_BIG -> SetSystemInfo.setTextSizeLarge(builder.context)
else -> SetSystemInfo.setTextSizeDefault(builder.context)
}
return this
}
// 바텀 다이얼로그 가로 비율 설정
private fun attributeDialog() {
val params: WindowManager.LayoutParams? = alertDialog.window?.attributes
params?.let {
it.width = getBottomSheetDialogDefaultWidth(75)
it.gravity = Gravity.START
it.windowAnimations = R.style.DialogAnimationMenuAnim // 열기 & 닫기 시 애니메이션 설정
}
alertDialog.window?.attributes = params
}
// 바텀 다이얼로그 세로 비율 설정
private fun getBottomSheetDialogDefaultWidth(per: Int): Int = getWindowWidth() * per / 100
// 디바이스 넓이 구하기
private fun getWindowWidth(): Int {
val displayMetrics = DisplayMetrics() // 디바이스의 width 를 구한다
@Suppress("DEPRECATION")
if (context is Activity) context.windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics.widthPixels
}
} | 0 | Kotlin | 1 | 1 | 36011d3ad2bdc9e0a7f02007de9b65557639da22 | 3,158 | AS_Cloud_App | Open Market License |
src/main/kotlin/data/entity/Response.kt | iammohdzaki | 427,616,642 | false | null | package data.entity
/**
Created by Mohammad Zaki
on Nov,13 2021
**/
data class Response(
var password : String = "",
var strengthResult: StrengthResult
)
| 0 | Kotlin | 1 | 0 | 5567ef4b768b7fb9b1d1189dad79fb87d555c0b5 | 164 | Password-Generator | The Unlicense |
app/src/main/java/com/chillibits/pmapp/tool/SimpleAnimationListener.kt | chillibits | 115,863,331 | false | null | /*
* Copyright © <NAME> 2017 - 2020. All rights reserved
*/
package com.chillibits.pmapp.tool
import android.view.animation.Animation
open class SimpleAnimationListener : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
} | 24 | null | 5 | 9 | fafdf73e03f2ea67769bf67cc0433997d516d66c | 383 | particulate-matter-app | MIT License |
core/src/commonMain/kotlin/com.chrynan.graphkl/language/parser/usecase/extension/ParseTypeSystemExtensionUseCase.kt | chRyNaN | 230,310,677 | false | null | package com.chrynan.graphkl.language.parser.usecase.extension
import com.chrynan.graphkl.language.node.TypeSystemExtensionNode
class ParseTypeSystemExtensionUseCase {
operator fun invoke(): TypeSystemExtensionNode = TODO()
} | 0 | Kotlin | 0 | 2 | 2526cedddc0a5b5777dea0ec7fc67bc2cd16fe05 | 231 | graphkl | Apache License 2.0 |
app/src/main/java/com/kylecorry/trail_sense/weather/ui/QuickActionThermometer.kt | ebraminio | 410,687,263 | true | {"Kotlin": 1274699, "Batchfile": 179} | package com.kylecorry.trail_sense.weather.ui
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.shared.CustomUiUtils
import com.kylecorry.trail_sense.shared.QuickActionButton
class QuickActionThermometer(btn: FloatingActionButton, fragment: Fragment) :
QuickActionButton(btn, fragment) {
override fun onCreate() {
button.setImageResource(R.drawable.thermometer)
CustomUiUtils.setButtonState(button, false)
button.setOnClickListener {
fragment.findNavController()
.navigate(R.id.action_action_weather_to_thermometerFragment)
}
}
override fun onResume() {
}
override fun onPause() {
}
override fun onDestroy() {
}
} | 0 | null | 0 | 1 | a89122d4ae1172dae9cf45451cffbeeb36b384d1 | 902 | Trail-Sense | MIT License |
app/src/main/java/com/quizapp/data/datasource/remote/reset_password/ResetPasswordRemoteDataSourceImpl.kt | AhmetOcak | 591,704,302 | false | null | package com.quizapp.data.datasource.remote.reset_password
import com.quizapp.data.datasource.remote.reset_password.api.ResetPasswordApi
import com.quizapp.data.datasource.remote.reset_password.entity.ResetPasswordBodyDto
import com.quizapp.data.datasource.remote.reset_password.entity.ResetPasswordDto
import com.quizapp.data.datasource.remote.reset_password.entity.SendPasswordResetMailDto
import javax.inject.Inject
class ResetPasswordRemoteDataSourceImpl @Inject constructor(private val api: ResetPasswordApi) :
ResetPasswordRemoteDataSource {
override suspend fun resetPassword(resetPasswordDto: ResetPasswordDto, resetPasswordBody: ResetPasswordBodyDto) =
api.resetPassword(newPassword = resetPasswordBody, email = resetPasswordDto.email, token = resetPasswordDto.token)
override suspend fun sendPasswordResetMail(sendPasswordResetMailDto: SendPasswordResetMailDto) =
api.sendPasswordResetMail(email = sendPasswordResetMailDto.email)
} | 0 | Kotlin | 0 | 5 | cc9d467fcd37cc88c9bbac315bd9aae920722bac | 972 | QuizApp | MIT License |
src/Day25.kt | RusticFlare | 574,508,778 | false | null | import kotlin.math.max
private data class CarryOverState(val previousDigit: Int, val carryOver: Int) {
init {
require(previousDigit in Snafu.validDigits) { "Invalid previousValue <$previousDigit>" }
}
companion object {
val INITIAL = CarryOverState(previousDigit = 0, carryOver = 0)
}
}
private fun List<Int>.padZeros(newSize: Int) = plus(List(newSize - size) { 0 })
private data class Snafu(val digits: List<Int>) {
init {
require(digits.all { it in validDigits }) { digits }
}
operator fun plus(other: Snafu): Snafu {
val zipSize = max(digits.size, other.digits.size)
val carryOverStates = digits.padZeros(zipSize).zip(other.digits.padZeros(zipSize), transform = Int::plus)
.runningFold(CarryOverState.INITIAL) { (_, carryOver), digit ->
var value = digit + carryOver
var toCarryOver = 0
while (value !in validDigits) {
when {
value < validDigits.first -> {
value += 5
toCarryOver -= 1
}
value > validDigits.last -> {
value -= 5
toCarryOver += 1
}
}
}
CarryOverState(previousDigit = value, carryOver = toCarryOver)
}.drop(1)
return Snafu(
carryOverStates.map { it.previousDigit } + carryOverStates.last().carryOver
)
}
override fun toString(): String = digits.reversed()
.dropWhile { it == 0 }
.joinToString(separator = "") {
when (it) {
0, 1, 2 -> it.toString()
-1 -> "-"
-2 -> "="
else -> error(it)
}
}
companion object {
val validDigits = -2..2
fun parse(input: String) = Snafu(
input.reversed().map {
it.digitToIntOrNull() ?: when (it) {
'-' -> -1
'=' -> -2
else -> error(it)
}
}
)
}
}
fun main() {
fun part1(input: List<String>): String {
return input.map { Snafu.parse(it) }
.reduce(Snafu::plus)
.toString()
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day25_test")
check(part1(testInput) == "2=-1=0")
// check(part2(testInput) == 4)
val input = readLines("Day25")
with(part1(input)) {
check(this == "2-2--02=1---1200=0-1")
println(this)
}
// with(part2(input)) {
// check(this == 569)
// println(this)
// }
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 2,877 | advent-of-code-kotlin-2022 | Apache License 2.0 |
modules/core/src/main/java/de/deutschebahn/bahnhoflive/debug/InMemoryDbProvider.kt | dbbahnhoflive | 267,806,942 | false | null | package de.deutschebahn.bahnhoflive.debug
import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
abstract class ContentProviderTable(
val db: SQLiteDatabase,
val providerName: String,
val tableName: String
) {
protected val values: HashMap<String, String>? = null
// private val URL_TABLE = "content://${providerName}/${tableName}"
// val CONTENT_URI: Uri = Uri.parse(URL_TABLE)
fun getType(): String = providerName + "//" + tableName
abstract fun createQuery(queryBuilder: SQLiteQueryBuilder, sortOrder: String?): String?
abstract fun insert(values: ContentValues?): Long // returns rowID
abstract fun createInDatabase()
open fun upgradeInDatabase(oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $tableName")
createInDatabase()
}
open fun update(
values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
return db.update(
tableName,
values,
selection,
selectionArgs
)
}
open fun delete(selection: String?, selectionArgs: Array<String>?): Int {
return db.delete(tableName, selection, selectionArgs)
}
}
class ContentProviderTableValues(db:SQLiteDatabase, providerName:String, tableName:String) :
ContentProviderTable(db, providerName, tableName.lowercase())
{
override fun createInDatabase() {
val sqlCreateTable =
(" CREATE TABLE " + tableName +
" (" +
" id INTEGER PRIMARY KEY AUTOINCREMENT," +
" key_name TEXT(256) UNIQUE NOT NULL," +
" var_type INTEGER DEFAULT(0) NOT NULL," +
" var_value TEXT(256)," +
" last_change TEXT DEFAULT (DATETIME('NOW', 'localtime') )" +
" );"
)
db.execSQL(sqlCreateTable)
val sqlCreateTrigger =
("CREATE TRIGGER trigger_key_values_after_update" +
" AFTER UPDATE" +
" ON " + tableName +
" BEGIN" +
" UPDATE key_values" +
" SET last_change = datetime('now', 'localtime')" +
" WHERE ID = new.ID;" +
" END;")
db.execSQL(sqlCreateTrigger)
}
override fun createQuery(queryBuilder : SQLiteQueryBuilder, sortOrder:String?) : String {
queryBuilder.projectionMap = values
if (sortOrder == null || sortOrder === "") {
return InMemoryDbProviderInterface.field_name_values_id
}
return sortOrder
}
override fun insert(values: ContentValues?) : Long {
return db.insertWithOnConflict(tableName, "", values, CONFLICT_REPLACE)
}
}
class ContentProviderTableDebug(db:SQLiteDatabase, providerName:String, tableName:String) :
ContentProviderTable(db, providerName, tableName.lowercase())
{
override fun createInDatabase() {
val sqlCreateTable =
(" CREATE TABLE " + tableName +
" (" +
" receive_date_time TEXT DEFAULT (DATETIME('NOW', 'localtime') )," +
" debug_key TEXT(256)," +
" debug_value BLOB" +
" );"
)
db.execSQL(sqlCreateTable)
}
override fun createQuery(queryBuilder : SQLiteQueryBuilder, sortOrder:String?) : String {
queryBuilder.projectionMap = values
if (sortOrder == null || sortOrder === "") {
return InMemoryDbProviderInterface.field_name_debug_receive_date_time
}
return sortOrder
}
override fun insert(values: ContentValues?) : Long {
return db.insert(tableName, "", values)
}
}
class InMemoryDbProvider : ContentProvider() {
private var db: SQLiteDatabase? = null
private var tables: ArrayList<ContentProviderTable> = arrayListOf()
private var uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
private fun checkOrDie(uri: Uri?): Int {
val code = uriMatcher.match(uri)
if (code >= 1 && code <= tables.size) return code
throw IllegalArgumentException("Unknown URI $uri")
}
fun addTable(table: ContentProviderTable) {
tables.add(table)
uriMatcher.apply {
addURI(
table.providerName,
table.tableName,
tables.size
) // tables.size = unique code for table
addURI(table.providerName, table.tableName + "/*", tables.size)
}
}
override fun getType(uri: Uri): String {
val code = uriMatcher.match(uri)
if (code >= 1 && code <= tables.size)
return tables[code - 1].getType()
else
throw IllegalArgumentException("Unsupported URI: $uri")
}
override fun onCreate(): Boolean {
// todo: get providerName from manifest-file (android:authorities)
// val packageManager = context?.packageManager
//
// if (packageManager != null) {
// for (pack in packageManager.getInstalledPackages(PackageManager.GET_PROVIDERS)) {
// val providers = pack.providers
// if (providers != null) {
// for (provider in providers) {
// Log.d("Example", "provider: " + provider.authority)
// packageManager?.let { provider.loadLabel(it).toString() }?.let { Log.d("cr", it) }
// }
// }
// }
// }
val dbHelper = DatabaseHelper(context)
db = dbHelper.writableDatabase
db?.also {
initMe(it, this)
it.execSQL("PRAGMA recursive_triggers = 0;")
if(dbHelper.createNeeded) {
for (table in tables) {
table.createInDatabase()
}
}
if(dbHelper.upgradeNeeded) {
for (table in tables) {
table.upgradeInDatabase(dbHelper.oldVersion, dbHelper.newVersion)
}
}
}
return db != null
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, _sortOrder: String?
): Cursor? {
var sortOrder = _sortOrder
val qb = SQLiteQueryBuilder()
val code = checkOrDie(uri)
qb.tables = tables[code - 1].tableName
sortOrder = tables[code - 1].createQuery(qb, sortOrder)
val c = qb.query(
db, projection, selection, selectionArgs, null,
null, sortOrder
)
context?.also {
c.setNotificationUri(it.contentResolver, uri)
}
return c
}
override fun insert(uri: Uri, values: ContentValues?): Uri {
val code = checkOrDie(uri)
val rowID = tables[code - 1].insert(values)
if (rowID > 0) {
val uriWithRowId = ContentUris.withAppendedId(InMemoryDbProviderInterface.getUri(tables[code - 1].tableName), rowID)
context?.contentResolver?.notifyChange(uriWithRowId, null)
return uriWithRowId
}
throw SQLiteException("Failed to add a record into $uri")
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
val code = checkOrDie(uri)
val count = tables[code-1].update(values, selection, selectionArgs)
context?.contentResolver?.notifyChange(uri, null)
return count
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val code = checkOrDie(uri)
val count = tables[code-1].delete(selection, selectionArgs)
context?.contentResolver?.notifyChange(uri, null)
return count
}
private class DatabaseHelper(context: Context?) :
SQLiteOpenHelper(context, null, null, DATABASE_VERSION) { // name=null -> in Memory
var oldVersion : Int = -1
private set
var newVersion : Int = -1
private set
val upgradeNeeded = oldVersion != newVersion
var createNeeded : Boolean = false
private set
override fun onCreate(db: SQLiteDatabase) {
createNeeded = true
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
this.oldVersion = oldVersion
this.newVersion = newVersion
}
}
companion object {
const val DATABASE_VERSION = 1
fun initMe(db: SQLiteDatabase, provider: InMemoryDbProvider) {
provider.addTable(ContentProviderTableValues(db, InMemoryDbProviderInterface.PROVIDER_NAME, InMemoryDbProviderInterface.TABLE_NAME_VALUES))
provider.addTable(ContentProviderTableDebug(db, InMemoryDbProviderInterface.PROVIDER_NAME, InMemoryDbProviderInterface.TABLE_NAME_DEBUG))
}
}
}
| 0 | Kotlin | 4 | 33 | 3f453685d33215dbc6e9d289ce925ac430550f32 | 9,475 | dbbahnhoflive-android | Apache License 2.0 |
DSLs/kubernetes/dsl/src/main/kotlin-gen/dev/forkhandles/k8s/autoscaling/v2beta2/scaleUp.kt | fork-handles | 649,794,132 | false | {"Kotlin": 575626, "Shell": 2264, "Just": 1042, "Nix": 740} | // GENERATED
package dev.forkhandles.k8s.autoscaling.v2beta2
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HPAScalingRules as v2beta2_HPAScalingRules
import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerBehavior as v2beta2_HorizontalPodAutoscalerBehavior
fun v2beta2_HorizontalPodAutoscalerBehavior.scaleUp(block: v2beta2_HPAScalingRules.() -> Unit = {}) {
if (scaleUp == null) {
scaleUp = v2beta2_HPAScalingRules()
}
scaleUp.block()
}
| 0 | Kotlin | 0 | 9 | 68221cee577ea16dc498745606d07b0fb62f5cb7 | 501 | k8s-dsl | MIT License |
src/test/kotlin/care/better/platform/web/template/converter/WebTemplateBuildAndWriteTest.kt | better-care | 343,549,109 | false | null | /* Copyright 2021 Better Ltd (www.better.care)
*
* 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 care.better.platform.web.template.converter
import care.better.platform.web.template.WebTemplate
import care.better.platform.web.template.abstraction.AbstractWebTemplateTest
import com.google.common.collect.ImmutableSet
import care.better.platform.web.template.builder.context.WebTemplateBuilderContext
import care.better.platform.web.template.builder.WebTemplateBuilder
import care.better.platform.web.template.builder.model.WebTemplateNode
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.io.IOException
import javax.xml.bind.JAXBException
/**
* @author Primoz Delopst
* @since 3.1.0
*/
class WebTemplateBuildAndWriteTest : AbstractWebTemplateTest() {
@Test
@Throws(IOException::class, JAXBException::class)
fun testPerinatal() {
buildAndExport("/convert/templates/MED - Perinatal history Summary.opt", "perinatal")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testVital() {
buildAndExport("/convert/templates/ZN - Vital Functions Encounter.opt", "vital-all")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testAnamnesis() {
buildAndExport("/convert/templates/MED - Medical Admission History.opt", "anamnesis")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testVitals() {
buildAndExport("/convert/templates/Demo Vitals.opt", "vitals")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testInitialMedicationSafety() {
buildAndExport("/convert/templates/MSE - Initial Medication Safety Report.opt", "initialMedicationSafety")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testMedicationErrorReport() {
buildAndExport("/convert/templates/MSE - Medication Error Report.xml", "medicationErrorReport")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testMedicationEventCaseSummary() {
buildAndExport("/convert/templates/MSE - Medication Event Case Summary.opt", "medicationEventCaseSummary")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testAdverseReaction() {
buildAndExport("/convert/templates/adverse4.opt", "adverse", "sl", ImmutableSet.of("en", "sl"))
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testRussian() {
buildAndExport("/convert/templates/openEHR-EHR-COMPOSITION.t_primary_therapeutist_examination.opt", "therapeutist_examination")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testRadImaging() {
buildAndExport("/convert/templates/RAD - Imaging status event.opt", "imagingStatus")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testErco() {
buildAndExport("/convert/templates/Vaccination Record.opt", "erco")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testDefaultValues() {
buildAndExport("/convert/templates/Новый Шаблон.opt", "test")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testParsable() {
buildAndExport("/convert/templates/MED - Document.opt", "meddoc")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testScales() {
val builderContext = WebTemplateBuilderContext("sl")
writeOut("scales", WebTemplateBuilder.buildNonNull(getTemplate("/convert/templates/ZN - Assessment Scales Encounter.opt"), builderContext))
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testCabinet() {
val builderContext = WebTemplateBuilderContext("ru")
val webTemplate: WebTemplate = WebTemplateBuilder.buildNonNull(getTemplate("/convert/templates/Cabinet.opt"), builderContext)
val webTemplateNode: WebTemplateNode = webTemplate.tree.children[0].children[0]
assertThat(webTemplateNode.getInput()?.defaultValue).isEqualTo("at0007")
writeOut("cabinet", webTemplate)
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testCabinet123() {
val builderContext = WebTemplateBuilderContext("ru")
val webTemplate: WebTemplate = WebTemplateBuilder.buildNonNull(getTemplate("/convert/templates/Cabinet123.opt"), builderContext)
val webTemplateNode: WebTemplateNode = webTemplate.tree.children[0].children[0]
assertThat(webTemplateNode.annotations).contains(
Assertions.entry("GUI Directives.Widget Type", "List"),
Assertions.entry("GUI Directives.Show Description", "true"))
writeOut("cabinet123", webTemplate)
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testDefaultValue() {
val builderContext = WebTemplateBuilderContext("ru")
val webTemplate: WebTemplate =
WebTemplateBuilder.buildNonNull(getTemplate("/convert/templates/openEHR-EHR-COMPOSITION.t_allergologist_examination.opt"), builderContext)
writeOut("allergology", webTemplate)
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testHelloworld() {
buildAndExport("/convert/templates/helloworld.opt", "helloworld")
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testAdmission() {
buildAndExport("/convert/templates/ZN - Admition Summary Encounter new.opt", "admission", "sl", ImmutableSet.of("en", "sl"))
}
@Test
@Throws(IOException::class, JAXBException::class)
fun testFormsDemo() {
buildAndExport("/convert/templates/Forms Demo.opt", "formsdemo", "sl", ImmutableSet.of("en", "sl"))
}
@Throws(JAXBException::class, IOException::class)
private fun buildAndExport(templateName: String, prefix: String) {
buildAndExport(templateName, prefix, "sl", ImmutableSet.of("sl", "en"))
}
}
| 0 | Kotlin | 1 | 1 | 4aa47c5c598be6687dc2c095b1f7fcee49702a28 | 6,544 | web-template | Apache License 2.0 |
app/src/main/java/com/penkzhou/projects/android/playground/model/ItemModel.kt | penkzhou | 203,168,847 | false | null | package com.penkzhou.projects.android.playground.model
import androidx.annotation.Keep
@Keep
class ItemModel(val name: String, val icon: String, val path: String)
| 0 | Kotlin | 0 | 0 | 01dbedd4aa8531fd6694b99c4f9b60f36e0cc108 | 165 | AndroidPlayground | MIT License |
feature/management-survey/src/main/java/com/wap/wapp/feature/management/survey/SurveyFormState.kt | pknu-wap | 689,890,586 | false | {"Kotlin": 589300, "Shell": 233} | package com.wap.wapp.feature.management.survey
enum class SurveyFormState(
val page: String,
val progress: Float,
) {
EVENT_SELECTION("1", 0.25f),
INFORMATION("2", 0.50f),
QUESTION("3", 0.75f),
DEADLINE("4", 1f),
}
| 7 | Kotlin | 0 | 8 | 28a2281514f4330eb955f8e5867a415d60f8dfc1 | 240 | WAPP | MIT License |
common/src/main/java/sean/k/common/data/LoginRepository.kt | seanKenkeremath | 525,128,732 | false | null | package sean.k.common.data
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import sean.k.common.date.Clock
import sean.k.login.data.LoginApi
import java.text.SimpleDateFormat
import java.util.*
interface LoginRepository {
val username: String?
val sessionToken: String?
val lastLoginTime: Long?
val lastLoginDateFormatted: String?
get() = lastLoginTime?.let { dateFormat.format(Date(it)) }
val isLoggedIn: Boolean
get() = sessionToken != null
fun isLoggedInObservable(): Flow<Boolean>
fun logout()
fun login(username: String, password: String): Flow<Boolean>
companion object {
private val dateFormat = SimpleDateFormat.getDateTimeInstance()
}
}
class LoginRepositoryImpl(context: Context, private val api: LoginApi, private val clock: Clock) :
LoginRepository {
private val datastore = Datastore(context)
override val username: String?
get() = datastore.username
override val sessionToken: String?
get() = datastore.sessionToken
override val lastLoginTime: Long?
get() = datastore.loginDateTimestamp.let {
if (it == 0L) {
null
} else {
it
}
}
/** Must be updated whenever login state changes. **/
private val _isLoggedInObservable: MutableStateFlow<Boolean> = MutableStateFlow(isLoggedIn)
override fun isLoggedInObservable(): Flow<Boolean> {
return this._isLoggedInObservable
}
override fun logout() {
datastore.sessionToken = null
datastore.username = null
datastore.loginDateTimestamp = 0L
_isLoggedInObservable.value = false
}
override fun login(username: String, password: String): Flow<Boolean> {
return flow {
when (val result = api.login(username, password)) {
is Result.Error -> {
//TODO
emit(false)
}
is Result.Success -> {
datastore.username = result.data.userName
datastore.sessionToken = result.data.sessionToken
datastore.loginDateTimestamp = clock.currentTimeMillis
_isLoggedInObservable.value = true
emit(true)
}
}
//TODO: testable DispatcherProvider interface
}.flowOn(Dispatchers.IO)
}
internal class Datastore(context: Context) {
companion object {
private const val PREFERENCES_NAME = "sean.k.common.login_preferences"
private const val KEY_DATASTORE_VERSION = "key_datastore_version"
private const val KEY_USERNAME = "key_username"
private const val KEY_SESSION_TOKEN = "key_session_token"
private const val KEY_LOGIN_TIME = "key_login_time"
}
private val prefs: SharedPreferences = context.getSharedPreferences(
PREFERENCES_NAME,
Activity.MODE_PRIVATE
)
private fun getEditor(): SharedPreferences.Editor {
return prefs.edit()
}
var sessionToken: String?
get() = prefs.getString(KEY_SESSION_TOKEN, null)
set(value) = getEditor().putString(KEY_SESSION_TOKEN, value).apply()
var username: String?
get() = prefs.getString(KEY_USERNAME, null)
set(value) = getEditor().putString(KEY_USERNAME, value).apply()
var loginDateTimestamp: Long
get() = prefs.getLong(KEY_LOGIN_TIME, 0)
set(value) = getEditor().putLong(KEY_LOGIN_TIME, value).apply()
}
} | 0 | Kotlin | 0 | 0 | 09aad7faa4b89ddc205b36962f549830ec8e25f9 | 3,894 | AndroidModularAppExample | MIT License |
app/src/main/java/org/dclm/live/ui/util/db/DCLMDataBase.kt | Ochornma | 275,347,425 | false | null | package org.dclm.live.ui.util.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.dclm.live.ui.message.Blog
import org.dclm.live.ui.message.BlogDao
import org.dclm.live.ui.sermon.Note
import org.dclm.live.ui.sermon.NoteDao
@Database(entities = [Note::class], version = 6, exportSchema = false)
abstract class DCLMDataBase : RoomDatabase() {
abstract fun noteDAO(): NoteDao
// abstract fun blogDAO(): BlogDao
companion object {
var INSTANCE: DCLMDataBase? = null
fun getAppDataBase(context: Context): DCLMDataBase? {
if (INSTANCE == null){
synchronized(DCLMDataBase::class){
INSTANCE = Room.databaseBuilder(context.applicationContext, DCLMDataBase::class.java, "note_database")
.addMigrations(
MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6)
//.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}
fun destroyDataBase(){
INSTANCE = null
}
private val MIGRATION_3_4: Migration = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE note_table ADD COLUMN point4 TEXT")
}
}
private val MIGRATION_4_5: Migration = object : Migration(4, 5) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE note_table ADD COLUMN point4_description TEXT")
}
}
private val MIGRATION_5_6: Migration = object : Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
// database.execSQL("CREATE TABLE IF NOT EXISTS `blog` (`id` INTEGER , `title` TEXT NOT NULL, `date` TEXT NOT NULL,`body` TEXT NOT NULL, PRIMARY KEY(`id`))")
//database.execSQL("CREATE TABLE IF NOT EXISTS `blog` (`id` INTEGER NOT NULL, `title` TEXT, `date` TEXT,`body` TEXT, PRIMARY KEY(`id`))")
//database.execSQL("CREATE TABLE IF NOT EXISTS `blog` (`id` INTEGER NOT NULL, `title` TEXT, `date` TEXT,`body` TEXT, PRIMARY KEY(`id`))")
database.execSQL("CREATE TABLE IF NOT EXISTS note_table_Tmp (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, service TEXT, date TEXT , speaker TEXT, topic TEXT, description TEXT, point1 TEXT, point1_description TEXT, point2 TEXT, point2_description TEXT, point3 TEXT, point3_description TEXT, point4 TEXT, point4_description TEXT, decision TEXT)")
database.execSQL("INSERT INTO note_table_tmp(id, service, date , speaker, topic, description, point1, point1_description , point2 , point2_description , point3 , point3_description , point4 , point4_description , decision) SELECT id, service, date , speaker, topic, description, point1, point1_description , point2 , point2_description , point3 , point3_description , point4 , point4_description , decision FROM note_table")
database.execSQL("DROP TABLE note_table")
database.execSQL("ALTER TABLE note_table_Tmp RENAME TO note_table")
}
}
}
} | 0 | Kotlin | 1 | 1 | 2715e65c7c96587f0365c870b5fa6c8120d00f82 | 3,465 | DCLM-Project | MIT License |
app/src/main/java/com/phil/airinkorea/ui/appguide/AppGuideRoute.kt | want8607 | 574,473,916 | false | null | package com.phil.airinkorea.ui.appguide
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.phil.airinkorea.R
import com.phil.airinkorea.ui.theme.AIKTypography
import com.phil.airinkorea.ui.viewmodel.AppGuideUiState
import com.phil.airinkorea.ui.viewmodel.AppGuideViewModel
data class AppGuideContent(
@StringRes val title: Int,
val content: @Composable () -> Unit,
)
@Composable
fun AppGuideRoute(
appGuideViewModel: AppGuideViewModel = hiltViewModel(),
onBackButtonClick: () -> Unit
) {
val appGuideUiState by appGuideViewModel.appGuideUiState
when (appGuideUiState) {
AppGuideUiState.Loading -> Unit
is AppGuideUiState.Success -> {
val successAppGuideUiState = (appGuideUiState as AppGuideUiState.Success)
val appGuideContentList = listOf(
AppGuideContent(R.string.cautions) { GuideContentCommon(text = successAppGuideUiState.appGuide.cautionGuideText) },
AppGuideContent(R.string.data_loading) { GuideContentCommon(text = successAppGuideUiState.appGuide.dataLoadingGuideText) },
AppGuideContent(R.string.air_pollution_level) { GuideContentAirPollutionLevel(text = successAppGuideUiState.appGuide.airPollutionLevelGuideText) },
AppGuideContent(R.string.details) { GuideContentCommon(text = successAppGuideUiState.appGuide.detailGuideText) },
AppGuideContent(R.string.information) { GuideContentCommon(text =successAppGuideUiState.appGuide.informationGuideText )},
AppGuideContent(R.string.dailyForecast) { GuideContentCommon(text =successAppGuideUiState.appGuide.dailyForecastGuideText )},
AppGuideContent(R.string.koreaForecastMap) { GuideContentCommon(text =successAppGuideUiState.appGuide.koreaForecastModelGuideText )},
AppGuideContent(R.string.add_location) { GuideContentCommon(text =successAppGuideUiState.appGuide.addLocationGuideText )}
)
AppGuideScreen(
appGuideContentList = appGuideContentList,
onBackButtonClick = onBackButtonClick
)
}
}
}
private val contentPadding = 10.dp
@Composable
fun GuideContentCommon(
modifier: Modifier = Modifier,
text: String
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.fillMaxWidth()
.padding(vertical = contentPadding)
) {
Text(
text = text,
style = AIKTypography.body1,
textAlign = TextAlign.Start,
modifier = Modifier.fillMaxWidth()
)
}
}
@Composable
fun GuideContentAirPollutionLevel(
modifier: Modifier = Modifier,
text: String
) {
val pollutionImgList = arrayListOf<@receiver:DrawableRes Int>(
R.drawable.pm10,
R.drawable.pm25,
R.drawable.no2,
R.drawable.so2,
R.drawable.co,
R.drawable.o3
)
Column(
modifier = modifier
.fillMaxWidth()
.padding(vertical = contentPadding)
) {
Text(
text = text,
style = AIKTypography.body1,
textAlign = TextAlign.Start,
modifier = Modifier.fillMaxWidth()
)
for (img in pollutionImgList) {
Row(
modifier = modifier
.wrapContentSize()
.padding(vertical = 10.dp)
.horizontalScroll(state = rememberScrollState())
) {
Image(
painter = painterResource(id = img),
contentDescription = null
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 87502bbd7639a8fe9f930f0d413265e8e45e09ad | 4,540 | AirInKorea | Apache License 2.0 |
src/test/kotlin/com/arcadeanalytics/util/PlaygroundTest.kt | Surfndez | 171,409,313 | true | {"JavaScript": 2351390, "TypeScript": 1174181, "Java": 974584, "CSS": 848417, "HTML": 773435, "Scala": 41284, "Kotlin": 5061, "Dockerfile": 2754, "PHP": 2200, "Shell": 78} | package com.arcadeanalytics.util
import com.arcadeanalytics.domain.enumeration.MediaCategory
import com.arcadeanalytics.service.dto.MediaDTO
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Paths
class PlaygroundTest {
@Test
fun testFiles() {
Paths.get("./src/main/webapp/content/media/").toFile()
.walkBottomUp()
.filter { f -> f.isFile && f.extension.equals("png") }
.map { f ->
val media = MediaDTO()
media.name = f.name
media.category = MediaCategory.valueOf(f.parentFile.name.toUpperCase())
media.file = f.readBytes()
media
}
.forEach { m -> println("m = ${m}") }
Paths.get("./src/main/webapp/content/media/").toFile()
.walkBottomUp()
.filter { f -> f.extension == "png" }
Files.newDirectoryStream(Paths.get("./src/main/webapp/content/media/"), "**/*.png")
.map { p -> println("p = ${p}") }
}
}
| 4 | JavaScript | 0 | 0 | 3a59d3976f4709d59975d8a9f8ea6e36402e6250 | 1,045 | arcadeanalytics | Apache License 2.0 |
src/main/kotlin/sh/astrid/locksmith/commands/Wipe.kt | astridlol | 587,129,923 | false | {"Java": 69275, "Kotlin": 23502} | package sh.astrid.locksmith.commands
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.command.ConsoleCommandSender
import org.bukkit.entity.Player
import sh.astrid.locksmith.Locksmith
import sh.astrid.locksmith.lib.SQL
import sh.astrid.locksmith.lib.coloured
class Wipe : CommandExecutor {
init {
Locksmith.instance.getCommand("wipe")!!.setExecutor(this);
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
val canExecute = (sender is ConsoleCommandSender || sender is Player && sender.isOp)
if(!canExecute) {
var name = "Unknown"
if(sender is Player) name = sender.displayName
println("$name tried to use /wipe")
return false
}
SQL.execute("DELETE FROM locked_containers")
SQL.execute("DELETE FROM keys")
sender.sendMessage("&pSuccessfully &swiped&p all data".coloured())
return true;
}
} | 1 | null | 1 | 1 | 59fe741ca6089f6fa7149e78ed8567b837808dd8 | 1,074 | Locksmith | Apache License 2.0 |
infra/db/src/main/kotlin/physicaltherapy/entity/notification/SprintNotification.kt | giantbalance | 738,855,640 | false | {"Gradle Kotlin DSL": 8, "Java Properties": 1, "Shell": 3, "YAML": 10, "Text": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 37, "JAR Manifest": 5, "SQL": 6, "INI": 1, "Dockerfile": 1, "HTTP": 1, "XML": 2, "Java": 32} | package physicaltherapy.entity.notification
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.FetchType
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import physicaltherapy.entity.BaseEntity
import physicaltherapy.entity.notificationChannel.NotificationChannel
@Entity
internal class ProjectNotification(
@Column(name = "project_id", nullable = false)
val projectId: Long,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "notification_channel_id", nullable = false)
val notificationChannel: NotificationChannel,
@Column(name = "content", nullable = false)
val content: String,
@Column(name = "reaction_count", nullable = false)
private var reactionCount: Int = 0,
@Enumerated(EnumType.STRING)
@Column(name = "notification_type", nullable = false)
val type: NotificationType,
) : BaseEntity()
| 0 | Java | 0 | 0 | 96b6a414b326c41129d3f466b4171f9e31734904 | 1,002 | action_test | Apache License 2.0 |
samples/src/main/kotlin/20FinamTradingBalance.kt | Viktor-Kollegov | 739,564,741 | false | {"INI": 2, "Gradle Kotlin DSL": 10, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 5, "Kotlin": 43, "XML": 2, "YAML": 1, "Java": 54, "JSON": 3} | package org.cryptolosers.samples
import org.cryptolosers.trading.connector.Connector
import org.cryptolosers.transaq.FinamFutureInstrument
import org.cryptolosers.transaq.connector.concurrent.InternalTransaqConnector
/**
* Sample
* Connect to Finam via Transaq connector and print balance, positions, orders. It is not modify anything.
* Before run:
* - copy config/terminalConfig-example.json to config/terminalConfig.json
* - insert your login and password (of Finam Transaq connector) to config/terminalConfig.json
*/
suspend fun main() {
val conn = Connector(InternalTransaqConnector())
conn.connect()
println("tickers " + conn.tradingApi().getAllTickers().filter { it.id.ticker.startsWith("BR") && it.type == FinamFutureInstrument })
conn.abort()
} | 1 | null | 1 | 1 | 05f222e8847ce1c23f5e735e11e8840485ea23ea | 778 | koto-trader | Apache License 2.0 |
sdkCore/src/main/java/com/hyperring/sdk/core/data/HyperRingMFAChallengeInterface.kt | yoonil-hypercycle | 834,749,904 | false | {"Kotlin": 88780} | package com.hyperring.sdk.core.data
/**
* Default HyperRing MFA, Challenge Data Interface
*/
interface HyperRingMFAChallengeInterface : HyperRingDataInterface {
var isSuccess: Boolean?
override var id: Long?
override var data : String?
override fun encrypt(source: Any?) : ByteArray
override fun decrypt(source: String?) :Any
/**
* Parts you need to implement yourself (MFA Challenge)
*/
fun challenge(targetData: HyperRingDataInterface): MFAChallengeResponse
} | 0 | Kotlin | 0 | 0 | 1c434229fba5cab919d5891eb6ae5b593407a410 | 506 | HyperRing-for-FIDO-2-App | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.