path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/io/lunarchain/lunarcoin/core/CodeStorage.kt
lunarchain
121,196,186
false
null
package io.lunarchain.lunarcoin.core class CodeStorage(val codeHash: ByteArray, val contractCode: ByteArray) { }
1
Kotlin
2
2
4f43e5965fb32ee451260d8b1ddef7ae41b684fb
113
lunarcoin-core
Apache License 2.0
buildSrc/src/main/kotlin/com/bigbackboom/tryandroidstuff/build/Deps.kt
BigBackBoom
564,838,607
false
null
package com.bigbackboom.tryandroidstuff.build object Deps { object AndroidX { private const val lifecycleVersion = "2.5.1" const val design = "com.google.android.material:material:1.7.0" const val appCompat = "androidx.appcompat:appcompat:1.5.1" const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.1.4" const val liveData = "androidx.lifecycle:lifecycle-livedata:$lifecycleVersion" const val browser = "androidx.browser:browser:1.4.0" object Ktx { const val core = "androidx.core:core-ktx:1.7.0" const val liveDataKtx = "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion" const val navigationFragment = "androidx.navigation:navigation-fragment-ktx:2.5.3" const val navigationUI = "androidx.navigation:navigation-ui-ktx:2.5.3" } object Test { const val jUnit = "androidx.test.ext:junit:1.1.4" const val espresso = "androidx.test.espresso:espresso-core:3.5.0" } } object Kotlin { const val serialization = "org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1" } object Dagger { const val hilt = "com.google.dagger:hilt-android:2.44" const val hiltCompiler = "com.google.dagger:hilt-compiler:2.44" } object Retrofit2 { const val retrofit = "com.squareup.retrofit2:retrofit:2.9.0" const val retrofitSerializationConverter = "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" } object Glide { private const val glideVersion = "4.14.2" const val core = "com.github.bumptech.glide:glide:$glideVersion" const val integration = "com.github.bumptech.glide:okhttp3-integration:$glideVersion" const val compiler = "com.github.bumptech.glide:compiler:$glideVersion" } object Okhttp { const val okhttp = "com.squareup.okhttp3:okhttp:4.10.0" const val logger = "com.squareup.okhttp3:logging-interceptor:4.10.0" } object Timber { const val timber = "com.jakewharton.timber:timber:5.0.1" } object Test { const val jUnit = "junit:junit:4.13.2" } }
5
Kotlin
0
0
43edf8dc30f2211789fa0b7a9fcc09dd58547cd4
2,235
try_android_stuff
Apache License 2.0
app/src/main/java/com/eslamwaheed/fakestore/base/BaseDialog.kt
EslamWaheed
539,901,655
false
{"Kotlin": 18952}
package com.eslamwaheed.fakestore.base import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.eslamwaheed.fakestore.R class BaseDialog( private val title: String?, private val message: String?, private val negativeButton: String?, private val positiveButton: String?, private val negativeButtonAction: ((DialogInterface, Int) -> Unit)?, private val positiveButtonAction: ((DialogInterface, Int) -> Unit)? ) : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { isCancelable = false return activity?.let { val builder = AlertDialog.Builder(it) title?.let { title -> builder.setTitle(title) } builder.setMessage(message) .setNegativeButton(negativeButton ?: getString(R.string.ok)) { dialog, which -> negativeButtonAction?.invoke( dialog, which ) }.apply { setPositiveButton( positiveButton ?: getString(R.string.retry) ) { dialog, which -> positiveButtonAction?.invoke( dialog, which ) } } builder.create() } ?: throw IllegalStateException("Activity cannot be null") } }
0
Kotlin
0
0
bdaeeef34297fc7964cce70b5bd89c04816ab62a
1,593
FakeStore
Apache License 2.0
app/src/main/java/com/eslamwaheed/fakestore/base/BaseDialog.kt
EslamWaheed
539,901,655
false
{"Kotlin": 18952}
package com.eslamwaheed.fakestore.base import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.eslamwaheed.fakestore.R class BaseDialog( private val title: String?, private val message: String?, private val negativeButton: String?, private val positiveButton: String?, private val negativeButtonAction: ((DialogInterface, Int) -> Unit)?, private val positiveButtonAction: ((DialogInterface, Int) -> Unit)? ) : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { isCancelable = false return activity?.let { val builder = AlertDialog.Builder(it) title?.let { title -> builder.setTitle(title) } builder.setMessage(message) .setNegativeButton(negativeButton ?: getString(R.string.ok)) { dialog, which -> negativeButtonAction?.invoke( dialog, which ) }.apply { setPositiveButton( positiveButton ?: getString(R.string.retry) ) { dialog, which -> positiveButtonAction?.invoke( dialog, which ) } } builder.create() } ?: throw IllegalStateException("Activity cannot be null") } }
0
Kotlin
0
0
bdaeeef34297fc7964cce70b5bd89c04816ab62a
1,593
FakeStore
Apache License 2.0
app/src/main/java/com/atorresveiga/bluecloud/data/UserLocationDatasource.kt
atorresveiga
349,074,627
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.atorresveiga.bluecloud.data import android.annotation.SuppressLint import android.content.Context import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.tasks.CancellationTokenSource import com.google.android.gms.tasks.Task import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine import javax.inject.Inject import kotlin.coroutines.resumeWithException interface UserLocationDataSource { suspend fun getLocation(): Pair<Double, Double>? } class GMSUserLocationDataSource @Inject constructor(@ApplicationContext appContext: Context) : UserLocationDataSource { private val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(appContext) @SuppressLint("MissingPermission") override suspend fun getLocation(): Pair<Double, Double>? { val cancellationTokenSource = CancellationTokenSource() val location = fusedLocationClient.lastLocation.await() ?: fusedLocationClient.getCurrentLocation( LocationRequest.PRIORITY_LOW_POWER, cancellationTokenSource.token ).await { cancellationTokenSource.cancel() } return location?.let { Pair(it.latitude, it.longitude) } } } /** * Util function to transform Task callbacks to suspend function */ @OptIn(ExperimentalCoroutinesApi::class) suspend fun <T> Task<T>.await(onCancellation: () -> Unit = {}): T { // fast path if (isComplete) { val e = exception return if (e == null) { if (isCanceled) { throw CancellationException( "Task $this was cancelled normally." ) } else { result } } else { throw e } } return suspendCancellableCoroutine { cont -> cont.invokeOnCancellation { onCancellation() } addOnCompleteListener { val e = exception if (e == null) { if (isCanceled) cont.cancel() else cont.resume(result) { throw CancellationException( "Task $this was cancelled normally." ) } } else { cont.resumeWithException(e) } } } }
0
Kotlin
0
6
7c30dedb79dbce2cbc7dce686c49962b767e5409
3,213
android-dev-challenge-compose-weather
Apache License 2.0
src/main/kotlin/com/amitcul/translate_it/model/Translation.kt
AlexMitcul
836,668,344
false
{"Kotlin": 10238, "HTML": 1416, "JavaScript": 1174, "Dockerfile": 860, "CSS": 694, "Makefile": 231, "Shell": 57}
package com.amitcul.translate_it.model import java.time.LocalDateTime data class Translation( var id: Long? = null, var ipAddress: String, var sourceText: String, var translatedText: String, var sourceLang: String, var targetLang: String, var createdAt: LocalDateTime )
0
Kotlin
0
0
883f64355c57fe058808bd848c0c095b70af15b5
299
translate_it
MIT License
usvm-core/src/main/kotlin/org/usvm/statistics/distances/DistanceCalculator.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2623226, "Java": 476836}
package org.usvm.statistics.distances import org.usvm.UCallStack /** * @see calculateDistance */ fun interface DistanceCalculator<Method, Statement, out Distance> { /** * Calculate distance from location represented by [currentStatement] and [callStack] to * some predefined targets. */ fun calculateDistance(currentStatement: Statement, callStack: UCallStack<Method, Statement>): Distance } /** * Dynamically accumulates multiple [DistanceCalculator] by their targets allowing * to calculate distances to arbitrary targets. */ class MultiTargetDistanceCalculator<Method, Statement, Distance>( private val getDistanceCalculator: (Statement) -> DistanceCalculator<Method, Statement, Distance> ) { private val calculatorsByTarget = hashMapOf<Statement, DistanceCalculator<Method, Statement, Distance>>() // TODO: think later about better memory management using this function fun removeTargetFromCache(target: Statement): Boolean { return calculatorsByTarget.remove(target) != null } /** * Calculate distance from location represented by [currentStatement] and [callStack] to the [target]. */ fun calculateDistance( currentStatement: Statement, callStack: UCallStack<Method, Statement>, target: Statement ): Distance { val calculator = calculatorsByTarget.computeIfAbsent(target) { getDistanceCalculator(it) } return calculator.calculateDistance(currentStatement, callStack) } }
36
Kotlin
6
9
6bafd5c9f8301c179f74f3e8f0e8c9e911aaa5e1
1,505
usvm
Apache License 2.0
src/main/kotlin/com/manager/labo/utils/DisplayInJTable.kt
pszerszen
588,879,286
false
null
package com.manager.labo.utils import com.manager.labo.view.components.TableModel import java.lang.annotation.Inherited @Inherited @Retention(AnnotationRetention.RUNTIME) @Repeatable @Target(AnnotationTarget.FIELD) annotation class DisplayInJTable(val name: TableModel, val order: Int)
1
Kotlin
0
1
4fb55867e3c5331aa211e9c056bab5f09303cd0d
288
promedlab-v2
The Unlicense
app/src/main/java/me/anon/lib/ext/NumberUtils.kt
7LPdWcaW
40,006,856
false
null
package me.anon.lib.ext import android.content.Context import android.util.TypedValue import kotlin.math.round public fun Double.round(decimals: Int): Double { var multiplier = 1.0 repeat(decimals) { multiplier *= 10 } return round(this * multiplier) / multiplier } public fun Number?.formatWhole(): String { return this?.let { if (this.toDouble() - this.toInt().toDouble() == 0.0) return "${this.toInt()}" return when (this) { is Double -> { val value = this.round(2) return if (value - value.toInt().toDouble() == 0.0) "${value.toInt()}" else "${value}" } is Float -> { val value = this.toDouble().round(2) return if (value - value.toInt().toDouble() == 0.0) "${value.toInt()}" else "${value}" } else -> "${this.toInt()}" } } ?: "0" } public fun Long.toDays(): Double = (this / (1000.0 * 60.0 * 60.0 * 24.0)) public fun Number.dip(context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics) public fun Number.sp(context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), context.resources.displayMetrics) public fun Number.mm(context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, this.toFloat(), context.resources.displayMetrics) public fun Number.pt(context: Context): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, this.toFloat(), context.resources.displayMetrics) public fun Double?.max(other: Double?): Double? { return when { other == null -> this this == null -> other else -> kotlin.math.max(this, other) } } public fun Double?.min(other: Double?): Double? { return when { other == null -> this this == null -> other else -> kotlin.math.min(this, other) } }
21
null
31
147
61dea1bd9c5d618b5530725d817c30b20b267959
1,788
GrowTracker-Android
Apache License 2.0
imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/model/GridCount.kt
nguyenhoanglam
64,893,333
false
null
/* * Copyright (C) 2021 Image Picker * Author: <NAME> <<EMAIL>> */ package com.nguyenhoanglam.imagepicker.model import android.os.Parcel import android.os.Parcelable data class GridCount(val portrait: Int, val landscape: Int) : Parcelable { constructor(parcel: Parcel) : this( parcel.readInt(), parcel.readInt() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeInt(portrait) parcel.writeInt(landscape) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<GridCount> { override fun createFromParcel(parcel: Parcel): GridCount { return GridCount(parcel) } override fun newArray(size: Int): Array<GridCount?> { return arrayOfNulls(size) } } }
21
Kotlin
151
545
3568d1a02d52ac85b5297045865c1c3d9df1a96d
844
ImagePicker
Apache License 2.0
YTubeVideo/app/src/main/java/com/htk/ytubevideo/core/config/YTubeApplication.kt
lsbloo
774,691,626
false
{"Kotlin": 63128}
package com.htk.ytubevideo.core.config import android.app.Application import androidx.startup.AppInitializer import com.google.firebase.FirebaseApp import com.htk.ytubevideo.core.base.ScopedModule import com.htk.ytubevideo.features.splash.di.SplashInject import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin class YTubeApplication : Application() { override fun onCreate() { super.onCreate() val initializer = AppInitializer.getInstance(this) FirebaseApp.initializeApp(this) startKoin { androidLogger() androidContext(this@YTubeApplication) modules(YTubeKoinModules.appModules) } } }
0
Kotlin
0
0
3ec51fd7124fadcb56c890033465ac1cb93e623d
751
YTubeVideo
MIT License
app/src/main/java/com/rubens/applembretemedicamento/presentation/MainActivity.kt
rubens23
630,981,517
false
{"Kotlin": 339755}
package com.rubens.applembretemedicamento.presentation import android.app.PendingIntent import android.content.res.ColorStateList import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import androidx.core.content.ContextCompat import androidx.datastore.preferences.core.intPreferencesKey import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.rubens.applembretemedicamento.R import com.rubens.applembretemedicamento.databinding.ActivityMainBinding import com.rubens.applembretemedicamento.framework.ApplicationContextProvider import com.rubens.applembretemedicamento.framework.ApplicationContextProvider.setApplicationContext import com.rubens.applembretemedicamento.framework.broadcastreceivers.AlarmReceiver import com.rubens.applembretemedicamento.framework.broadcastreceivers.OnRestartDeviceReceiver import com.rubens.applembretemedicamento.framework.data.datastore.DataStoreTheme import com.rubens.applembretemedicamento.framework.data.datastore.interfaces.ThemeDataStoreInterface import com.rubens.applembretemedicamento.framework.data.entities.ConfiguracoesEntity import com.rubens.applembretemedicamento.framework.viewModels.ActivityHostAndFragmentConfikguracoesSharedViewModel import com.rubens.applembretemedicamento.framework.viewModels.ActivityHostAndFragmentListaMedicamentosSharedViewModel import com.rubens.applembretemedicamento.framework.viewModels.MainActivityViewModel import com.rubens.applembretemedicamento.presentation.interfaces.FragmentListaMedicamentosInterface import com.rubens.applembretemedicamento.presentation.interfaces.MainActivityInterface import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @AndroidEntryPoint class MainActivity: AppCompatActivity(), MainActivityInterface{ private lateinit var navHostFragment: NavHostFragment private lateinit var navController: NavController private val pendingIntentsList = ArrayList<PendingIntent>() private lateinit var binding: ActivityMainBinding private lateinit var viewModel: MainActivityViewModel private lateinit var sharedViewModel: ActivityHostAndFragmentListaMedicamentosSharedViewModel private lateinit var configuracoesSharedViewModel: ActivityHostAndFragmentConfikguracoesSharedViewModel private var temaAzulReferenceId: Int = R.style.CustomThemeAzul private var temaVermelhoReferenceId: Int = R.style.Theme_AppLembreteMedicamento private var tema = "" private lateinit var fragmentListaMedicamentosInterface: FragmentListaMedicamentosInterface private lateinit var themeDataStore: ThemeDataStoreInterface private var theme: Int = R.style.Theme_AppLembreteMedicamento override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) launchScopeToLoadTheme() setContentView(binding.root) Log.d("callobserver", "metodo que vai esconder a toolbar foi chamado") hideToolbarTitle() hideToolbar() configNavigation() initViewModel() initConfiguracoesApp() onClickListeners() setApplicationContextt() } private fun initConfiguracoesApp() { val configuracoes = viewModel.getSwitchersState() if(configuracoes == null){ viewModel.mudarConfiguracoes(ConfiguracoesEntity()) } } private fun setApplicationContextt() { ApplicationContextProvider.setApplicationContext(this) } private fun injetarInstanciaDaInterfaceDaMainActivity(fragmentLista: FragmentListaMedicamentos) { fragmentLista.setMainActivityInterface(this) } private fun launchScopeToLoadTheme(){ lifecycleScope.launch { themeDataStore = DataStoreTheme(applicationContext) val intDataStore = intPreferencesKey("theme_key") val theme = themeDataStore.getThemeChosenByUser(intDataStore) withContext(Dispatchers.Main){ initConfiguracoesSharedViewModel() setTheme(theme) configBottomNavigationTheme(theme) } } } private fun initConfiguracoesSharedViewModel() { configuracoesSharedViewModel = ViewModelProvider(this)[ActivityHostAndFragmentConfikguracoesSharedViewModel::class.java] initConfiguracoesObserver() } private fun initConfiguracoesObserver() { configuracoesSharedViewModel.getMudouTema.observe(this){ mudou-> mostrarToolbar(mudou) } } private fun configBottomNavigationTheme(theme: Int) { if(theme == temaAzulReferenceId){ //tema azul tema = theme.toString() configuracoesSharedViewModel.atualizarTema("Azul") if(this::fragmentListaMedicamentosInterface.isInitialized){ changeFloatingActionButtonColor(R.color.blue) } changeBottomNavigationToBlueTheme() } if(theme == temaVermelhoReferenceId){ //tema vermelho tema = theme.toString() configuracoesSharedViewModel.atualizarTema("Vermelho") if(this::fragmentListaMedicamentosInterface.isInitialized){ changeFloatingActionButtonColor(R.color.rosa_salmao) } changeBottomNavigationToRedTheme() } } private fun changeFloatingActionButtonColor(color: Int) { fragmentListaMedicamentosInterface.changeFloatingActionButtonColor(color) } private fun changeFloatingActionButtonTheme(){ if(tema == temaAzulReferenceId.toString()){ //tema azul tema = theme.toString() changeFloatingActionButtonColor(R.color.blue) } if(tema == temaVermelhoReferenceId.toString()){ //tema vermelho Log.d("instanciafragmento", "eu to aqui no tema vermelho") changeFloatingActionButtonColor(R.color.rosa_salmao) } } private fun changeBottomNavigationTheme(){ if(tema == temaAzulReferenceId.toString()){ //tema azul changeBottomNavigationToBlueTheme() } if(tema == temaVermelhoReferenceId.toString()){ //tema vermelho changeBottomNavigationToRedTheme() } } private fun changeBottomNavigationToRedTheme() { changeBottomNavigationIconTintToRed() changeBottomNavigationTextColorToRed() } private fun changeBottomNavigationToBlueTheme() { changeBottomNavigationIconTintToBlue() changeBottomNavigationTextColorToBlue() } private fun configNavigation() { navHostFragment = (supportFragmentManager.findFragmentById(binding.fragmentContainerView.id)) as MainNavHostFragment navController = navHostFragment.navController binding.bottomNavigationView.setupWithNavController(navController) val appBarConfiguration = AppBarConfiguration(navController.graph) binding.toolbar.setupWithNavController(navController, appBarConfiguration) binding.bottomNavigationView.setOnItemSelectedListener { item -> val currentDestination = navController.currentDestination val isMedicamentosFragment = currentDestination?.id == R.id.medicamentosFragment for (i in 0 until binding.bottomNavigationView.menu.size()) { val menuItem = binding.bottomNavigationView.menu.getItem(i) menuItem.isChecked = false } item.isChecked = true when (item.itemId) { R.id.medicamentosFragment -> { hideToolbarTitle() changeBottomNavigationTheme() if(isMedicamentosFragment){ if(navController.currentDestination?.id != R.id.medicamentosFragment){ navController.navigate(R.id.medicamentosFragment) } }else{ navController.popBackStack() } } R.id.historicoFragment -> { hideToolbarTitle() changeBottomNavigationTheme() if(navController.currentDestination?.id != R.id.historicoFragment){ navController.navigate(R.id.historicoFragment) } } } true } initFragmentListaMedicamentosInterface(navController) } private fun onClickListeners() { binding.btnDeleteMedicamento.setOnClickListener { checarSeFragmentoDetalhesEstaAberto() } } private fun checarSeFragmentoDetalhesEstaAberto() { val nc = findNavController(R.id.fragmentContainerView) verSeDestinoAtualEIgualAFragmentDetalhesMedicamentos(nc) } private fun initFragmentListaMedicamentosInterface(navController: NavController) { verSeDestinoAtualEIgualAFragmentListaMedicamentos(navController) } private fun verSeDestinoAtualEIgualAFragmentListaMedicamentos(nc: NavController) { if (nc.currentDestination?.id == R.id.medicamentosFragment){ val medicamentosFragment = verSeMedicamentosFragmentEstaCertoParaPegarInstancia() if (medicamentosFragment != null) { fragmentListaMedicamentosInterface = medicamentosFragment changeFloatingActionButtonTheme() } } } private fun verSeMedicamentosFragmentEstaCertoParaPegarInstancia(): FragmentListaMedicamentos? { val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment val fragmentMedicamentos = navHostFragment.childFragmentManager.fragments.first() as? FragmentListaMedicamentos if (fragmentMedicamentos != null){ return fragmentMedicamentos } return null } private fun verSeDestinoAtualEIgualAFragmentDetalhesMedicamentos(nc: NavController) { if (nc.currentDestination?.id == R.id.fragmentDetalhesMedicamentos){ val fragmentDetalhes = verSeFragmentoEstaCertoParaPegarInstancia() fragmentDetalhes?.onDeleteMedicamento() } } private fun verSeFragmentoEstaCertoParaPegarInstancia(): FragmentDetalhesMedicamentos? { val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment val fragmentDetalhes = navHostFragment.childFragmentManager.fragments.first() as? FragmentDetalhesMedicamentos if (fragmentDetalhes != null){ return fragmentDetalhes } return null } private fun initViewModel() { sharedViewModel = ViewModelProvider(this)[ActivityHostAndFragmentListaMedicamentosSharedViewModel::class.java] viewModel = ViewModelProvider(this)[MainActivityViewModel::class.java] initCollectors() } private fun mostrarToolbar(mudou: Boolean) { Log.d("callobserver", "observer que vai chamar o metodo que vai mostrar a toolbar foi chamado $mudou") if(mudou){ showToolbar() hideToolbarTitle() hideBtnDeleteMedicamento() } } private fun initCollectors() { lifecycleScope.launchWhenStarted { sharedViewModel.getFragmentListaInstance.collectLatest { fragmentLista-> injetarInstanciaDaInterfaceDaMainActivity(fragmentLista) } } } override fun onResume() { super.onResume() } override fun hideToolbar() { Log.d("callobserver", "encondi a toolbar") binding.toolbar.visibility = View.GONE } override fun hideBtnDeleteMedicamento() { binding.btnDeleteMedicamento.visibility = View.GONE } override fun changeThemeToBlueTheme() { lifecycleScope.launch { themeDataStore = DataStoreTheme(applicationContext) val intDataStore = intPreferencesKey("theme_key") themeDataStore.passThemeToUserChosenTheme(intDataStore, R.style.CustomThemeAzul) withContext(Dispatchers.Main){ recreate() } } } private fun changeBottomNavigationTextColorToBlue() { binding.bottomNavigationView.itemTextColor = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf(-android.R.attr.state_checked)), intArrayOf(ContextCompat.getColor(this@MainActivity, R.color.blue), ContextCompat.getColor(this@MainActivity, R.color.light_gray))) } private fun changeBottomNavigationIconTintToBlue() { binding.bottomNavigationView.itemIconTintList = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf(-android.R.attr.state_checked)), intArrayOf(ContextCompat.getColor(this@MainActivity, R.color.blue), ContextCompat.getColor(this@MainActivity, R.color.light_gray))) } private fun changeBottomNavigationTextColorToRed() { binding.bottomNavigationView.itemTextColor = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf(-android.R.attr.state_checked)), intArrayOf(ContextCompat.getColor(this@MainActivity, R.color.rosa_salmao), ContextCompat.getColor(this@MainActivity, R.color.light_gray))) } private fun changeBottomNavigationIconTintToRed() { binding.bottomNavigationView.itemIconTintList = ColorStateList(arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf(-android.R.attr.state_checked)), intArrayOf(ContextCompat.getColor(this@MainActivity, R.color.rosa_salmao), ContextCompat.getColor(this@MainActivity, R.color.light_gray))) } override fun changeThemeToRedTheme() { lifecycleScope.launch { themeDataStore = DataStoreTheme(applicationContext) val intDataStore = intPreferencesKey("theme_key") themeDataStore.passThemeToUserChosenTheme(intDataStore, R.style.Theme_AppLembreteMedicamento) withContext(Dispatchers.Main){ recreate() } } } override fun showToolbar() { binding.toolbar.visibility = View.VISIBLE } override fun hideToolbarTitle() { binding.toolbar.title = "" } override fun showBtnDeleteMedicamento() { binding.btnDeleteMedicamento.visibility = View.VISIBLE } override fun getPendingIntentsList(): ArrayList<PendingIntent> { return pendingIntentsList } override fun clearPendingIntentsList() { pendingIntentsList.clear() } override fun addPendingIntentToPendingIntentsList(pi: PendingIntent) { pendingIntentsList.add(pi) } }
0
Kotlin
0
0
ca58da50e8261b8bff5eed592a0523f94bc09f98
15,404
DoseCerta
Apache License 2.0
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/apiTest/kotlin/com/android/build/api/apiTest/buildsrc/ManifestUpdaterTest.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.apiTest.buildsrc import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome import org.junit.Test import kotlin.test.assertNotNull class ManifestUpdaterTest: BuildSrcScriptApiTest() { @Test fun manifestUpdaterTest() { given { addBuildSrc() { testingElements.addGitVersionTask(this) testingElements.addManifestTransformerTask(this) testingElements.addManifestVerifierTask(this) addSource( "src/main/kotlin/ExamplePlugin.kt", // language=kotlin """ import com.android.build.api.artifact.SingleArtifact import org.gradle.api.Plugin import org.gradle.api.Project import java.io.File import com.android.build.api.variant.AndroidComponentsExtension abstract class ExamplePlugin: Plugin<Project> { override fun apply(project: Project) { val gitVersionProvider = project.tasks.register("gitVersionProvider", GitVersionTask::class.java) { it.gitVersionOutputFile.set( File(project.buildDir, "intermediates/gitVersionProvider/output") ) it.outputs.upToDateWhen { false } } val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java) androidComponents.onVariants { variant -> val manifestUpdater = project.tasks.register(variant.name + "ManifestUpdater", ManifestTransformerTask::class.java) { it.gitInfoFile.set(gitVersionProvider.flatMap(GitVersionTask::gitVersionOutputFile)) } variant.artifacts.use(manifestUpdater) .wiredWithFiles( ManifestTransformerTask::mergedManifest, ManifestTransformerTask::updatedManifest) .toTransform(SingleArtifact.MERGED_MANIFEST) project.tasks.register(variant.name + "Verifier", VerifyManifestTask::class.java) { it.apkFolder.set(variant.artifacts.get(SingleArtifact.APK)) it.builtArtifactsLoader.set(variant.artifacts.getBuiltArtifactsLoader()) } } } } """.trimIndent() ) } addModule(":app") { addCommonBuildFile(this) testingElements.addManifest(this) testingElements.addMainActivity(this) } } check { assertNotNull(this) Truth.assertThat(output).contains("BUILD SUCCESSFUL") arrayOf( ":app:debugManifestUpdater", ":app:processDebugMainManifest", ":app:gitVersionProvider" ).forEach { val task = task(it) assertNotNull(task) Truth.assertThat(task.outcome).isEqualTo(TaskOutcome.SUCCESS) } } } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
4,138
CppBuildCacheWorkInProgress
Apache License 2.0
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemStickerContentProvider.kt
element-hq
546,522,002
false
{"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.messages.impl.timeline.model.event import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.media3.common.MimeTypes import io.element.android.libraries.matrix.api.media.MediaSource import io.element.android.libraries.matrix.ui.components.A_BLUR_HASH open class TimelineItemStickerContentProvider : PreviewParameterProvider<TimelineItemStickerContent> { override val values: Sequence<TimelineItemStickerContent> get() = sequenceOf( aTimelineItemStickerContent(), aTimelineItemStickerContent().copy(aspectRatio = 1.0f), aTimelineItemStickerContent().copy(aspectRatio = 1.5f), ) } fun aTimelineItemStickerContent() = TimelineItemStickerContent( body = "a body", mediaSource = MediaSource(""), thumbnailSource = null, mimeType = MimeTypes.IMAGE_JPEG, blurhash = A_BLUR_HASH, width = null, height = 128, aspectRatio = 0.5f, formattedFileSize = "4MB", fileExtension = "jpg" )
263
Kotlin
129
955
31d0621fa15fe153bfd36104e560c9703eabe917
1,635
element-x-android
Apache License 2.0
vscode/src/jsMain/kotlin/vscode/TreeCheckboxChangeEvent.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
package vscode import js.array.JsTuple2 import js.array.ReadonlyArray /** * An event describing the change in a tree item's checkbox state. */ external interface TreeCheckboxChangeEvent<T> { /** * The items that were checked or unchecked. */ val items: ReadonlyArray<JsTuple2<T, TreeItemCheckboxState>> }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
319
kotlin-externals
MIT License
src/main/kotlin/internals/systemCalls/calls/readFile.kt
ChippyPlus
850,474,357
false
{"Kotlin": 137591, "Python": 2332, "Java": 228, "Shell": 148}
package internals.systemCalls.calls import data.registers.enumIdenifiers.SuperRegisterType import data.registers.enumIdenifiers.SuperRegisterType.R2 import errors import fileDescriptors import helpers.VMFile import helpers.fullRegisterRead import helpers.fullRegisterWrite import helpers.writeClosestString import internals.systemCalls.SystemCall /** * Reads data from a file into a buffer in memory. * * System call number: 1 * * @param fd The file descriptor of the file to read from (stored in register S2). * @param buffer The starting address of the buffer in memory to store the read data (stored in register S3). */ @Suppress("RemoveExplicitTypeArguments") fun SystemCall.readFile(fd: SuperRegisterType, buffer: SuperRegisterType): Unit = try { val f: VMFile = fileDescriptors.getFileDescriptor(fd = fullRegisterRead(register = fd)) ?: throw NullPointerException( "Expression 'fileDescriptors.getFileDescriptor(fd = fullRegisterRead(register = fd))' must not be null" ) fullRegisterWrite( register = R2, value = writeClosestString(string = f.file.readText()) ) } catch (_: Exception) { with(errors) { this@with.SystemCallGeneralException(message = buildString { append("readFile") }) } }
0
Kotlin
0
1
6308a3208d63f5865931a1439a3f828b28a6af8f
1,298
MVM
MIT License
src/main/kotlin/com/tang/hwplib/reader/util/CompoundFileReader.kt
accforaus
169,677,219
false
null
package com.tang.hwplib.reader.util import com.tang.hwplib.objects.fileheader.HWPFileVersion import com.tang.hwplib.util.exceptions.StreamReaderException import org.apache.poi.poifs.filesystem.DirectoryEntry import org.apache.poi.poifs.filesystem.DocumentEntry import org.apache.poi.poifs.filesystem.Entry import org.apache.poi.poifs.filesystem.POIFSFileSystem import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream internal class CompoundFileReader { private var fs: POIFSFileSystem private var currentStorage: DirectoryEntry constructor(file : File) { fs = try { POIFSFileSystem(file) } catch (e: IOException) { throw StreamReaderException("On error reading", e) } currentStorage = fs.root } constructor(inputStream: InputStream) { fs = try { POIFSFileSystem(inputStream) } catch (e: IOException) { throw StreamReaderException("On error reading", e) } currentStorage = fs.root } fun listChildNames(): Set<String> = currentStorage.entryNames fun isChildStorage(name: String) : Boolean = try { currentStorage.hasEntry(name) && currentStorage.getEntry(name).isDirectoryEntry } catch(e: FileNotFoundException) { throw StreamReaderException("Storage has not $name storage", e)} fun isChildStream(name: String) : Boolean = try { currentStorage.hasEntry(name) && currentStorage.getEntry(name).isDocumentEntry } catch(e: FileNotFoundException) { throw StreamReaderException("Storage has not $name streams", e)} fun moveChildStorage(name: String) { val e: Entry = try { currentStorage.getEntry(name) } catch (e: FileNotFoundException) { throw StreamReaderException("This is not a storage", e)} when(e is DirectoryEntry) { true -> currentStorage = e else -> throw StreamReaderException("this is not storage.") } } fun moveParentStorage() { if (currentStorage != fs.root) currentStorage = currentStorage.parent } fun getChildStreamReader(name: String, compress: Boolean, fileVersion: HWPFileVersion) : StreamReader = try { currentStorage.getEntry(name).run { when (this is DocumentEntry) { true -> when (compress) { true -> StreamReaderForCompress(this, fileVersion) else -> StreamReaderForNormal(this, fileVersion) } else -> throw StreamReaderException("This is not stream") } } } catch (e: FileNotFoundException) { throw StreamReaderException("this is not storage", e)} fun close() { try { fs.close() } catch (e: IOException) { throw StreamReaderException(e.message ?: "", e) } } }
1
null
7
22
b828271f12a885dece5af5aa6281a1b2cf84d459
2,741
libhwp
Apache License 2.0
src/main/kotlin/com/codeflix/admin/catalog/domain/validation/handler/Notification.kt
Fernandounuts
753,396,308
false
{"Kotlin": 24619}
package com.codeflix.admin.catalog.domain.validation.handler import com.codeflix.admin.catalog.domain.exceptions.DomainException import com.codeflix.admin.catalog.domain.validation.Error import com.codeflix.admin.catalog.domain.validation.Validation import com.codeflix.admin.catalog.domain.validation.ValidationHandler class Notification private constructor( private val errors: MutableList<Error> ): ValidationHandler { override fun append(error: Error): ValidationHandler { this.errors.add(error) return this } override fun append(validationHandler: ValidationHandler): Notification { this.errors.addAll(validationHandler.getErrors()) return this } override fun validate(validation: Validation): ValidationHandler { try { validation.validate() } catch (de: DomainException) { this.errors.addAll(de.getErrors()) } catch (t: Throwable) { this.errors.add(Error(t.message.toString())) } return this } override fun getErrors(): List<Error> { return this.errors } companion object { fun new(t: Throwable): Notification { return new(Error(t.message)) } fun new(): Notification { return Notification(arrayListOf()) } fun new(error: Error): Notification { val notification = Notification(mutableListOf()) notification.append(error) return notification } } }
0
Kotlin
0
0
f3c453852418ecf746a6993594b2a12b32fd359e
1,529
CodeFlix-Catalog
MIT License
app/src/main/java/net/appitiza/workmanager/app/moderno.kt
appitiza
131,850,434
false
null
package net.appitiza.workmanager.app import android.app.Application import android.support.multidex.MultiDexApplication import net.appitiza.workmanager.constants.Constants import net.appitiza.workmanager.utils.PreferenceHelper class Moderno : MultiDexApplication() { override fun onCreate() { super.onCreate() PreferenceHelper.init(this, Constants.PREF_NAME) } }
2
Kotlin
3
5
adab092ddb838726cfbf24390728665effea2abf
388
workmanager
The Unlicense
app/src/main/java/com/wadera/kevin/opentracks_kotlin/settings/PreferencesOpenHelper.kt
kevwad
799,286,250
false
{"Kotlin": 5911}
package com.wadera.kevin.opentracks_kotlin.settings class PreferencesOpenHelper { companion object { fun newInstance(version: Int): PreferencesOpenHelper { return PreferencesOpenHelper(version) } } private val version: Int private constructor(version: Int) { this.version = version } }
0
Kotlin
0
0
589c69f9e0530d1b3a3eeb8131773c97d208768f
346
OpenTracks-Kotlin
Apache License 2.0
app/src/main/java/com/goiz/pokedex/model/pokemon/Species.kt
gsesdras
311,452,829
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 193, "XML": 45, "Java": 1, "JSON": 1}
package com.goiz.pokedex.model.pokemon data class Species( val name: String, val url: String )
1
null
1
1
3d36c4f787ff76be4d327c19b45608c253ebdca8
103
afrodev_pokedex
MIT License
app/src/main/java/com/himanshuw/yff/HomeActivity.kt
waliahimanshu
294,806,425
false
null
package com.himanshuw.yff import android.annotation.SuppressLint import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.compose.ui.platform.setContent import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.himanshuw.yff.databinding.ActivityHomeBinding @SuppressLint("attachBaseContext") class HomeActivity : AppCompatActivity() { private lateinit var binding: ActivityHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_home) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. val appBarConfiguration = AppBarConfiguration(setOf( R.id.navigation_home, R.id.navigation_add_record, R.id.navigation_read_more)) // setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } }
1
Kotlin
0
0
63c89ba36b4089a9de8e9b62c4144c8a5ba2c3ce
1,427
YFF
MIT License
app/src/main/java/io/arjuningole/gpt/navGraph.kt
Arjun-Ingole
556,588,324
false
{"Kotlin": 18889}
package io.arjuningole.gpt import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import io.arjuningole.gpt.home.HomeScreen import io.arjuningole.gpt.output.OutputScreen import io.arjuningole.gpt.services.story @Composable fun SetupNavGraph( navController : NavHostController ){ NavHost( navController = navController, startDestination = Screen.Home.route) { composable( Screen.Home.route ){ HomeScreen(navController = navController) } composable( Screen.Output.route ){ OutputScreen(navController) } } }
0
Kotlin
0
15
7ace9819d3548ff05d0b8862694c9e4940dccdb2
756
GPT-3.kt
The Unlicense
app/src/main/java/com/frogobox/kickstart/FrogoApplication.kt
100daycode
378,601,560
false
null
package com.frogobox.kickstart import android.app.Application import com.frogobox.kickstart.di.repositoryModule import com.frogobox.kickstart.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level /* * Created by <NAME> on 23/10/2020 * KickStartProject Source Code * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2020 FrogoBox Inc. * All rights reserved * */ class FrogoApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@FrogoApplication) androidLogger(Level.NONE) modules(listOf(repositoryModule, viewModelModule)) } } }
0
Kotlin
0
0
a99bee5301fbdeb6e5bfde89b9b23ae1006e9329
928
learn-kotlin
Apache License 2.0
app/src/main/java/com/xdzl/golden/mango/application/viewmodel/MainViewModelFactory.kt
xhh4215
315,176,301
false
null
package com.xdzl.golden.mango.application.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import java.lang.IllegalArgumentException class MainViewModelFactory(private val loginStatus: String) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(loginStatus) as T } throw IllegalArgumentException("unknow ViewModel Class") } }
1
null
1
1
beae1136c4e66e0706554fd73148c5a70af9aad8
538
JetPackProject
Apache License 2.0
composeApp/shared/src/commonMain/kotlin/shared/features/carcasses/CarcassesScreen.kt
joharei
772,430,932
false
{"Kotlin": 57435, "Swift": 1006}
package shared.features.carcasses import androidx.compose.animation.Crossfade import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.PlainTooltip import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.jetbrains.compose.resources.stringResource import org.jetbrains.compose.ui.tooling.preview.Preview import shared.features.carcasses.components.Carcass import shared.features.carcasses.models.CarcassUiState import shared.features.carcasses.models.CarcassesUiState import shared.ui.theme.AppTheme import shared.utils.plus import tender.composeapp.shared.generated.resources.Res import tender.composeapp.shared.generated.resources.carcasses_button_add_new import tender.composeapp.shared.generated.resources.carcasses_title import kotlin.time.Duration.Companion.days @OptIn(ExperimentalMaterial3Api::class) @Composable fun CarcassesScreen( modifier: Modifier = Modifier, uiState: CarcassesUiState, onAddNewClick: () -> Unit, onDeleteClick: (carcassId: Long) -> Unit, onEditClick: (carcassId: Long) -> Unit, ) { Scaffold( modifier = modifier, topBar = { CenterAlignedTopAppBar(title = { Text(stringResource(Res.string.carcasses_title)) }) }, floatingActionButton = { TooltipBox( positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), tooltip = { PlainTooltip { Text(stringResource(Res.string.carcasses_button_add_new)) } }, state = rememberTooltipState(), ) { FloatingActionButton(onClick = onAddNewClick) { Icon(Icons.Default.Add, contentDescription = stringResource(Res.string.carcasses_button_add_new)) } } }, ) { contentPadding -> Crossfade( targetState = uiState.loading, ) { Box(Modifier.fillMaxSize()) { if (!it) { LazyVerticalGrid( modifier = Modifier .align(Alignment.TopCenter) .sizeIn(maxWidth = 800.dp), contentPadding = contentPadding + PaddingValues(16.dp), columns = GridCells.Adaptive(200.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { items(uiState.carcasses) { Carcass( state = it, onDeleteClick = { onDeleteClick(it.id) }, onEditClick = { onEditClick(it.id) }, ) } } } } } } } @Preview @Composable private fun Preview() { AppTheme { CarcassesScreen( uiState = CarcassesUiState( carcasses = List(7) { CarcassUiState( id = it.toLong(), name = "Kjøtt $it", durationSinceStarted = it.days, durationUntilDueEstimate = it.days, progress = it / 7f, current24HoursDegrees = it * 10.0, ) }, loading = false, ), onAddNewClick = {}, onDeleteClick = {}, onEditClick = {}, ) } }
0
Kotlin
0
0
afba1f62445f6b5a532c754cf16ccb781adb3ade
3,785
tender
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageprisonvisitsorchestration/integration/prisoner/profile/GetPrisonerProfileTest.kt
ministryofjustice
575,484,836
false
null
package uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration.prisoner.profile import org.assertj.core.api.Assertions import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.springframework.beans.factory.annotation.Value import org.springframework.boot.test.mock.mockito.SpyBean import org.springframework.http.HttpHeaders import org.springframework.test.web.reactive.server.WebTestClient import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.client.PrisonApiClient import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.client.PrisonerOffenderSearchClient import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.client.VisitSchedulerClient import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.PrisonerProfileDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prison.api.AlertDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prison.api.InmateDetailDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prison.api.PrisonerBookingSummaryDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prison.api.VisitBalancesDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prisoner.search.CurrentIncentive import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prisoner.search.IncentiveLevel import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.prisoner.search.PrisonerDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.visit.scheduler.VisitDto import uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.integration.IntegrationTestBase import java.time.LocalDate import java.time.LocalDateTime import java.time.Period import java.time.temporal.ChronoUnit import java.time.temporal.TemporalAdjusters @DisplayName("Get Prisoner Profile") class GetPrisonerProfileTest( @Value("\${prisoner.profile.past-visits.duration-in-months: -P3M}") private val pastVisitsPeriod: Period, @Value("\${prisoner.profile.future-visits.duration-in-months: P2M}") private val futureVisitsPeriod: Period, ) : IntegrationTestBase() { companion object { private const val prisonerId = "AA112233B" private const val firstName = "FirstName" private const val lastName = "LastName" private val dateOfBirth = LocalDate.of(2000, 1, 31) private const val category = "Category - C" private const val prisonId = "MDI" private val alert = AlertDto(comment = "Alert 1", alertCode = "C", alertCodeDescription = "Alert Code Desc", alertType = "T", alertTypeDescription = "Type Description", dateCreated = LocalDate.now()) } private final val currentIncentive = createCurrentIncentive() private final val prisonerDto = createPrisoner( prisonerId = prisonerId, firstName = firstName, lastName = lastName, dateOfBirth = dateOfBirth, currentIncentive = currentIncentive, ) private final val alerts = listOf(alert) private final val inmateDetailDto = createInmateDetails(prisonerId, category, alerts) private final val visitBalancesDto = createVisitBalancesDto() private final val prisonerBookingSummaryDto = createPrisonerBookingSummary(prisonerId, "Convicted") private final val visit1 = createVisitDto(reference = "visit-1", prisonerId = prisonerId) private final val visit2 = createVisitDto(reference = "visit-2", prisonerId = prisonerId) @SpyBean lateinit var visitSchedulerClientSpy: VisitSchedulerClient @SpyBean lateinit var prisonAPiClientSpy: PrisonApiClient @SpyBean lateinit var prisonerOffenderSearchClientSpy: PrisonerOffenderSearchClient fun callGetPrisonerProfile( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, prisonId: String, prisonerId: String, ): WebTestClient.ResponseSpec { return webTestClient.get().uri("/prisoner/$prisonId/$prisonerId/profile") .headers(authHttpHeaders) .exchange() } @Test fun `when valid prisoner prisoner profile is collated and returned`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isEqualTo(prisonerDto.currentIncentive!!.level.description) assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isEqualTo(prisonerBookingSummaryDto.convictedStatus) Assertions.assertThat(prisonerProfile.visitBalances).isEqualTo(visitBalancesDto) Assertions.assertThat(prisonerProfile.visits.size).isEqualTo(2) assertVisits(prisonerProfile, listOf(visit1, visit2)) verifyExternalAPIClientCalls() } @Test fun `when prison API get prisoner details returns NOT_FOUND prisoner profile call returns NOT_FOUND status`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, null) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then responseSpec.expectStatus().isNotFound verifyExternalAPIClientCalls() } @Test fun `when prison API get inmate details returns NOT_FOUND prisoner profile call returns NOT_FOUND status`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, null) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then responseSpec.expectStatus().isNotFound verifyExternalAPIClientCalls() } @Test fun `when prison returned by prison API does not match prison id passed to endpoint prisoner profile call returns internal server error`() { // Given prisoner's prison ID is different to the prison ID passed in endpoint val prisonerDto = createPrisoner( prisonerId = prisonerId, prisonId = "XYZ", firstName = firstName, lastName = lastName, dateOfBirth = dateOfBirth, currentIncentive = currentIncentive, ) prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then responseSpec.expectStatus().is4xxClientError verifyExternalAPIClientCalls() } @Test fun `when prison API get visit balances returns NOT_FOUND prisoner profile call returns a profile profile with visitBalances as null`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, null) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isEqualTo(prisonerDto.currentIncentive!!.level.description) assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isEqualTo(prisonerBookingSummaryDto.convictedStatus) Assertions.assertThat(prisonerProfile.visitBalances).isNull() Assertions.assertThat(prisonerProfile.visits.size).isEqualTo(2) assertVisits(prisonerProfile, listOf(visit1, visit2)) verifyExternalAPIClientCalls() } @Test fun `when prison API get bookings returns no records some prisoner profile details are blank`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) // get bookings will return empty contents prisonApiMockServer.stubGetBookings(prisonId, prisonerId, mutableListOf()) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isEqualTo(prisonerDto.currentIncentive!!.level.description) assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isNull() Assertions.assertThat(prisonerProfile.visitBalances).isEqualTo(visitBalancesDto) assertVisits(prisonerProfile, listOf(visit1, visit2)) verifyExternalAPIClientCalls() } @Test fun `when prison API get bookings returns multiple records only 1st one is populated on prisoner profile`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) val prisonerBookingSummaryDto1 = createPrisonerBookingSummary(prisonerId, "Remand") prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto, prisonerBookingSummaryDto1)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isEqualTo(prisonerDto.currentIncentive!!.level.description) assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isEqualTo(prisonerBookingSummaryDto.convictedStatus) Assertions.assertThat(prisonerProfile.visitBalances).isEqualTo(visitBalancesDto) assertVisits(prisonerProfile, listOf(visit1, visit2)) verifyExternalAPIClientCalls() } @Test fun `when prison API get prisoner current incentive is null prisoner profile current incentive is null`() { // Given val prisonerDto = createPrisoner( prisonerId = prisonerId, firstName = firstName, lastName = lastName, dateOfBirth = dateOfBirth, currentIncentive = null, ) prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(listOf(visit1, visit2)) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isNull() assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isEqualTo(prisonerBookingSummaryDto.convictedStatus) Assertions.assertThat(prisonerProfile.visitBalances).isEqualTo(visitBalancesDto) assertVisits(prisonerProfile, listOf(visit1, visit2)) verifyExternalAPIClientCalls() } @Test fun `when visits do not exist for prisoner visits list is empty`() { // Given prisonOffenderSearchMockServer.stubGetPrisonerById(prisonerId, prisonerDto) prisonApiMockServer.stubGetInmateDetails(prisonerId, inmateDetailDto) prisonApiMockServer.stubGetBookings(prisonId, prisonerId, listOf(prisonerBookingSummaryDto)) prisonApiMockServer.stubGetVisitBalances(prisonerId, visitBalancesDto) stubGetVisits(mutableListOf()) // When val responseSpec = callGetPrisonerProfile(webTestClient, roleVisitSchedulerHttpHeaders, prisonId, prisonerId) // Then val returnResult = responseSpec.expectStatus().isOk.expectBody() val prisonerProfile = getResults(returnResult) assertPrisonerDtoDetails(prisonerProfile, prisonerDto) Assertions.assertThat(prisonerProfile.incentiveLevel).isEqualTo(prisonerDto.currentIncentive!!.level.description) assertInmateDetails(prisonerProfile, inmateDetailDto) Assertions.assertThat(prisonerProfile.convictedStatus).isEqualTo(prisonerBookingSummaryDto.convictedStatus) Assertions.assertThat(prisonerProfile.visitBalances).isEqualTo(visitBalancesDto) Assertions.assertThat(prisonerProfile.visits).isEmpty() verifyExternalAPIClientCalls() } private fun assertPrisonerDtoDetails(prisonerProfile: PrisonerProfileDto, prisonerDto: PrisonerDto) { Assertions.assertThat(prisonerProfile.prisonerId).isEqualTo(prisonerDto.prisonerNumber) Assertions.assertThat(prisonerProfile.firstName).isEqualTo(prisonerDto.firstName) Assertions.assertThat(prisonerProfile.lastName).isEqualTo(prisonerDto.lastName) Assertions.assertThat(prisonerProfile.dateOfBirth).isEqualTo(prisonerDto.dateOfBirth) Assertions.assertThat(prisonerProfile.prisonId).isEqualTo(prisonerDto.prisonId) Assertions.assertThat(prisonerProfile.prisonName).isEqualTo(prisonerDto.prisonName) Assertions.assertThat(prisonerProfile.cellLocation).isEqualTo(prisonerDto.cellLocation) } private fun assertInmateDetails(prisonerProfile: PrisonerProfileDto, inmateDetails: InmateDetailDto) { Assertions.assertThat(prisonerProfile.category).isEqualTo(inmateDetails.category) Assertions.assertThat(prisonerProfile.alerts).isEqualTo(inmateDetails.alerts) } private fun assertVisits(prisonerProfile: PrisonerProfileDto, visits: List<VisitDto>) { val visitReferences = prisonerProfile.visits.stream().map { it.reference }.toList() Assertions.assertThat(prisonerProfile.visits.size).isEqualTo(visits.size) visits.forEach { Assertions.assertThat(visitReferences).contains(it.reference) } } private fun getResults(returnResult: WebTestClient.BodyContentSpec): PrisonerProfileDto { return objectMapper.readValue(returnResult.returnResult().responseBody, PrisonerProfileDto::class.java) } private fun createPrisoner( prisonerId: String, firstName: String, lastName: String, dateOfBirth: LocalDate, prisonId: String = "MDI", prisonName: String = "<NAME>", cellLocation: String? = null, currentIncentive: CurrentIncentive? = null, ): PrisonerDto { return PrisonerDto( prisonerNumber = prisonerId, firstName = firstName, lastName = lastName, dateOfBirth = dateOfBirth, prisonId = prisonId, prisonName = prisonName, cellLocation = cellLocation, currentIncentive = currentIncentive, ) } private fun createInmateDetails( prisonerId: String, category: String? = null, alerts: List<AlertDto>? = null, ): InmateDetailDto { return InmateDetailDto(offenderNo = prisonerId, category = category, alerts = alerts) } private fun createVisitBalancesDto(): VisitBalancesDto { return VisitBalancesDto(remainingVo = 10, remainingPvo = 10) } private fun createCurrentIncentive(): CurrentIncentive { val incentiveLevel = IncentiveLevel("S", "Standard") return CurrentIncentive(incentiveLevel, LocalDateTime.now()) } private fun createPrisonerBookingSummary(prisonerId: String, convictedStatus: String): PrisonerBookingSummaryDto { return PrisonerBookingSummaryDto(prisonerId, convictedStatus) } private fun stubGetVisits(visits: List<VisitDto>) { visitSchedulerMockServer.stubGetVisits( prisonerId, listOf("BOOKED", "CANCELLED"), LocalDateTime.now().minus(pastVisitsPeriod).with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS), LocalDateTime.now().plus(futureVisitsPeriod).with(TemporalAdjusters.lastDayOfMonth()).truncatedTo(ChronoUnit.DAYS), 0, 1000, visits, ) } private fun verifyExternalAPIClientCalls() { verify(visitSchedulerClientSpy, times(1)).getVisitsAsMono(any()) verify(prisonerOffenderSearchClientSpy, times(1)).getPrisonerByIdAsMono(any()) verify(prisonAPiClientSpy, times(1)).getInmateDetailsAsMono(any()) verify(prisonAPiClientSpy, times(1)).getVisitBalancesAsMono(any()) verify(prisonAPiClientSpy, times(1)).getBookingsAsMono(any(), any()) } }
3
Kotlin
0
2
5c7b703730a6019e7d910b946b77974ae6082463
18,476
hmpps-manage-prison-visits-orchestration
MIT License
Server/src/main/java/i/blog/handlers/exceptions/ExceptionUtils.kt
ExplodingDragon
331,065,842
false
null
package i.blog.handlers.exceptions import org.springframework.http.HttpStatus object ExceptionUtils { fun httpRequestException(httpStatus: HttpStatus): ApplicationException = ApplicationException(httpStatus.value(), httpStatus.reasonPhrase) fun badRequest(msg: String = "Bad Request!"): ApplicationException { return ApplicationException(400, msg) } fun internalException(msg: String = "未知错误!"): ApplicationException = ApplicationException(500, msg) fun forbidden(contextPath: String): ApplicationException { return ApplicationException(403, "没有权限 $contextPath") } fun notFound(path: String): ApplicationException { return ApplicationException(404, "路径 $path 未找到.") } /** * 错误信息处理 * * @property errorId Int * @property errorMessage String * @constructor */ class ApplicationException(val errorId: Int, val errorMessage: String = "未知错误!") : RuntimeException(errorMessage) { } }
0
Kotlin
0
0
36ee137d27f6cd378a28753d2b557ff16b01e65b
990
Blog
MIT License
src/main/kotlin/fp/kotlin/example/chapter05/solution/5-18-productByFunStream.kt
funfunStory
101,662,895
false
null
package fp.kotlin.example.chapter05.solution import fp.kotlin.example.chapter05.FunStream import fp.kotlin.example.chapter05.foldLeft import fp.kotlin.example.chapter05.funStreamOf /** * * 연습문제 5-18 * * FunList에서 작성했던 product 함수를 FunStream에도 추가하자. * * 힌트: 함수의 선언 타입은 아래와 같다. * */ fun main() { require(funStreamOf(1, 2, 3, 4, 5).product() == 1 * 2 * 3 * 4 * 5) } fun FunStream<Int>.product(): Int = when (this) { FunStream.Nil -> 1 is FunStream.Cons -> foldLeft(1) { acc, value -> acc * value } }
1
Kotlin
23
39
bb10ea01d9f0e1b02b412305940c1bd270093cb6
519
fp-kotlin-example
MIT License
app/src/main/java/com/borabor/travelguideapp/presentation/base/BaseFragment.kt
bbor98
549,990,639
false
{"Kotlin": 85117}
package com.borabor.travelguideapp.presentation.base import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.databinding.library.baseAdapters.BR import androidx.fragment.app.Fragment abstract class BaseFragment<B : ViewDataBinding>(@LayoutRes private val layoutId: Int) : Fragment() { private var _binding: B? = null protected val binding get() = _binding!! abstract val viewModel: BaseViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = DataBindingUtil.inflate<B>(inflater, layoutId, container, false).apply { _binding = this lifecycleOwner = viewLifecycleOwner setVariable(BR.viewModel, viewModel) }.root override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
1
5905569b24a455f37e98f1dde409eddb8b7a9582
1,022
travel-guide-app
MIT License
arch/src/main/java/arch/BaseApp.kt
slp
250,540,490
true
{"Kotlin": 183410, "Java": 1863}
package arch import androidx.multidex.MultiDexApplication open class BaseApp : MultiDexApplication() { companion object { lateinit var instance: BaseApp private set } override fun onCreate() { super.onCreate() instance = this } }
2
Kotlin
2
7
d5a9adff1e14cde72790b02dbbae92f7272e8ad2
273
erouska-android
MIT License
apollo-engine-reporter/src/test/kotlin/com/gabrielterwesten/apollo/engine/E2ETest.kt
blaugold
222,702,655
false
{"Gradle Kotlin DSL": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "YAML": 2, "XML": 11, "Kotlin": 36, "Java": 1}
package com.gabrielterwesten.apollo.engine import graphql.GraphQL import graphql.execution.instrumentation.ChainedInstrumentation import graphql.execution.instrumentation.tracing.TracingInstrumentation import graphql.schema.StaticDataFetcher import graphql.schema.idl.RuntimeWiring import graphql.schema.idl.SchemaGenerator import graphql.schema.idl.SchemaParser import org.junit.jupiter.api.Test class E2ETest { private val testApiKey = "service:java-apollo-engine-reporter:9AHOL8XylVxVkjL_MLKGXg" @Test fun smoke() { val schema = """ type Query { hello: String error: String } """.trimIndent() val typeDefinitionRegistry = SchemaParser().parse(schema) val runtimeWiring = RuntimeWiring.newRuntimeWiring() .type("Query") { it.dataFetcher("hello", StaticDataFetcher("World")) it.dataFetcher("error") { throw IllegalArgumentException("Whops") } } .build() val reporter = ApolloEngineReporter( traceShipper = DefaultTraceShipper(apiKey = testApiKey), querySignatureStrategy = DefaultQuerySignatureStrategy, reportGenerator = DefaultReportGenerator(), traceInputProcessors = traceInputProcessors() + listOf( traceInputProcessor { it.copy( clientInfo = ClientInfo(name = "E2ETest", version = Version.string)) })) reporter.start() val instrumentation = ChainedInstrumentation( listOf(TracingInstrumentation(), TraceReporterInstrumentation(reporter))) val graphQLSchema = SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, runtimeWiring) val execution = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).build() val result = execution.execute("query { hello error }") println(result.getData<Any>().toString()) reporter.stop() } }
0
Kotlin
0
1
4c4d4464d029426413c062bdb82ca4ce647da261
2,087
apollo-engine-reporter
MIT License
src/academy/learnprogramming/datastructures/EnumExample.kt
bladefistx2
430,293,814
false
{"Kotlin": 19902, "Java": 1795}
package academy.learnprogramming.datastructures enum class Department(val fullName: String, val numEmployees: Int) { HR("Human Resources", 5), IT("Information Technology", 10), ACCOUNTING("Accounting", 3), SALES("Sales", 20); fun getDeptInfo() = "The $fullName department has $numEmployees employees" }
0
Kotlin
0
0
a8349446e202c187a0860614acc503fb412967ea
316
learn-kotlin
Apache License 2.0
app/src/main/java/com/mohmmed/mosa/eg/towmmen/domin/repostory/PurchaseRepository.kt
M4A28
842,519,543
false
{"Kotlin": 877792}
package com.mohmmed.mosa.eg.towmmen.domin.repostory import com.mohmmed.mosa.eg.towmmen.data.module.Purchase import com.mohmmed.mosa.eg.towmmen.data.module.PurchaseItem import com.mohmmed.mosa.eg.towmmen.data.module.PurchaseWithItems import kotlinx.coroutines.flow.Flow interface PurchaseRepository { fun getAllPurchases(): Flow<List<Purchase>> suspend fun insertPurchase(purchase: Purchase) suspend fun deletePurchase(purchase: Purchase) fun getPurchasesByCustomerId(customerId: Int): Flow<List<Purchase>> fun getTotalPurchases(): Flow<Int> fun getTotalPurchasesByCustomer(customerId: Int): Flow<Int> suspend fun upsertPurchaseWithItems(items: List<PurchaseItem>) fun getPurchaseWithItems(): Flow<List<PurchaseWithItems>> fun getPurchaseWithItems(purchaseId: String): Flow<PurchaseWithItems?> fun getPurchaseWithItemsByDealerId(dealerId: Int): Flow<List<PurchaseWithItems>> suspend fun insertFullPurchase(purchase: Purchase, items: List<PurchaseItem>) suspend fun clearPurchasesDate() }
0
Kotlin
0
0
37a6e192262f4995f599978957d1b39257fd88a9
1,049
Towmmen
MIT License
gradle-plugin/src/main/kotlin/com/improve_future/harmonica/task/JarmonicaUpMain.kt
KenjiOhtsuka
132,746,579
false
{"Kotlin": 227314}
/* * Harmonica: Kotlin Database Migration Tool * Copyright (c) 2022 <NAME> * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ package com.improve_future.harmonica.task import com.improve_future.harmonica.plugin.JarmonicaArgument object JarmonicaUpMain : JarmonicaTaskMain() { @JvmStatic fun main(vararg args: String) { val argument = JarmonicaArgument.parse(args) // (classLoader as URLClassLoader).urLs.forEach { // println(it) // } val maxStep = JarmonicaArgument.parseStepString(args[JarmonicaArgument.DEFAULT_ARGUMENT_SIZE]) var stepCounter = 1 val connection = createConnection(argument.migrationPackage, argument.env) try { connection.transaction { versionService.setupHarmonicaMigrationTable(connection) } for (migrationClass in findMigrationClassList(argument.migrationPackage)) { val migrationVersion = versionService.pickUpVersionFromClassName(migrationClass.name) if (versionService.isVersionMigrated(connection, migrationVersion)) continue println("== [Start] Migrate up $migrationVersion ==") connection.transaction { val migration = migrationClass.getConstructor().newInstance() argument.apply(migration) migration.connection = connection migration.up() if (!argument.isReview) versionService.saveVersion(connection, migrationVersion) } println("== [End] Migrate up $migrationVersion ==") if (maxStep != null && ++stepCounter > maxStep) break } connection.close() } catch (e: Exception) { connection.close() throw e } } }
31
Kotlin
17
132
fbb6f54990451e4ffa9d4ad0d9edee4943ebae1a
1,950
harmonica
MIT License
sms-persistence/src/main/kotlin/team/msg/sms/global/config/JpaConfig.kt
GSM-MSG
625,717,097
false
{"Kotlin": 529822, "Shell": 1480, "Dockerfile": 288}
package team.msg.sms.global.config import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.FilterType import org.springframework.data.jpa.repository.config.EnableJpaRepositories @Configuration @EnableJpaRepositories( basePackages = [ "team.msg.sms.persistence.authentication.repository", "team.msg.sms.persistence.certificate.repository", "team.msg.sms.persistence.file.repository", "team.msg.sms.persistence.image.repository", "team.msg.sms.persistence.languagecertificate.repository", "team.msg.sms.persistence.major.repository", "team.msg.sms.persistence.prize.repository", "team.msg.sms.persistence.project.repository", "team.msg.sms.persistence.region.repository", "team.msg.sms.persistence.student.repository", "team.msg.sms.persistence.teacher.repository", "team.msg.sms.persistence.techstack.repository", "team.msg.sms.persistence.user.repository", ], excludeFilters = [ComponentScan.Filter( type = FilterType.ASPECTJ, pattern = ["team.msg.sms.persistence.auth.repository.RefreshTokenRepository", "team.msg.sms.persistence.student.redisRepository.*"] )] ) class JpaConfig
7
Kotlin
0
9
871482bf7f1895f160fe6b6d2b99ff712ae4cd63
1,328
SMS-BackEnd
MIT License
app/src/main/java/me/simonpojok/sportlive/ui/common/fragments/destination/UiDestinationToNavigationMapper.kt
simonpojok
525,328,215
false
null
package me.simonpojok.sportlive.ui.common.fragments.destination import me.simonpojok.sportlive.ui.common.viewmodel.Destination import me.simonpojok.sportlive.ui.common.viewmodel.UiDestination interface UiDestinationToNavigationMapper { fun map(destination: Destination): UiDestination }
0
Kotlin
0
0
a21ab137d08e03862bde485a8fe2329f17bfa9c4
293
sportLive
MIT License
src/main/kotlin/wiki/mdzz/utils/tree/Trie.kt
limitLiu
231,546,946
false
null
package wiki.mdzz.utils.tree import wiki.mdzz.utils.map.HashMap class Trie<V> { private var size = 0 private var root: Node<V>? = null fun size(): Int { return size } val isEmpty: Boolean get() = size() == 0 fun clear() { size = 0 root = null } fun add(key: String?, value: V?): V? { check(key) if (root == null) { root = Node(null) } var node = root for (c in key!!) { var child = node!!.children?.get(c) if (child == null) { child = Node(node) child.character = c node.children = if (node.hasChildren()) { node.children } else { HashMap() } node.children!!.put(c, child) } node = child } if (node!!.isWord) { val old = node.value node.value = old return old } node.isWord = true node.value = value ++size return null } operator fun get(key: String?): V? { val node = getNode(key) return if (node in this) { node!!.value } else { null } } fun remove(key: String): V? { var node = getNode(key) if (node !in this) return null --size val old = node!!.value if (!(node.isNullOrEmpty())) { node.isWord = false node.value = null return old } var parent: Node<V>? while (node!!.parent.also { parent = it } != null) { parent!!.children!!.remove(node.character) if (parent!!.isWord || !parent!!.children!!.isEmpty) break node = parent } return old } fun startsWith(prefix: String?): Boolean { return getNode(prefix) != null } operator fun contains(key: String?): Boolean { val node = getNode(key) return node in this } private operator fun contains(node: Node<V>?): Boolean { return node != null && node.isWord } private fun getNode(key: String?): Node<V>? { check(key) var node: Node<V>? = root for (c in key!!) { if (node == null || node.isNullOrEmpty()) return null node = node.children!![c] } return node } private fun check(key: String?) { if (key.isNullOrEmpty()) { throw IllegalArgumentException("Key must not be empty.") } } inner class Node<V>(var parent: Node<V>?) { var children: HashMap<Char, Node<V>>? = null var value: V? = null var isWord = false var character: Char? = null fun isNullOrEmpty(): Boolean { return children == null || children!!.isEmpty } fun hasChildren(): Boolean { return children != null } } }
0
Kotlin
1
0
e613e47ad22d42eb4efa0b99f6f9da620e63982d
3,017
algorithm
MIT License
domain/src/main/java/com/aitor/samplemarket/domain/usecase/FetchDiscounts.kt
JavierSegoviaCordoba
292,857,508
true
{"Kotlin": 62708}
package com.aitor.samplemarket.domain.usecase import arrow.core.Option import com.aitor.samplemarket.domain.model.Discount class FetchDiscounts(private val discountRepository: com.aitor.samplemarket.domain.repository.DiscountRepository) { operator fun invoke(): Option<Discount> { return discountRepository.fetchDiscounts() } }
0
null
0
0
09b85b990004955b2a9b50150cde528a7716bc27
345
Android-Market-App-CleanArchitecture
Apache License 2.0
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Bitcoinsv.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.simpleicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.SimpleIcons public val SimpleIcons.Bitcoinsv: ImageVector get() { if (_bitcoinsv != null) { return _bitcoinsv!! } _bitcoinsv = Builder(name = "Bitcoinsv", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.648f, 14.423f) lineToRelative(0.003f, -0.004f) arcToRelative(1.34f, 1.34f, 0.0f, false, true, -0.498f, 0.659f) curveToRelative(-0.269f, 0.189f, -0.647f, 0.338f, -1.188f, 0.364f) lineToRelative(-1.99f, 0.004f) verticalLineToRelative(-2.93f) curveToRelative(0.288f, 0.008f, 1.565f, -0.013f, 2.119f, 0.015f) curveToRelative(0.722f, 0.035f, 1.171f, 0.321f, 1.41f, 0.668f) curveToRelative(0.262f, 0.351f, 0.293f, 0.82f, 0.144f, 1.224f) close() moveTo(12.519f, 11.162f) curveToRelative(0.503f, -0.024f, 0.852f, -0.162f, 1.101f, -0.336f) curveToRelative(0.214f, -0.146f, 0.375f, -0.367f, 0.46f, -0.611f) curveToRelative(0.134f, -0.375f, 0.107f, -0.81f, -0.136f, -1.135f) curveToRelative(-0.223f, -0.319f, -0.638f, -0.584f, -1.306f, -0.616f) curveToRelative(-0.495f, -0.026f, -1.413f, -0.003f, -1.664f, -0.01f) verticalLineToRelative(2.709f) curveToRelative(0.025f, 0.004f, 1.539f, -0.001f, 1.545f, -0.001f) close() moveTo(24.0f, 12.0f) curveToRelative(0.0f, 6.627f, -5.373f, 12.0f, -12.0f, 12.0f) reflectiveCurveTo(0.0f, 18.627f, 0.0f, 12.0f) reflectiveCurveTo(5.373f, 0.0f, 12.0f, 0.0f) reflectiveCurveToRelative(12.0f, 5.373f, 12.0f, 12.0f) close() moveTo(17.35f, 14.142f) curveToRelative(0.022f, -1.477f, -1.24f, -2.332f, -1.908f, -2.572f) curveToRelative(0.715f, -0.491f, 1.206f, -1.043f, 1.206f, -2.085f) curveToRelative(0.0f, -1.655f, -1.646f, -2.43f, -2.647f, -2.529f) curveToRelative(-0.082f, -0.009f, -0.31f, -0.013f, -0.31f, -0.013f) lineTo(13.691f, 5.361f) horizontalLineToRelative(-1.633f) lineToRelative(0.004f, 1.583f) lineTo(10.97f, 6.944f) lineTo(10.97f, 5.367f) lineTo(9.31f, 5.367f) verticalLineToRelative(1.569f) curveToRelative(-0.292f, 0.007f, -2.049f, 0.006f, -2.049f, 0.006f) verticalLineToRelative(1.401f) horizontalLineToRelative(0.571f) curveToRelative(0.601f, 0.016f, 0.822f, 0.362f, 0.798f, 0.677f) verticalLineToRelative(6.041f) arcToRelative(0.408f, 0.408f, 0.0f, false, true, -0.371f, 0.391f) curveToRelative(-0.249f, 0.011f, -0.621f, 0.0f, -0.621f, 0.0f) lineToRelative(-0.32f, 1.588f) horizontalLineToRelative(1.996f) verticalLineToRelative(1.6f) horizontalLineToRelative(1.661f) verticalLineToRelative(-1.591f) horizontalLineToRelative(1.091f) verticalLineToRelative(1.594f) horizontalLineToRelative(1.624f) verticalLineToRelative(-1.588f) curveToRelative(1.899f, 0.05f, 3.643f, -1.071f, 3.66f, -2.913f) close() } } .build() return _bitcoinsv!! } private var _bitcoinsv: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
4,402
compose-icons
MIT License
solidfragment/src/main/java/com/mitteloupe/solid/fragment/handler/NavigationHandler.kt
EranBoudjnah
223,144,820
false
null
package com.mitteloupe.solid.fragment.handler import androidx.fragment.app.Fragment interface NavigationHandler { /** * @see Fragment.onPrimaryNavigationFragmentChanged */ fun onPrimaryNavigationFragmentChanged(isPrimaryNavigationFragment: Boolean) }
0
Kotlin
0
35
c022a6f6d905262647da4cc737b776e5c0601a09
271
solid
MIT License
platform/workspace/storage/tests/testSrc/com/intellij/platform/workspace/storage/tests/AssertConsistencyTest.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.platform.workspace.storage.tests import com.intellij.platform.workspace.storage.impl.AbstractEntityStorage import com.intellij.platform.workspace.storage.impl.assertConsistency import com.intellij.platform.workspace.storage.testEntities.entities.AssertConsistencyEntity import com.intellij.platform.workspace.storage.testEntities.entities.MySource import org.junit.jupiter.api.Test class AssertConsistencyTest { @Test fun `check should pass`() { val builder = createEmptyBuilder() builder addEntity AssertConsistencyEntity(true, MySource) (builder.toSnapshot() as AbstractEntityStorage).assertConsistency() } @Test fun `check should fail`() { val builder = createEmptyBuilder() builder addEntity AssertConsistencyEntity(false, MySource) (builder.toSnapshot() as AbstractEntityStorage).assertConsistency() } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
989
intellij-community
Apache License 2.0
dcache/src/main/java/dora/http/DoraCallback.kt
dora4
378,306,065
false
null
package dora.http import retrofit2.Call import retrofit2.Callback import retrofit2.Response abstract class DoraCallback<M> : Callback<M> { abstract fun onSuccess(model: M) abstract fun onFailure(code: Int, msg: String?) override fun onResponse(call: Call<M>, response: Response<M>) { if (response.isSuccessful) { val body = response.body() if (body != null) { onSuccess(body) } else { onFailure(-1, "Empty Body") } } } override fun onFailure(call: Call<M>, t: Throwable) { onFailure(-1, t.message) } }
0
Kotlin
1
7
99b570a5e04b616ac1cd18be02d086b0f76cc3d9
635
dcache-android
Apache License 2.0
app/src/main/kotlin/br/com/joffer/mango/features/payment/creditcard/CardPrimingPresenter.kt
felipejm
179,542,089
false
{"Kotlin": 63931}
package br.com.joffer.mango.features.payment.creditcard import java.io.Serializable interface CardPrimingPresenter { fun onCreate() fun onReceiveSerializable(serializableExtra: Serializable?) fun onRegisterNewClicked() }
0
Kotlin
0
0
657146c9970511ada26b39cac701c55ab5f0438a
234
Desafio-PicPay-Android-iOS
Apache License 2.0
JPAAnnotationReaderAPI/src/main/kotlin/net/dankito/jpa/apt/serializer/json/ReflectionClassesSerializerBase.kt
dankito
94,338,853
false
{"Gradle": 5, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 47, "Java": 40}
package net.dankito.jpa.apt.serializer.json import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.ser.std.StdSerializer import java.lang.reflect.Member abstract class ReflectionClassesSerializerBase<T: Member>(clazz: Class<T>) : StdSerializer<T>(clazz) { override fun serialize(value: T?, gen: JsonGenerator?, provider: SerializerProvider?) { value?.let { value -> gen?.let { jsonGenerator -> jsonGenerator.writeStartObject() jsonGenerator.writeStringField(SerializerConfig.ClassNameFieldName, value.declaringClass.name) writeInstanceIdentifier(jsonGenerator, value) jsonGenerator.writeEndObject() } } } abstract fun writeInstanceIdentifier(jsonGenerator: JsonGenerator, value: T) }
0
Kotlin
0
0
b58ca2f3cad0e95584b5a783c355a49a03600482
895
jpa-apt
Apache License 2.0
themes/new-ui/new-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/expui/standalone/style/AreaProvider.kt
JetBrains
440,164,967
false
null
package io.kanro.compose.jetbrains.expui.style interface AreaProvider { val normalAreaColors: AreaColors } interface ErrorAreProvider : AreaProvider { val errorAreaColors: AreaColors } interface ErrorFocusAreaProvider : ErrorAreProvider, FocusAreaProvider { val errorFocusAreaColors: AreaColors } interface SelectionAreaProvider : AreaProvider { val selectionAreaColors: AreaColors } interface FocusAreaProvider : AreaProvider { val focusAreaColors: AreaColors } interface DisabledAreaProvider : AreaProvider { val disabledAreaColors: AreaColors } interface HoverAreaProvider : AreaProvider { val hoverAreaColors: AreaColors } interface PressedAreaProvider : AreaProvider { val pressedAreaColors: AreaColors } interface InactiveAreaProvider : AreaProvider { val inactiveAreaColors: AreaColors } interface InactiveErrorAreaProvider : ErrorAreProvider, InactiveAreaProvider { val inactiveErrorAreaColors: AreaColors } interface InactiveSelectionAreaProvider : SelectionAreaProvider, InactiveAreaProvider { val inactiveSelectionAreaColors: AreaColors } interface InactiveFocusAreaProvider : FocusAreaProvider, InactiveAreaProvider { val inactiveFocusAreaColors: AreaColors }
17
null
8
318
817adc042a029698983c9686d0f1497204bfdf14
1,232
jewel
Apache License 2.0
src/test/kotlin/ui/settings/reducer/ChangeCategoryNameReducerImplTest.kt
gmatyszczak
171,290,380
false
null
package ui.settings.reducer import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyZeroInteractions import kotlinx.coroutines.test.TestCoroutineScope import model.Category import model.CategoryScreenElements import model.ScreenElement import org.junit.Before import org.junit.Test import org.mockito.Mock import ui.settings.SettingsState class ChangeCategoryNameReducerImplTest : BaseReducerTest() { @Mock private lateinit var updateCategoryReducerMock: UpdateCategoryReducer private lateinit var reducer: ChangeCategoryNameReducerImpl @Before fun setup() { reducer = ChangeCategoryNameReducerImpl(state, effectMock, TestCoroutineScope(), updateCategoryReducerMock) } @Test fun `if selected element not null on invoke`() { state.value = SettingsState( categories = listOf( CategoryScreenElements( Category(), listOf(ScreenElement()) ) ), selectedCategoryIndex = 0 ) reducer.invoke("test") verify(updateCategoryReducerMock).invoke(Category(name = "test")) } @Test fun `if selected element null on invoke`() { reducer.invoke("test") verifyZeroInteractions(updateCategoryReducerMock) } }
5
Kotlin
27
130
1fcfbb0bf39d6f1dbe3b69016c39fb3d79214e7e
1,334
screen-generator-plugin
Apache License 2.0
ConverterApp/app/src/main/java/com/example/converter/domain/entities/Coin.kt
fsalom
721,109,040
false
{"Kotlin": 90906}
package com.example.converter.domain.entities import java.io.Serializable data class Coin( val id: String = "", val symbol: String = "", val name: String = "", val priceUsd: Double = 0.0 ): Serializable
0
Kotlin
0
0
7341a535c6348547434b93a17aa35904201bb22f
220
android-compose-clean-architecture
MIT License
PoC/android/app/src/main/java/com/epam/crowdresitance/ui/AdvertiserFragment.kt
epam
255,630,202
false
null
// ========================================================================= // Copyright 2020 EPAM Systems, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ========================================================================= package com.epam.crowdresitance.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Switch import android.widget.TextView import androidx.fragment.app.Fragment import com.epam.crowdresitance.R import com.epam.crowdresitance.bluetooth.BtConfig import com.epam.crowdresitance.service.BtService class AdvertiserFragment : Fragment(), View.OnClickListener { private var switch: Switch? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view: View = inflater.inflate(R.layout.fragment_advertiser, container, false) switch = view.findViewById(R.id.advertise_switch) switch!!.setOnClickListener(this) val myId: TextView = view.findViewById(R.id.myId) myId.text = getString(R.string.my_id, BtConfig.userIdData().toString(Charsets.UTF_8)) return view } override fun onResume() { super.onResume() switch!!.isChecked = BtService.running } override fun onClick(v: View) { val on = (v as Switch).isChecked if (on) { startAdvertising() } else { stopAdvertising() } } private fun startAdvertising() { val context = activity if (context != null) { BtService.startService(context) } } private fun stopAdvertising() { val context = activity context?.stopService(getServiceIntent(context)) switch!!.isChecked = false } companion object { private fun getServiceIntent(c: Context): Intent { return Intent(c, BtService::class.java) } } }
1
Kotlin
2
6
48190bd062cdd7a78883f9ef6b5db70de5de1463
2,575
covid-tracing-bluetooth-poc
Apache License 2.0
remote/src/main/java/com/hu/dgswgr/remote/request/lol/LolCreateRequest.kt
8954sood
664,697,491
false
null
package com.hu.dgswgr.remote.request.lol import com.google.gson.annotations.SerializedName data class LolCreateRequest( @field:SerializedName("name") val name: String )
0
Kotlin
0
0
886aea70ea47b85b747ef6bf829fb1724a4e3388
174
DGSW-GR
MIT License
shared/src/commonMain/kotlin/com/sedsoftware/nxmods/component/modlist/store/ModsListStore.kt
djkovrik
555,405,236
false
null
package com.sedsoftware.nxmods.component.modlist.store import com.arkivanov.mvikotlin.core.store.Store import com.sedsoftware.nxmods.component.modlist.store.ModsListStore.Intent import com.sedsoftware.nxmods.component.modlist.store.ModsListStore.Label import com.sedsoftware.nxmods.component.modlist.store.ModsListStore.State import com.sedsoftware.nxmods.domain.entity.GameInfo import com.sedsoftware.nxmods.domain.entity.ModInfo internal interface ModsListStore : Store<Intent, State, Label> { sealed class Intent { object Refresh : Intent() } data class State( val progress: Boolean = true, val activeGame: GameInfo? = null, val mods: List<ModInfo> = emptyList(), ) sealed class Label { data class ErrorCaught(val throwable: Throwable) : Label() } }
0
Kotlin
0
0
45839defa1eb6d52eec9399a2358c1436ea61947
822
NXMods
MIT License
app/src/main/java/dev/abhaycloud/fdtracker/domain/usecase/GetFixedDepositByIDUseCase.kt
Abhay-cloud
816,359,684
false
{"Kotlin": 164703}
package dev.abhaycloud.fdtracker.domain.usecase import dev.abhaycloud.fdtracker.domain.model.FixedDeposit import dev.abhaycloud.fdtracker.domain.repository.FixedDepositRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetFixedDepositByIDUseCase @Inject constructor(private val repository: FixedDepositRepository) { fun execute(id: Int): Flow<FixedDeposit?> = repository.getFixedDepositById(id) }
2
Kotlin
4
32
a8ab2db4b600c29ecfffe45c263305bf939a5142
431
Fixed-Deposit-Tracker
MIT License
app/src/main/java/com/betulnecanli/purplepage/data/dao/ProjectsDao.kt
betulnecanli
522,035,167
false
{"Kotlin": 62419}
package com.betulnecanli.purplepage.data.dao import androidx.room.* import com.betulnecanli.purplepage.data.model.Projects import kotlinx.coroutines.flow.Flow @Dao interface ProjectsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertProject(p : Projects) @Update suspend fun updateProject(p: Projects) @Delete suspend fun deleteProject(p: Projects) @Query("SELECT * FROM projectTable ORDER BY projectTitle ASC") fun getAllProjects(): Flow<List<Projects>> @Query("SELECT * FROM projectTable WHERE projectTitle LIKE '%'|| :query || '%' ORDER BY projectTitle ASC") fun searchProject(query : String) : Flow<List<Projects>> }
0
Kotlin
0
2
864b6385e6f79bf2f4e793a126d5a0ee3e74ad40
690
PurplePage
Apache License 2.0
app/src/androidTest/java/com/lora/skylink/presentation/PermissionsFragmentEndToEndInstrumentationTest.kt
joshflugel
748,166,569
false
{"Kotlin": 120110}
package com.lora.skylink.presentation import android.content.Intent import android.widget.Switch import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until import com.lora.skylink.R import dagger.hilt.android.testing.HiltAndroidTest import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @HiltAndroidTest class PermissionsFragmentEndToEndInstrumentationTest { @get:Rule var activityRule: ActivityScenarioRule<NavHostActivity> = ActivityScenarioRule(NavHostActivity::class.java) val timeoutMilliseconds = 4000L private fun setSwitchTo(switch: UiObject2, state: Boolean) { val isChecked = switch.isChecked if (isChecked != state) { switch.click() } } private fun navigateToBluetoothSettingsSwitch() { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) device.pressHome() val context = InstrumentationRegistry.getInstrumentation().targetContext val intent = context.packageManager.getLaunchIntentForPackage("com.android.settings") intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) // Clear out any previous instances context.startActivity(intent) device.wait(Until.hasObject(By.pkg("com.android.settings").depth(0)), 5000) val connections = device.wait(Until .findObject(By.text(getLocalizedString(R.string.connections_settings_text))), timeoutMilliseconds) connections?.clickAndWait(Until.newWindow(), timeoutMilliseconds) val bluetoothOption = device.wait(Until .findObject(By.text(getLocalizedString(R.string.bluetooth_settings_text))), timeoutMilliseconds) bluetoothOption?.clickAndWait(Until.newWindow(), timeoutMilliseconds) } private fun setAndroidBluetoothSetting(shouldBeTurnedOn: Boolean): Boolean { var couldSetBluetoothSuccessfully = false navigateToBluetoothSettingsSwitch() val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // Find the Bluetooth switch val bluetoothSwitch = device.wait(Until.findObject(By.clazz(Switch::class.java)), timeoutMilliseconds) setSwitchTo(bluetoothSwitch, shouldBeTurnedOn) if (bluetoothSwitch != null) { couldSetBluetoothSuccessfully = true } return couldSetBluetoothSuccessfully } private fun turnOnAndroidBluetooth(): Boolean { return setAndroidBluetoothSetting(true) } private fun turnOffAndroidBluetooth(): Boolean { return setAndroidBluetoothSetting(false) } private fun getLocalizedString(resId: Int): String { val context = InstrumentationRegistry.getInstrumentation().targetContext return context.getString(resId) } private fun navigateBackToApp(device: UiDevice) { val context = InstrumentationRegistry.getInstrumentation().targetContext val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) // Clear out any previous instances } context.startActivity(intent) device.wait(Until.hasObject(By.pkg(context.packageName).depth(0)), timeoutMilliseconds) } @Test fun testTheScanFragmentIsShownAfterEnablingPermissionsAndBluetooth() { assertTrue("Unable to Turn Off Android Bluetooth Setting", turnOffAndroidBluetooth()) // Navigate back to the App to interact with the system permission dialog val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) navigateBackToApp(device) onView(withId(R.id.btn_grant_permissions)).perform(ViewActions.click()) val allowButton = device.findObject(UiSelector() .textMatches("(?i)${getLocalizedString(R.string.while_using_the_app_button_text)}")) if (allowButton.exists() && allowButton.isEnabled) { allowButton.click() val allowButton2 = device.findObject(UiSelector().textMatches("(?i)${getLocalizedString(R.string.allow_button_text)}")) if (allowButton2.exists() && allowButton2.isEnabled) { allowButton2.click() val enableBluetoothButton = device.findObject(UiSelector() .textMatches("(?i)${getLocalizedString(R.string.allow_button_text)}")) if (enableBluetoothButton.exists() && enableBluetoothButton.isEnabled) { enableBluetoothButton.click() } } } onView(withId(R.id.scan_fragment_rootview)).check(matches(isDisplayed())) } }
0
Kotlin
0
2
7284f6e8f509e7168d8bb799b5762ef9180dffe3
5,317
SkyLink-Android-LoRaWAN
Apache License 2.0
src/commonMain/kotlin/io/smallibs/aktor/ActorContext.kt
Smallibs
159,055,361
false
null
package io.smallibs.aktor interface ActorContext<T> { val self: ActorReference<T> fun root(): ActorReference<*> fun parent(): ActorReference<*>? fun children(): Collection<ActorReference<*>> }
2
Kotlin
1
7
e8276ac9dcc8cf14ef253e7c32a74bf9f7af6a2b
214
aktor
Apache License 2.0
api/src/commonMain/kotlin/krono/serializers/LocalDateIsoSerializer.kt
picortex
544,285,520
false
{"Kotlin": 73072}
package krono.serializers import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import krono.LocalDate @Serializer(forClass = LocalDate::class) object LocalDateIsoSerializer : KSerializer<LocalDate> { override val descriptor = PrimitiveSerialDescriptor( serialName = "krono.LocalDate", kind = PrimitiveKind.STRING ) override fun deserialize(decoder: Decoder): LocalDate = LocalDate(decoder.decodeString()).getOrThrow() override fun serialize(encoder: Encoder, value: LocalDate) = encoder.encodeString(value.toIsoString()) }
0
Kotlin
0
1
8aeadd94e2f510dd4217298abf052646beef5f7c
800
krono
MIT License
app/src/main/java/org/coepi/android/extensions/ListExtensions.kt
Co-Epi
249,138,523
false
null
package org.coepi.android.extensions fun <T> List<T>.add(index: Int, element: T): List<T> = toMutableList().apply { add(index, element) }
14
null
20
32
54cffa441d27d18ba33d7719a34dc9b5c9125262
155
app-android
MIT License
arrow-libs/fx/arrow-benchmarks-fx/arrow-kio-benchmarks/src/main/kotlin/kio/Delay.kt
tiarebalbi
111,073,383
false
null
package arrow.benchmarks.effects.kio import it.msec.kio.UIO import it.msec.kio.effect import it.msec.kio.flatMap import it.msec.kio.runtime.Runtime object Delay { private fun kioDelayLoop(size: Int, i: Int): UIO<Int> = effect { i }.flatMap { j -> if (j > size) effect { j } else kioDelayLoop(size, j + 1) } fun unsafeIODelayLoop(size: Int, i: Int): Int = Runtime.unsafeRunSyncAndGet(kioDelayLoop(size, i)) }
1
null
1
1
12f047b4a7d267e622933bc991f57a05ecf63add
434
kategory
Apache License 2.0
lib/theme/src/main/java/com/dinesh/theme/ToolbarManager.kt
Dinesh2811
745,880,179
false
{"Kotlin": 1200547, "Java": 206284, "JavaScript": 20260}
package com.dinesh.theme import android.util.Log import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.PopupMenu import androidx.annotation.MenuRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.viewbinding.ViewBinding class ToolbarHandler private constructor( private val activity: AppCompatActivity, private val title: String, private val navigationClickListener: (() -> Unit)?, private val optionsMenuResId: Int?, private val onOptionsItemSelected: ((MenuItem) -> Boolean)? ) { private val TAG = "log_" + ToolbarHandler::class.java.name.split(ToolbarHandler::class.java.name.split(".").toTypedArray()[2] + ".").toTypedArray()[1] class Builder(private val activity: AppCompatActivity) { private var title: String = "" private var navigationClickListener: (() -> Unit)? = null private var optionsMenuResId: Int? = null private var onOptionsItemSelected: ((MenuItem) -> Boolean)? = null fun setTitle(title: String): Builder { this.title = title return this } fun setNavigationClickListener(listener: (() -> Unit)?): Builder { this.navigationClickListener = listener return this } fun setOptionsMenu(@MenuRes optionsMenuResId: Int, onOptionsItemSelected: ((MenuItem) -> Boolean)? = null): Builder { this.optionsMenuResId = optionsMenuResId this.onOptionsItemSelected = onOptionsItemSelected return this } fun build(): ToolbarHandler { val toolbarHandler = ToolbarHandler( activity, title, navigationClickListener, optionsMenuResId, onOptionsItemSelected ) toolbarHandler.setupToolbar() return toolbarHandler } } private fun setupToolbar() { val toolbar: Toolbar = activity.findViewById(R.id.toolbar) activity.setSupportActionBar(toolbar) toolbar.title = title toolbar.setNavigationIcon(R.drawable.baseline_arrow_back_24) toolbar.setNavigationOnClickListener { navigationClickListener?.invoke() } optionsMenuResId?.let { toolbar.inflateMenu(it) // val menuInflater = MenuInflater(activity) // menuInflater.inflate(it, toolbar.menu) val selectThemeItem = toolbar.menu.findItem(R.id.action_select_theme) selectThemeItem.isVisible = true toolbar.setOnMenuItemClickListener { menuItem -> // onOptionsItemSelected?.invoke(menuItem) ?: when (menuItem.itemId) { R.id.action_select_theme -> { Log.e(TAG, "Select Theme Clicked") true } R.id.action_kotlin -> { Log.e(TAG, "Kotlin Clicked") true } R.id.action_java -> { Log.e(TAG, "Java Clicked") true } R.id.action_testing -> { Log.e(TAG, "Testing Clicked") true } else -> false } } } } }
0
Kotlin
0
1
d5b4b55728848196c71c351c186df7e57ad4e8c2
3,482
Android101
Apache License 2.0
SimpleLogin/app/src/main/java/io/simplelogin/android/utils/extension/View.kt
simple-login
244,631,377
false
{"Kotlin": 341987}
package io.simplelogin.android.utils.extension import android.animation.ValueAnimator import android.view.View import android.view.ViewOutlineProvider import android.view.animation.AnimationUtils import android.view.animation.LinearInterpolator import io.simplelogin.android.R @Suppress("MagicNumber") fun View.customSetEnabled(enabled: Boolean) { isEnabled = enabled alpha = if (enabled) 1.0f else 0.5f } fun View.makeSubviewsClippedToBound() { outlineProvider = ViewOutlineProvider.BACKGROUND clipToOutline = true } fun View.shake() = startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake)) @Suppress("MagicNumber") fun View.fadeOut() { val valueAnimator = ValueAnimator.ofFloat(1f, 0f) valueAnimator.addUpdateListener { alpha = it.animatedValue as Float } valueAnimator.duration = 200 valueAnimator.interpolator = LinearInterpolator() valueAnimator.start() }
23
Kotlin
39
312
46a0b7a7d9c560d7f230b11788d9c52ab74d50d5
915
Simple-Login-Android
Apache License 2.0
sample-app/src/main/java/dev/arunkumar/android/home/HomeActivity.kt
aleonq
397,084,334
true
{"Kotlin": 148553, "Dockerfile": 1501}
/* * Copyright 2021 Arunkumar * * 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 dev.arunkumar.android.home import android.app.Activity import android.os.Bundle import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import com.uber.autodispose.android.lifecycle.autoDispose import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.android.support.DaggerAppCompatActivity import dagger.multibindings.IntoMap import dev.arunkumar.android.R import dev.arunkumar.android.dagger.activity.PerActivity import dev.arunkumar.android.dagger.viewmodel.UsesViewModel import dev.arunkumar.android.dagger.viewmodel.ViewModelKey import dev.arunkumar.android.dagger.viewmodel.viewModel import dev.arunkumar.android.home.items.ItemsPagingController import dev.arunkumar.android.item.DeleteItemWorker import dev.arunkumar.android.itemanimator.SpringSlideInItemAnimator import dev.arunkumar.common.result.success import kotlinx.android.synthetic.main.activity_main.* import javax.inject.Inject class HomeActivity : DaggerAppCompatActivity(), UsesViewModel { @Inject lateinit var testActivityScope: DummyActivityScopeDep @Inject override lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var itemsController: ItemsPagingController @Inject lateinit var workManager: WorkManager private val homeViewModel by viewModel<HomeViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupItems() homeViewModel.connect( this, stateConsumer, sideEffectConsumer ) } private fun setupItems() { itemsRv.setController(itemsController) itemsRv.run { setController(itemsController) itemAnimator = SpringSlideInItemAnimator() } itemsController.itemClicks .map { HomeAction.DeleteItem(it) } .autoDispose(this) .subscribe(homeViewModel::sendAction) itemsController.resetDbs .autoDispose(this) .subscribe(homeViewModel::sendAction) } private val stateConsumer: (HomeState) -> Unit = { homeState -> homeState.items.success { itemsController.submitList(data) } itemsController.headers = homeState.headers } private val sideEffectConsumer: (HomeSideEffect) -> Unit = { homeSideEffect -> when (homeSideEffect) { is HomeSideEffect.PerformDelete -> deleteItem(homeSideEffect) } } private fun deleteItem(homeSideEffect: HomeSideEffect.PerformDelete) { val workRequest = OneTimeWorkRequestBuilder<DeleteItemWorker>().run { setInputData(workDataOf("id" to homeSideEffect.item.id)) build() } workManager.enqueue(workRequest) } @Module interface HomeModule { @PerActivity @Binds fun HomeActivity.bindActivity(): Activity } @Module interface Builder { @PerActivity @ContributesAndroidInjector(modules = [HomeModule::class]) fun homeActivity(): HomeActivity @Binds @IntoMap @ViewModelKey(HomeViewModel::class) fun HomeViewModel.homeViewModel(): ViewModel } @PerActivity class DummyActivityScopeDep @Inject constructor() }
0
null
0
0
0a3f69860737517cf216a3dc569f786aa09464dd
3,850
base-android
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/events/OffenderEventEntity.kt
ministryofjustice
665,659,688
false
{"Kotlin": 1538950, "Dockerfile": 1997}
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.events import jakarta.persistence.Entity import jakarta.persistence.EntityListeners import jakarta.persistence.EnumType import jakarta.persistence.Enumerated import jakarta.persistence.Id import jakarta.persistence.Table import org.springframework.data.annotation.CreatedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.time.LocalDateTime import java.time.ZonedDateTime import java.util.UUID @Entity @Table(name = "offender_event") @EntityListeners(AuditingEntityListener::class) data class OffenderEventEntity( @Id val id: UUID = UUID.randomUUID(), val prisonerId: Long, val nomsId: String, @Enumerated(EnumType.STRING) val type: OffenderEventType, val occurredAt: ZonedDateTime, @Enumerated(EnumType.STRING) val reason: MovementReasonType? = null, val reasonCode: String? = null, @CreatedDate var creationDate: LocalDateTime? = null, ) enum class OffenderEventType { PRISON_ADMISSION, } enum class MovementReasonType { RECALL, }
0
Kotlin
2
1
a7251ff491a6fc063e49389c00a9feac76bbf1d1
1,072
hmpps-resettlement-passport-api
MIT License
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/event/TimelineItemPollView.kt
vector-im
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.messages.impl.timeline.components.event import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.PreviewParameter import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContent import io.element.android.features.messages.impl.timeline.model.event.TimelineItemPollContentProvider import io.element.android.features.poll.api.ActivePollContentView import io.element.android.libraries.designsystem.preview.DayNightPreviews import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.matrix.api.poll.PollAnswer import kotlinx.collections.immutable.toImmutableList @Composable fun TimelineItemPollView( content: TimelineItemPollContent, onAnswerSelected: (PollAnswer) -> Unit, modifier: Modifier = Modifier, ) { ActivePollContentView( question = content.question, answerItems = content.answerItems.toImmutableList(), pollKind = content.pollKind, onAnswerSelected = onAnswerSelected, modifier = modifier, ) } @DayNightPreviews @Composable internal fun TimelineItemPollViewPreview(@PreviewParameter(TimelineItemPollContentProvider::class) content: TimelineItemPollContent) = ElementPreview { TimelineItemPollView( content = content, onAnswerSelected = {}, ) }
105
Kotlin
32
287
4587b51bd33e8b5a2e2c81c79f3aa70a3ac52923
2,046
element-x-android
Apache License 2.0
core/src/main/kotlin/io/toolisticon/testing/jgiven/format/VarargsFormatter.kt
toolisticon
333,476,571
false
{"Kotlin": 7119}
package io.toolisticon.testing.jgiven.format import com.tngtech.jgiven.annotation.Format import com.tngtech.jgiven.format.ArgumentFormatter import com.tngtech.jgiven.format.PrintfFormatter import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.* /** * Varargs step parameters annotated with this annotation will be put into quotes (" ") in reports. */ @MustBeDocumented @Format(value = VarargsFormatter::class, args = ["\"%s\""]) @Target(FIELD, VALUE_PARAMETER, ANNOTATION_CLASS) @Retention(RUNTIME) annotation class VarargsQuoted /** * Argument formatter for varargs delegating to [PrintfFormatter] */ class VarargsFormatter @JvmOverloads constructor(private val delimiter: String = ", ") : ArgumentFormatter<Any?> { companion object { fun anyToList(instance: Any?): List<Any?>? { if (instance == null || !instance::class.java.isArray) { return null } // deal with the various primitive array (int[],...) wrappers in kotlin. return when (instance) { is IntArray -> instance.toList() is ByteArray -> instance.toList() is CharArray -> instance.toList() is ShortArray -> instance.toList() is LongArray -> instance.toList() is DoubleArray -> instance.toList() is FloatArray -> instance.toList() is BooleanArray -> instance.toList() else -> (instance as Array<*>).toList() } } } private val formatter = PrintfFormatter() override fun format(argumentToFormat: Any?, vararg formatterArguments: String): String { val argumentList = anyToList(argumentToFormat) return argumentList ?.joinToString(separator = delimiter) { formatter.format(it, *formatterArguments) } ?: formatter.format(argumentToFormat, *formatterArguments) } }
2
Kotlin
2
5
9e6d6d9f0520d661f855cd53e772237765fee97f
1,820
jgiven-kotlin
Apache License 2.0
projects/Kotlin/src/com/chronoxor/proto/fbe/FinalClient.kt
jiangnengbin
192,683,164
true
{"C++": 3655487, "Yacc": 16374, "Lex": 12641, "CMake": 8673, "C": 80}
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: proto.fbe // Version: 1.3.0.0 @file:Suppress("UnusedImport", "unused") package com.chronoxor.proto.fbe // Fast Binary Encoding com.chronoxor.proto final client @Suppress("MemberVisibilityCanBePrivate", "PropertyName") open class FinalClient : com.chronoxor.fbe.Client, FinalReceiverListener { // Client sender models accessors val OrderSenderModel: OrderFinalModel val BalanceSenderModel: BalanceFinalModel val AccountSenderModel: AccountFinalModel // Client receiver values accessors private val OrderReceiverValue: com.chronoxor.proto.Order private val BalanceReceiverValue: com.chronoxor.proto.Balance private val AccountReceiverValue: com.chronoxor.proto.Account // Client receiver models accessors private val OrderReceiverModel: OrderFinalModel private val BalanceReceiverModel: BalanceFinalModel private val AccountReceiverModel: AccountFinalModel constructor() : super(true) { OrderSenderModel = OrderFinalModel(sendBuffer) OrderReceiverValue = com.chronoxor.proto.Order() OrderReceiverModel = OrderFinalModel() BalanceSenderModel = BalanceFinalModel(sendBuffer) BalanceReceiverValue = com.chronoxor.proto.Balance() BalanceReceiverModel = BalanceFinalModel() AccountSenderModel = AccountFinalModel(sendBuffer) AccountReceiverValue = com.chronoxor.proto.Account() AccountReceiverModel = AccountFinalModel() } constructor(sendBuffer: com.chronoxor.fbe.Buffer, receiveBuffer: com.chronoxor.fbe.Buffer) : super(sendBuffer, receiveBuffer, true) { OrderSenderModel = OrderFinalModel(sendBuffer) OrderReceiverValue = com.chronoxor.proto.Order() OrderReceiverModel = OrderFinalModel() BalanceSenderModel = BalanceFinalModel(sendBuffer) BalanceReceiverValue = com.chronoxor.proto.Balance() BalanceReceiverModel = BalanceFinalModel() AccountSenderModel = AccountFinalModel(sendBuffer) AccountReceiverValue = com.chronoxor.proto.Account() AccountReceiverModel = AccountFinalModel() } @Suppress("JoinDeclarationAndAssignment") fun send(obj: Any): Long { when (obj) { is com.chronoxor.proto.Order -> return send(obj) is com.chronoxor.proto.Balance -> return send(obj) is com.chronoxor.proto.Account -> return send(obj) } return 0 } fun send(value: com.chronoxor.proto.Order): Long { // Serialize the value into the FBE stream val serialized = OrderSenderModel.serialize(value) assert(serialized > 0) { "com.chronoxor.proto.Order serialization failed!" } assert(OrderSenderModel.verify()) { "com.chronoxor.proto.Order validation failed!" } // Log the value if (logging) { val message = value.toString() onSendLog(message) } // Send the serialized value return sendSerialized(serialized) } fun send(value: com.chronoxor.proto.Balance): Long { // Serialize the value into the FBE stream val serialized = BalanceSenderModel.serialize(value) assert(serialized > 0) { "com.chronoxor.proto.Balance serialization failed!" } assert(BalanceSenderModel.verify()) { "com.chronoxor.proto.Balance validation failed!" } // Log the value if (logging) { val message = value.toString() onSendLog(message) } // Send the serialized value return sendSerialized(serialized) } fun send(value: com.chronoxor.proto.Account): Long { // Serialize the value into the FBE stream val serialized = AccountSenderModel.serialize(value) assert(serialized > 0) { "com.chronoxor.proto.Account serialization failed!" } assert(AccountSenderModel.verify()) { "com.chronoxor.proto.Account validation failed!" } // Log the value if (logging) { val message = value.toString() onSendLog(message) } // Send the serialized value return sendSerialized(serialized) } // Send message handler override fun onSend(buffer: ByteArray, offset: Long, size: Long): Long { throw UnsupportedOperationException("com.chronoxor.proto.fbe.Client.onSend() not implemented!") } override fun onReceive(type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean { return onReceiveListener(this, type, buffer, offset, size) } open fun onReceiveListener(listener: FinalReceiverListener, type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean { when (type) { com.chronoxor.proto.fbe.OrderFinalModel.fbeTypeConst -> { // Deserialize the value from the FBE stream OrderReceiverModel.attach(buffer, offset) assert(OrderReceiverModel.verify()) { "com.chronoxor.proto.Order validation failed!" } val deserialized = OrderReceiverModel.deserialize(OrderReceiverValue) assert(deserialized > 0) { "com.chronoxor.proto.Order deserialization failed!" } // Log the value if (logging) { val message = OrderReceiverValue.toString() onReceiveLog(message) } // Call receive handler with deserialized value listener.onReceive(OrderReceiverValue) return true } com.chronoxor.proto.fbe.BalanceFinalModel.fbeTypeConst -> { // Deserialize the value from the FBE stream BalanceReceiverModel.attach(buffer, offset) assert(BalanceReceiverModel.verify()) { "com.chronoxor.proto.Balance validation failed!" } val deserialized = BalanceReceiverModel.deserialize(BalanceReceiverValue) assert(deserialized > 0) { "com.chronoxor.proto.Balance deserialization failed!" } // Log the value if (logging) { val message = BalanceReceiverValue.toString() onReceiveLog(message) } // Call receive handler with deserialized value listener.onReceive(BalanceReceiverValue) return true } com.chronoxor.proto.fbe.AccountFinalModel.fbeTypeConst -> { // Deserialize the value from the FBE stream AccountReceiverModel.attach(buffer, offset) assert(AccountReceiverModel.verify()) { "com.chronoxor.proto.Account validation failed!" } val deserialized = AccountReceiverModel.deserialize(AccountReceiverValue) assert(deserialized > 0) { "com.chronoxor.proto.Account deserialization failed!" } // Log the value if (logging) { val message = AccountReceiverValue.toString() onReceiveLog(message) } // Call receive handler with deserialized value listener.onReceive(AccountReceiverValue) return true } } return false } }
0
C++
0
0
5e3e0e96e39a753cd0934a62781e8a5ecd1d7271
7,502
FastBinaryEncoding
MIT License
web/src/main/java/com/codeabovelab/tpc/web/ui/UiDocProcessController.kt
codeabovelab
159,236,130
false
null
package com.codeabovelab.tpc.web.ui import com.codeabovelab.tpc.core.processor.Label import com.codeabovelab.tpc.core.processor.ProcessorReport import com.codeabovelab.tpc.web.docproc.DocProcessor import com.codeabovelab.tpc.web.docproc.ProcessorReportsStorage import com.codeabovelab.tpc.web.jpa.ProcessorReportEntity import com.codeabovelab.tpc.web.jpa.ProcessorReportsRepository import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.MimeTypeUtils import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.time.LocalDateTime /** */ @RequestMapping( path = arrayOf("/docproc"), produces = arrayOf(MimeTypeUtils.APPLICATION_JSON_VALUE)) @Transactional(propagation = Propagation.REQUIRED) @RestController class UiDocProcessController( private var reportsRepo: ProcessorReportsRepository, private var processorReportsStorage: ProcessorReportsStorage, private var processor: DocProcessor ) { @RequestMapping("/analyze", method = arrayOf(RequestMethod.POST)) fun analyze( documentId: String, @RequestParam(required = false) renew: Boolean ): UiProcessorReport? { return processor.process(documentId, renew).toUi() } @RequestMapping("/get", method = arrayOf(RequestMethod.GET)) fun get(documentId: String): UiProcessorReport? { return processorReportsStorage.getLastReportEntity(documentId).toUi() } @RequestMapping("/getAll", method = arrayOf(RequestMethod.GET)) fun getAll(documentId: String): List<UiProcessorReport> { return reportsRepo.getReportsByDocument(documentId).map { it.toUi()!! } } @RequestMapping("/delete", method = arrayOf(RequestMethod.POST)) fun delete(id: Long) { return reportsRepo.deleteById(id) } fun ProcessorReportEntity?.toUi() : UiProcessorReport? { if(this == null) { return null } val report = processorReportsStorage.reportFromString(data) return UiProcessorReport( id = id, date = date, report = report ) } } data class UiProcessorReport( val id: Long, val date: LocalDateTime, val report: ProcessorReport? ) { val labels: Collection<Label> get() = report?.labels ?: listOf() }
0
Kotlin
0
0
ee62aeecc62baefabd6085ad659e6cf5a1b237ff
2,591
text-compliance
Apache License 2.0
core/src/main/kotlin/com/github/andrewoma/kwery/core/Row.kt
tbml
33,686,630
true
{"Kotlin": 333272, "Java": 31398, "HTML": 7111, "Scala": 2252, "Shell": 116}
/* * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kwery.core import java.io.InputStream import java.io.Reader import java.math.BigDecimal import java.sql.* public class Row(val resultSet: ResultSet) { public fun obj(name: String): Any = requireNotNull(resultSet.getObject(name), name) public fun objectOrNull(name: String): Any? = resultSet.getObject(name) public fun boolean(name: String): Boolean = requireNotNull(resultSet.getBoolean(name), name) public fun booleanOrNull(name: String): Boolean? = valueOrNull(resultSet.getBoolean(name)) public fun byte(name: String): Byte = requireNotNull(resultSet.getByte(name), name) public fun byteOrNull(name: String): Byte? = valueOrNull(resultSet.getByte(name)) public fun short(name: String): Short = requireNotNull(resultSet.getShort(name), name) public fun shortOrNull(name: String): Short? = valueOrNull(resultSet.getShort(name)) public fun int(name: String): Int = requireNotNull(resultSet.getInt(name), name) public fun intOrNull(name: String): Int? = valueOrNull(resultSet.getInt(name)) public fun long(name: String): Long = requireNotNull(resultSet.getLong(name), name) public fun longOrNull(name: String): Long? = valueOrNull(resultSet.getLong(name)) public fun float(name: String): Float = requireNotNull(resultSet.getFloat(name), name) public fun floatOrNull(name: String): Float? = valueOrNull(resultSet.getFloat(name)) public fun double(name: String): Double = requireNotNull(resultSet.getDouble(name), name) public fun doubleOrNull(name: String): Double? = valueOrNull(resultSet.getDouble(name)) public fun bigDecimal(name: String): BigDecimal = resultSet.getBigDecimal(name) public fun bigDecimalOrNull(name: String): BigDecimal? = resultSet.getBigDecimal(name) public fun string(name: String): String = resultSet.getString(name) public fun stringOrNull(name: String): String? = resultSet.getString(name) public fun bytes(name: String): ByteArray = resultSet.getBytes(name) public fun bytesOrNull(name: String): ByteArray? = resultSet.getBytes(name) public fun timestamp(name: String): Timestamp = resultSet.getTimestamp(name) public fun timestampOrNull(name: String): Timestamp? = resultSet.getTimestamp(name) public fun time(name: String): Time = resultSet.getTime(name) public fun timeOrNull(name: String): Time? = resultSet.getTime(name) public fun date(name: String): Date = resultSet.getDate(name) public fun dateOrNull(name: String): Date? = resultSet.getDate(name) public fun clob(name: String): Clob = resultSet.getClob(name) public fun clobOrNull(name: String): Clob? = resultSet.getClob(name) public fun blob(name: String): Blob = resultSet.getBlob(name) public fun blobOrNull(name: String): Blob? = resultSet.getBlob(name) public fun characterStream(name: String): Reader = resultSet.getCharacterStream(name) public fun characterStreamOrNull(name: String): Reader? = resultSet.getCharacterStream(name) public fun binaryStream(name: String): InputStream = resultSet.getBinaryStream(name) public fun binaryStreamOrNull(name: String): InputStream? = resultSet.getBinaryStream(name) suppress("UNCHECKED_CAST") public fun <T> array(name: String): List<T> { val value = resultSet.getArray(name) return if (resultSet.wasNull()) listOf() else (value.getArray() as Array<Any>).toList() as List<T> } fun <T : Any> valueOrNull(value: T): T? = if (resultSet.wasNull()) null else value fun <T : Any> requireNotNull(value: T?, name: String): T { require(!resultSet.wasNull(), "Unexpected null for column '$name'") return value!! } }
0
Kotlin
0
0
15c5cab3e1452d24133ad3bf12ca98bb8dbd3239
4,804
kwery
MIT License
src/main/kotlin/dev/galiev/sc/items/custom/WaterCan.kt
GalievDev
628,931,160
false
{"Kotlin": 88302, "Java": 6133}
package dev.galiev.sc.items.custom import dev.galiev.sc.SummerCottage import dev.galiev.sc.SummerCottage.RANDOM import dev.galiev.sc.helper.NbtHelper import net.fabricmc.fabric.api.item.v1.FabricItemSettings import net.minecraft.block.CropBlock import net.minecraft.block.Material import net.minecraft.client.item.TooltipContext import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.item.ItemUsageContext import net.minecraft.particle.ParticleTypes import net.minecraft.server.world.ServerWorld import net.minecraft.sound.SoundEvents import net.minecraft.text.Text import net.minecraft.util.ActionResult import net.minecraft.util.Formatting import net.minecraft.util.Hand import net.minecraft.util.TypedActionResult import net.minecraft.util.hit.BlockHitResult import net.minecraft.util.hit.HitResult import net.minecraft.util.math.BlockPos import net.minecraft.world.RaycastContext import net.minecraft.world.World import net.minecraft.world.WorldEvents class WaterCan : Item(FabricItemSettings().maxCount(1)) { override fun use(world: World?, user: PlayerEntity?, hand: Hand?): TypedActionResult<ItemStack> { val stack = user?.getStackInHand(hand) NbtHelper.setBoolean(stack, "Water", false) val trace: BlockHitResult = raycast(world, user, RaycastContext.FluidHandling.SOURCE_ONLY) if (trace.type != HitResult.Type.BLOCK){ return TypedActionResult.pass(stack) } val pos = trace.blockPos val state = world?.getBlockState(pos) if (!NbtHelper.getBoolean(stack, "Water")) { if (state?.material == Material.WATER) { NbtHelper.setInt(stack, "Liters", 1000) NbtHelper.setBoolean(stack, "Water", true) user?.playSound(SoundEvents.ITEM_BUCKET_FILL, 1.0F, 1.0F) SummerCottage.logger.info("Water: ${NbtHelper.getInt(stack, "Liters")}") return TypedActionResult.success(stack) } } return TypedActionResult.pass(stack) } override fun useOnBlock(context: ItemUsageContext?): ActionResult { val world = context?.world val item = context?.stack val blockPos = context?.blockPos if (NbtHelper.getBoolean(item, "Liters") && blockPos != null) { for (targetPos in BlockPos.iterate(blockPos.add(-1, 0, -1), blockPos.add(1, 0, 1))) { useOnFertilizable(targetPos, world!!, item!!) } if (!world?.isClient!!) { world.syncWorldEvent(WorldEvents.POINTED_DRIPSTONE_DRIPS_WATER_INTO_CAULDRON, blockPos, 0) } return ActionResult.success(world.isClient) } return ActionResult.PASS } private fun useOnFertilizable(pos: BlockPos, world: World, stack: ItemStack): Boolean { val blockState = world.getBlockState(pos) if (blockState.block is CropBlock && (blockState.block as CropBlock).isFertilizable(world, pos, blockState, world.isClient)) { if (world is ServerWorld){ if ((blockState.block as CropBlock).canGrow(world, world.random, pos, blockState) && NbtHelper.getInt(stack, "Liters") >= 30) { (blockState.block as CropBlock).grow(world, world.random, pos, blockState) NbtHelper.setInt(stack, "Liters", NbtHelper.getInt(stack, "Liters") - RANDOM.nextInt(10, 30)) } } else if (world.isClient) { world.addParticle(ParticleTypes.RAIN, pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, 0.2, 0.1, 0.3) } return true } return false } override fun appendTooltip(stack: ItemStack?, world: World?, tooltip: MutableList<Text>?, context: TooltipContext?) { val waterCount = NbtHelper.getInt(stack, "Liters") tooltip?.add(Text.literal("$waterCount/1000 Milliliters").formatted(Formatting.AQUA)) super.appendTooltip(stack, world, tooltip, context) } }
0
Kotlin
0
0
2c5fd9aaea3001af6e88433c5d9685145552e019
4,059
summer-cottage
MIT License
src/main/kotlin/ch/unil/pafanalysis/analysis/steps/group_filter/GroupFilterRunner.kt
UNIL-PAF
419,229,519
false
null
package ch.unil.pafanalysis.analysis.steps.group_filter import ch.unil.pafanalysis.analysis.model.AnalysisStep import ch.unil.pafanalysis.analysis.model.AnalysisStepType import ch.unil.pafanalysis.analysis.steps.CommonRunner import ch.unil.pafanalysis.analysis.steps.CommonStep import com.itextpdf.kernel.pdf.PdfDocument import com.itextpdf.layout.Document import com.itextpdf.layout.element.Paragraph import com.itextpdf.layout.element.Text import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class GroupFilterRunner() : CommonStep(), CommonRunner { @Autowired var asyncGroupFilterRunner: AsyncGroupFilterRunner? = null override var type: AnalysisStepType? = AnalysisStepType.GROUP_FILTER fun getParameters(step: AnalysisStep?): GroupFilterParams { return if(step?.parameters != null) gson.fromJson(step?.parameters, GroupFilterParams().javaClass) else GroupFilterParams() } override fun createPdf(step: AnalysisStep, document: Document?, pdf: PdfDocument): Document? { val title = Paragraph().add(Text(step.type).setBold()) //val params = gson.fromJson(step.parameters, FilterParams::class.java) document?.add(title) if (step.comments !== null) document?.add(Paragraph().add(Text(step.comments))) return document } override fun run(oldStepId: Int, step: AnalysisStep?, params: String?): AnalysisStep { val newStep = runCommonStep(type!!, oldStepId, true, step, params) asyncGroupFilterRunner?.runAsync(oldStepId, newStep) return newStep!! } override fun getCopyDifference(step: AnalysisStep, origStep: AnalysisStep?): String? { val params = gson.fromJson(step.parameters, GroupFilterParams::class.java) val origParams = if (origStep?.parameters != null) gson.fromJson( origStep.parameters, GroupFilterParams::class.java ) else null val filterInGroupText = when(params.filterInGroup ) { FilterInGroup.ONE_GROUP.value -> FilterInGroup.ONE_GROUP.text FilterInGroup.ALL_GROUPS.value -> FilterInGroup.ALL_GROUPS.text else -> "NONE" } return "Parameter(s) changed:" .plus(if (params.minNrValid != origParams?.minNrValid) " [Minimal number of valid: ${params.minNrValid}]" else "") .plus(if (params.filterInGroup != origParams?.filterInGroup) " [Number of valid entries required in: ${filterInGroupText}]" else "") } }
0
Kotlin
0
0
f91130040eb640029a94d486fd77a6c311f9476e
2,541
paf-analysis-backend
MIT License
app/src/main/java/com/zhangke/notionlight/setting/SettingActivity.kt
0xZhangKe
468,651,930
false
{"Kotlin": 207160, "HTML": 1745}
package com.zhangke.notionlight.setting import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.PowerSettingsNew import androidx.compose.material.icons.outlined.Feedback import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.constraintlayout.compose.ConstraintLayout import coil.compose.AsyncImage import coil.request.ImageRequest import coil.transform.CircleCropTransformation import com.zhangke.architect.activity.BaseActivity import com.zhangke.architect.theme.* import com.zhangke.notionlight.R import com.zhangke.notionlight.code.OpenSourceActivity import com.zhangke.notionlight.draft.DraftBoxActivity import com.zhangke.notionlight.draft.DraftBoxManager import com.zhangke.notionlight.pagemanager.PageManagerActivity import kotlinx.coroutines.delay import kotlinx.coroutines.launch class SettingActivity : BaseActivity() { companion object { fun open(activity: Activity) { Intent(activity, SettingActivity::class.java).let { activity.startActivity(it) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val vm: SettingViewModel by viewModels() setContent { AppMaterialTheme { Page(vm) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun Page(vm: SettingViewModel) { val coroutineScope = rememberCoroutineScope() Scaffold { Column( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxWidth() .padding(top = 100.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { val userInfo = vm.userInfo.observeAsState().value Surface( shadowElevation = 10.dp, shape = CircleShape ) { if (userInfo == null) { Image( modifier = Modifier .size(90.dp), alpha = 0.5F, painter = painterResource(R.drawable.ic_baseline_account_circle_24), contentDescription = "workspace icon" ) } else { AsyncImage( model = ImageRequest.Builder(this@SettingActivity) .data(userInfo.workspaceIcon) .transformations(CircleCropTransformation()) .placeholder(R.drawable.ic_baseline_account_circle_24) .error(R.drawable.ic_baseline_account_circle_24) .build(), contentDescription = "workspace icon", modifier = Modifier .size(90.dp) ) } } if (userInfo != null) { val ownerName = userInfo.owner.user.name PrimaryText( text = userInfo.workspaceName ?: "$ownerName's WorkSpace", fontWeight = FontWeight.Bold, fontSize = 22.sp, modifier = Modifier.padding(top = 10.dp) ) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 5.dp) ) { SecondaryText( text = "created by $ownerName", color = Color.Gray, fontSize = 18.sp ) AsyncImage( model = ImageRequest.Builder(this@SettingActivity) .data(userInfo.workspaceIcon) .transformations(CircleCropTransformation()) .build(), contentDescription = "workspace icon", modifier = Modifier .padding(start = 5.dp) .size(20.dp) ) } } else { PrimaryText( text = getString(R.string.setting_not_login), fontWeight = FontWeight.Medium, fontSize = 20.sp, modifier = Modifier.padding(top = 10.dp) ) } Divider( modifier = Modifier .fillMaxWidth() .padding(top = 20.dp) ) CreateSettingLine( modifier = Modifier.clickable { PageManagerActivity.open(this@SettingActivity) }, iconResId = R.drawable.ic_page_manager, iconPadding = 3.dp, title = getString(R.string.setting_page_manager), subtitle = getString(R.string.setting_page_manager_subtitle), ) CreateSettingLine( modifier = Modifier.clickable { DraftBoxActivity.open(this@SettingActivity) }, iconResId = R.drawable.ic_baseline_drafts_24, iconPadding = 3.dp, title = getString(R.string.setting_draft_box), subtitle = getString(R.string.setting_draft_box_subtitle), ) var dayNightModeMenuExpanded by remember { mutableStateOf(false) } val currentDayNightMode = vm.currentDayNightMode.observeAsState().value val currentDayNightModeName = if (currentDayNightMode != null) { vm.getDayNightVm(currentDayNightMode).name } else { "" } CreateSettingLine( modifier = Modifier.clickable { dayNightModeMenuExpanded = true }, iconResId = R.drawable.ic_night_mode, title = getString(R.string.setting_page_day_night), subtitle = currentDayNightModeName, onDismissRequest = { dayNightModeMenuExpanded = false }, menuExpanded = dayNightModeMenuExpanded ) { vm.getDayNightModeList().forEach { DropdownMenuItem( text = { Text(text = it.name) }, onClick = { dayNightModeMenuExpanded = false coroutineScope.launch { delay(200) vm.updateDayNight(it) } } ) } } var languageMenuExpanded by remember { mutableStateOf(false) } val currentLanguage = vm.getCurrentLanguage() CreateSettingLine( modifier = Modifier.clickable { languageMenuExpanded = true }, iconResId = R.drawable.ic_language, iconPadding = 4.dp, title = getString(R.string.setting_language), subtitle = currentLanguage.name, onDismissRequest = { languageMenuExpanded = false }, menuExpanded = languageMenuExpanded ) { vm.getSupportedLanguage().forEach { DropdownMenuItem( text = { Text(text = it.name) }, onClick = { languageMenuExpanded = false vm.setLanguage(this@SettingActivity, it) } ) } } CreateSettingLine( modifier = Modifier.clickable { HelpActivity.open(this@SettingActivity) }, iconResId = R.drawable.ic_help, iconPadding = 4.dp, title = getString(R.string.setting_page_help), subtitle = getString(R.string.setting_page_help_desc) ) CreateSettingLine( modifier = Modifier.clickable { OpenSourceActivity.open(this@SettingActivity) }, icon = Icons.Filled.Code, title = getString(R.string.setting_page_open_source), subtitle = getString(R.string.setting_page_open_source_desc) ) val showFeedbackDialog = remember { mutableStateOf(false) } if (showFeedbackDialog.value) { FeedbackDialog(vm) { showFeedbackDialog.value = false } } CreateSettingLine( modifier = Modifier.clickable { showFeedbackDialog.value = true }, icon = Icons.Outlined.Feedback, iconPadding = 3.dp, title = getString(R.string.setting_feedback), subtitle = getString(R.string.setting_feedback_desc) ) CreateSettingLine( modifier = Modifier.clickable { vm.openAppMarket(this@SettingActivity) }, iconResId = R.drawable.ic_ratting, iconPadding = 5.dp, title = getString(R.string.setting_page_appraise), subtitle = getString(R.string.setting_page_appraise_desc) ) CreateSettingLine( modifier = Modifier.clickable { }, iconResId = R.mipmap.logo, title = getString(R.string.setting_page_about_title), tintColor = null, subtitle = vm.getAppVersionDesc() ) } Row( modifier = Modifier .fillMaxWidth() .padding(start = 15.dp, top = 15.dp, end = 15.dp) ) { IconButton( onClick = { finish() } ) { Icon( painter = rememberVectorPainter(image = Icons.Filled.ArrowBack), "back" ) } Spacer(modifier = Modifier.weight(1F)) var showLogoutDialog by remember { mutableStateOf(false) } if (showLogoutDialog) { AlertDialog( onDismissRequest = { showLogoutDialog = false }, title = { PrimaryText( text = getString(R.string.setting_logout_dialog_title), fontSize = 16.sp, fontWeight = FontWeight.Medium, ) }, dismissButton = { Button(onClick = { showLogoutDialog = false }) { PrimaryText( text = getString(R.string.cancel), color = Color.White ) } }, confirmButton = { Button(onClick = { showLogoutDialog = false vm.logout() }) { PrimaryText( text = getString(R.string.ok), color = Color.White ) } } ) } IconButton( onClick = { showLogoutDialog = true } ) { Icon( painter = rememberVectorPainter(image = Icons.Filled.PowerSettingsNew), "login out", ) } } } } @Composable fun CreateSettingLine( modifier: Modifier, icon: ImageVector? = null, iconResId: Int? = null, iconPadding: Dp = 0.dp, tintColor: Color? = androidx.compose.material.MaterialTheme.colors.textPrimaryColor, title: String, subtitle: String, menuExpanded: Boolean = false, onDismissRequest: (() -> Unit)? = null, dropDownItems: (@Composable () -> Unit)? = null ) { ConstraintLayout( modifier = modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp, top = 20.dp, bottom = 20.dp) ) { val (iconId, titleId, subtitleId, dropDownMenu) = createRefs() if (icon != null) { Icon( modifier = Modifier .size(30.dp, 30.dp) .padding(iconPadding) .constrainAs(iconId) { top.linkTo(titleId.top) bottom.linkTo(subtitleId.bottom) start.linkTo(parent.start) }, tint = tintColor ?: LocalContentColor.current, painter = rememberVectorPainter(image = icon), contentDescription = null ) } else { Image( modifier = Modifier .size(30.dp, 30.dp) .padding(iconPadding) .constrainAs(iconId) { top.linkTo(titleId.top) bottom.linkTo(subtitleId.bottom) start.linkTo(parent.start) }, colorFilter = if (tintColor == null) null else ColorFilter.tint(tintColor), painter = painterResource(id = iconResId!!), contentDescription = null ) } PrimaryText( fontSize = 16.sp, fontWeight = FontWeight.Medium, modifier = Modifier.constrainAs(titleId) { top.linkTo(parent.top) start.linkTo(iconId.end, margin = 20.dp) }, text = title, ) SecondaryText( fontSize = 14.sp, modifier = Modifier.constrainAs(subtitleId) { top.linkTo(titleId.bottom, margin = 3.dp) start.linkTo(titleId.start) }, text = subtitle, color = Color.Gray, ) if (dropDownItems != null) { DropdownMenu( modifier = Modifier.constrainAs(dropDownMenu) { top.linkTo(subtitleId.bottom) start.linkTo(subtitleId.start) }, expanded = menuExpanded, onDismissRequest = onDismissRequest!! ) { dropDownItems() } } } } @Composable fun FeedbackDialog(vm: SettingViewModel, onDismissRequest: () -> Unit) { Dialog(onDismissRequest = onDismissRequest) { Column( modifier = Modifier .fillMaxWidth() .background( MaterialTheme.colorScheme.surface, RoundedCornerShape(8.dp) ) ) { Surface( modifier = Modifier .fillMaxWidth() .clickable { vm.feedbackByAppStore(this@SettingActivity) onDismissRequest() } .padding(25.dp, 10.dp, 25.dp, 5.dp) ) { PrimaryText( modifier = Modifier.padding(13.dp, 13.dp, 13.dp, 13.dp), text = getString(R.string.setting_feedback_dialog_app_store) ) } Surface( modifier = Modifier .fillMaxWidth() .clickable { vm.feedbackByEmail(this@SettingActivity) onDismissRequest() } .padding(25.dp, 5.dp, 25.dp, 5.dp) ) { PrimaryText( modifier = Modifier.padding(13.dp, 13.dp, 13.dp, 13.dp), text = getString(R.string.setting_feedback_dialog_email) ) } Surface( modifier = Modifier .fillMaxWidth() .clickable { vm.feedbackByGithub(this@SettingActivity) onDismissRequest() } .padding(25.dp, 5.dp, 25.dp, 10.dp) ) { PrimaryText( modifier = Modifier.padding(13.dp, 13.dp, 13.dp, 13.dp), text = getString(R.string.setting_feedback_dialog_github) ) } } } } }
0
Kotlin
11
94
f5ba12c5f80cfd192a5667e488ccd86c00b6a65b
19,662
NotionLight
Apache License 2.0
connectors/v20182/src/main/java/de/pbauerochse/worklogviewer/connector/v2018/domain/grouping/UnknownGroupByParameter.kt
Bhanditz
168,944,765
false
null
package de.pbauerochse.worklogviewer.connector.v2018.domain.grouping import com.fasterxml.jackson.annotation.JsonIgnoreProperties import de.pbauerochse.worklogviewer.connector.GroupByParameter @JsonIgnoreProperties(ignoreUnknown = true) class UnknownGroupByParameter : GroupByParameter { override val id: String = "UNKNOWN" override fun getLabel(): String = "UNKNOWN" }
1
null
1
1
bf2cd66f3fc030d501f5a0c72827ba3e30aae555
379
youtrack-worklog-viewer
MIT License
tmp/arrays/kotlinAndJava/448.kt
mandelshtamd
249,374,670
true
{"Kotlin": 7965847}
//File A.java import kotlin.Metadata; import kotlin.jvm.internal.MutablePropertyReference1Impl; import kotlin.jvm.internal.Reflection; import kotlin.properties.Delegates; import kotlin.properties.ReadWriteProperty; import kotlin.reflect.KProperty; import org.jetbrains.annotations.NotNull; public class A { // $FF: synthetic field static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.mutableProperty1(new MutablePropertyReference1Impl(Reflection.getOrCreateKotlinClass(A.class), "value", "getValue()Ljava/lang/Object;"))}; @NotNull private final ReadWriteProperty value$delegate; @NotNull protected final Object getValue() { return this.value$delegate.getValue(this, $$delegatedProperties[0]); } private final void setValue(Object var1) { this.value$delegate.setValue(this, $$delegatedProperties[0], var1); } public A() { this.value$delegate = Delegates.INSTANCE.notNull(); } } //File B.java import kotlin.Metadata; public final class B extends A { } //File Main.kt // IGNORE_BACKEND_FIR: JVM_IR // KJS_WITH_FULL_RUNTIME // WITH_RUNTIME import kotlin.properties.Delegates fun box(): String { B() return "OK" }
1
Kotlin
1
1
da010bdc91c159492ae74456ad14d93bdb5fdd0a
1,216
bbfgradle
Apache License 2.0
app/src/main/java/com/example/mycommish/ui/theme/Color.kt
moaliyou
786,551,198
false
{"Kotlin": 13516}
package com.example.mycommish.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF4659A9) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFDDE1FF) val md_theme_light_onPrimaryContainer = Color(0xFF001355) val md_theme_light_secondary = Color(0xFF6F5D00) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFE16A) val md_theme_light_onSecondaryContainer = Color(0xFF221B00) val md_theme_light_tertiary = Color(0xFF4659A9) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFDDE1FF) val md_theme_light_onTertiaryContainer = Color(0xFF001355) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFEFBFF) val md_theme_light_onBackground = Color(0xFF1B1B1F) val md_theme_light_surface = Color(0xFFFEFBFF) val md_theme_light_onSurface = Color(0xFF1B1B1F) val md_theme_light_surfaceVariant = Color(0xFFE2E1EC) val md_theme_light_onSurfaceVariant = Color(0xFF45464F) val md_theme_light_outline = Color(0xFF767680) val md_theme_light_inverseOnSurface = Color(0xFFF2F0F4) val md_theme_light_inverseSurface = Color(0xFF303034) val md_theme_light_inversePrimary = Color(0xFFB8C3FF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF4659A9) val md_theme_light_outlineVariant = Color(0xFFC6C5D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFB8C3FF) val md_theme_dark_onPrimary = Color(0xFF112878) val md_theme_dark_primaryContainer = Color(0xFF2C4090) val md_theme_dark_onPrimaryContainer = Color(0xFFDDE1FF) val md_theme_dark_secondary = Color(0xFFE2C54A) val md_theme_dark_onSecondary = Color(0xFF3A3000) val md_theme_dark_secondaryContainer = Color(0xFF544600) val md_theme_dark_onSecondaryContainer = Color(0xFFFFE16A) val md_theme_dark_tertiary = Color(0xFFB8C3FF) val md_theme_dark_onTertiary = Color(0xFF112878) val md_theme_dark_tertiaryContainer = Color(0xFF2C4090) val md_theme_dark_onTertiaryContainer = Color(0xFFDDE1FF) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1B1B1F) val md_theme_dark_onBackground = Color(0xFFE4E1E6) val md_theme_dark_surface = Color(0xFF1B1B1F) val md_theme_dark_onSurface = Color(0xFFE4E1E6) val md_theme_dark_surfaceVariant = Color(0xFF45464F) val md_theme_dark_onSurfaceVariant = Color(0xFFC6C5D0) val md_theme_dark_outline = Color(0xFF90909A) val md_theme_dark_inverseOnSurface = Color(0xFF1B1B1F) val md_theme_dark_inverseSurface = Color(0xFFE4E1E6) val md_theme_dark_inversePrimary = Color(0xFF4659A9) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFB8C3FF) val md_theme_dark_outlineVariant = Color(0xFF45464F) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFF4F5B92)
1
Kotlin
0
0
dac4e5b542774e6639c17631a5006b7ceff5abf0
3,202
My-Commish
MIT License
paletteon-icons/src/commonMain/kotlin/dev/teogor/paletteon/icons/filled/ContrastDropInverse.kt
teogor
849,961,511
false
{"Kotlin": 482882}
/* * Copyright 2024 Teogor (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.teogor.paletteon.icons.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import dev.teogor.paletteon.icons.Icons public val Icons.Filled.ContrastDropInverse: ImageVector get() { if (_contrastDropInverse != null) { return _contrastDropInverse!! } _contrastDropInverse = Builder(name = "ContrastDropInverse", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.6367f, 6.6367f) lineTo(12.0f, 0.2734f) lineTo(18.3633f, 6.6367f) curveTo(21.8789f, 10.1523f, 21.8789f, 15.8477f, 18.3633f, 19.3633f) curveTo(14.8477f, 22.8789f, 9.1523f, 22.8789f, 5.6367f, 19.3633f) curveTo(2.1211f, 15.8477f, 2.1211f, 10.1523f, 5.6367f, 6.6367f) close() moveTo(7.0508f, 8.0508f) curveTo(5.0469f, 10.0508f, 4.4492f, 13.0664f, 5.5313f, 15.6797f) curveTo(6.6172f, 18.2969f, 9.1719f, 20.0f, 12.0039f, 20.0f) lineTo(12.0f, 3.1016f) close() moveTo(7.0508f, 8.0508f) } } .build() return _contrastDropInverse!! } private var _contrastDropInverse: ImageVector? = null
0
Kotlin
0
2
de712f6bb9d48be94e204086cbddabd32110d61d
2,609
paletteon
Apache License 2.0
app/src/main/java/employee/summon/asano/adapter/FilterableAdapter.kt
kwote
130,745,182
false
{"Gradle": 3, "Java Properties": 1, "Text": 1, "Ignore List": 2, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 40, "Kotlin": 28}
package employee.summon.asano.adapter import android.support.v7.widget.RecyclerView import android.widget.Filterable abstract class FilterableAdapter<T : RecyclerView.ViewHolder> : RecyclerView.Adapter<T>(), Filterable
0
Kotlin
0
0
2f5b2866bb67048dcc67b42f93a5d18e18e68dab
220
summon_employee_android
MIT License
EjemploRecycler2223/app/src/main/java/com/example/ejemplorecycler2223/MainActivity.kt
aranzabe
542,008,470
false
{"Text": 28, "Ignore List": 111, "Markdown": 1, "Gradle": 103, "Java Properties": 83, "Shell": 32, "Batchfile": 32, "Proguard": 39, "Kotlin": 195, "XML": 1028, "Gradle Kotlin DSL": 2, "INI": 36, "SQL": 4, "JAR Manifest": 1, "Maven POM": 1, "Java": 210, "JSON": 391}
package com.example.ejemplorecycler2223 import Adaptadores.MiAdaptadorRecycler import Modelo.FactoriaListaPersonaje import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.ejemplorecycler2223.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { var personajes = FactoriaListaPersonaje.generaLista(12) lateinit var miRecyclerView : RecyclerView lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_main) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) Log.e("Fernando", personajes.toString()) miRecyclerView = binding.listaPersonajesRecycler as RecyclerView miRecyclerView.setHasFixedSize(true) miRecyclerView.layoutManager = LinearLayoutManager(this) var miAdapter = MiAdaptadorRecycler(personajes, this) miRecyclerView.adapter = miAdapter binding.btDetalle.setOnClickListener { if (MiAdaptadorRecycler.seleccionado >= 0) { val pe = personajes.get(MiAdaptadorRecycler.seleccionado) Log.e("Fernando",pe.toString()) } else { Toast.makeText(this,"Selecciona algo previamente", Toast.LENGTH_SHORT).show() } } } }
0
Java
0
0
0dc4782d3cc311488a48d2b8763c56cbc66ca58f
1,628
AndroidDAM2_22_23
MIT License
ktor/server/src/main/kotlin/org/requestscript/ktor/server/resource/InternalResourceResolver.kt
merideum
470,393,991
false
{"Gradle Kotlin DSL": 7, "INI": 2, "Markdown": 3, "Shell": 3, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 25, "Java": 6, "ANTLR": 2, "YAML": 1, "XML": 1}
package org.requestscript.ktor.server.resource import org.requestscript.core.interpreter.Resource import org.requestscript.core.interpreter.ResourceResolver data class InternalResourceResolver( // Map resourcePath, Resource val resources: Map<String, Resource> ): ResourceResolver { override fun get(name: String) = resources[name] }
4
Java
0
2
9cb07e9275ddc438f33b88418d491199f93c0a33
348
requestscript-kotlin
Apache License 2.0
SampleCode-V5/android-sdk-v5-sample/app-aircraft/src/main/java/dji/sampleV5/aircraft/AircraftTestingToolsActivity.kt
sorajiro0802
686,880,930
true
{"Markdown": 3, "Text": 1, "Ignore List": 1, "Gradle": 7, "XML": 753, "Kotlin": 384, "Java": 450, "HTML": 670, "JSON": 4, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "SCSS": 12, "CSS": 4, "JavaScript": 24, "SVG": 24}
package dji.sampleV5.aircraft import androidx.fragment.app.commit import dji.sampleV5.moduleaircraft.AircraftMSDKInfoFragment import dji.sampleV5.modulecommon.TestingToolsActivity import dji.sampleV5.modulecommon.data.CommonFragmentPageInfoFactory import dji.sampleV5.modulecommon.data.FragmentPageItemList import dji.sampleV5.moduleaircraft.data.AircraftFragmentPageInfoFactory import dji.sampleV5.modulecommon.R import java.util.* /** * Class Description * * @author Hoker * @date 2021/3/9 * * Copyright (c) 2021, DJI All Rights Reserved. */ class AircraftTestingToolsActivity : TestingToolsActivity() { override fun loadPages() { msdkCommonOperateVm.apply { val itemList = LinkedHashSet<FragmentPageItemList>().also { it.add(CommonFragmentPageInfoFactory().createPageInfo()) it.add(AircraftFragmentPageInfoFactory().createPageInfo()) } loaderItem(itemList) } } override fun loadTitleView() { supportFragmentManager.commit { replace(R.id.main_info_fragment_container, AircraftMSDKInfoFragment()) } } }
0
Java
0
0
e323847fe17f4d9752dc09fe73e1c2cc15201f27
1,142
Mobile-SDK-Android-V5
MIT License
src/test/kotlin/org/jetbrains/intellij/tasks/SignPluginTaskSpec.kt
r2ys
368,802,774
true
{"Kotlin": 318586}
package org.jetbrains.intellij.tasks import org.jetbrains.intellij.IntelliJPluginConstants import org.jetbrains.intellij.IntelliJPluginSpecBase import kotlin.test.Test import kotlin.test.assertTrue class SignPluginTaskSpec : IntelliJPluginSpecBase() { @Test fun `reuse configuration cache`() { build(IntelliJPluginConstants.SIGN_PLUGIN_TASK_NAME, "--configuration-cache") val result = build(IntelliJPluginConstants.SIGN_PLUGIN_TASK_NAME, "--configuration-cache") assertTrue(result.output.contains("Reusing configuration cache.")) } }
0
null
0
0
58115823d6ca767cec5c858cf5add185dd4af968
574
gradle-intellij-plugin
Apache License 2.0
app/src/main/java/com/mhuman/movieplot/network/model/MovieInfoResponse.kt
machine-human
221,143,852
false
null
package com.mhuman.movieplot.network.model import androidx.room.Entity import com.google.gson.annotations.SerializedName data class MovieInfoResponse( @SerializedName("page") val page: Int?, @SerializedName("results") val results: List<MovieInfoList>?, @SerializedName("total_pages") val totalPages: Int?, @SerializedName("total_results") val totalResults: Int? ) @Entity(tableName = "movieInfo", primaryKeys = ["id"]) data class MovieInfoList( @SerializedName("id") val id: Int?, @SerializedName("overview") val overview: String?, @SerializedName("poster_path") val posterPath: String?, @SerializedName("title") val title: String? /* @SerializedName("adult") val adult: Boolean?,*/ /* @SerializedName("backdrop_path") val backdropPath: String?,*/ /* @SerializedName("genre_ids") val genreIds: List<Int>?,*/ /* @SerializedName("original_language") val original_language: String?, @SerializedName("original_title") val original_title: String?,*/ /* @SerializedName("popularity") val popularity: Double?,*/ /* @SerializedName("release_date") val release_date: String?,*/ /* @SerializedName("video") val video: Boolean?, @SerializedName("vote_average") val vote_average: Double?, @SerializedName("vote_count") val vote_count: Int?*/ )
0
Kotlin
0
0
64a2b96127911dcb8a3ba6f1e0ea831263cd9e85
1,388
MoviePlot
Apache License 2.0
app/src/main/java/com/example/moviesapp/ui/tvshow/TvShowFragment.kt
resqiar
253,286,300
false
{"Kotlin": 58598}
package com.example.moviesapp.ui.tvshow import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.example.moviesapp.R import com.example.moviesapp.backend.data.api.MovieDBClient import com.example.moviesapp.backend.data.api.MovieDBInterface import com.example.moviesapp.backend.data.repository.NetworkState import com.example.moviesapp.ui.tvshow.adapter.TVAdapter import com.example.moviesapp.ui.tvshow.viewmodel.TVViewModel import kotlinx.android.synthetic.main.fragment_tvshow.* class TvShowFragment : Fragment() { // view model private lateinit var viewModel: TVViewModel // pagination lateinit var tvListRepository: TVListRepository override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_tvshow, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) rv_tvshow.setHasFixedSize(true) // API SERVICE val api: MovieDBInterface = MovieDBClient.getClient() tvListRepository = TVListRepository(api) // VIEW MODEL viewModel = getViewModel() // SHOW RECYCLERVIEW val tvAdapter = context?.let { TVAdapter(it) } val gridLayoutManager = GridLayoutManager(context, 3) // modify span gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val viewType = tvAdapter?.getItemViewType(position) return if (viewType == tvAdapter?.TV_TYPE) 1 else 3 // jika MOVIE_TYPE maka occupy menjadi 1 baris } } // set adapter rv_tvshow.layoutManager = gridLayoutManager rv_tvshow.adapter = tvAdapter tvAdapter?.setOnItemClickCallback(object : TVAdapter.OnItemClickCallback { override fun onItemClicked(id: Int?) { //siapkan data val bundle = Bundle() // masukkan ke bundle if (id != null) { bundle.putInt("id", id) } // buat perpindahan fragment view.findNavController() .navigate(R.id.action_navigation_tvshow_to_navigation_tvshow_detail, bundle) } }) // VIEW MODEL viewModel.tvPagedList.observe(viewLifecycleOwner, Observer { tvAdapter?.submitList(it) }) // network state viewModel.networkState.observe(viewLifecycleOwner, Observer { progressBar_tv.visibility = if (viewModel.isEmpty() && it == NetworkState.LOADING) View.VISIBLE else View.GONE error_messages_tv.visibility = if (viewModel.isEmpty() && it == NetworkState.ERROR) View.VISIBLE else View.GONE if (!viewModel.isEmpty()) { tvAdapter?.setNetworkState(it) } }) } // get view model fun getViewModel(): TVViewModel { return ViewModelProvider(this, object : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return TVViewModel(tvListRepository) as T } })[TVViewModel::class.java] } }
1
Kotlin
0
0
930cf82a86f6365786ba00282bb1cfb6875d4b36
3,766
Simple-Movie-Catalog
Creative Commons Zero v1.0 Universal
src/jsMain/kotlin/matt/http/internet/internet.kt
mgroth0
532,378,353
false
null
package matt.http.internet import org.w3c.xhr.XMLHttpRequest actual fun TheInternet.isAvailable(): Boolean { val req = XMLHttpRequest() req.open("GET", "https://www.google.com/") require(req.status == 200.toShort()) { "detecting offline in JS is not implemented yet" } return true }
0
Kotlin
0
0
6d214b63657e675d3487fb780e862a77a106361c
296
http
MIT License
src/main/kotlin/com/urielsalis/mccrashlib/parser/MinecraftCrashParser.kt
urielsalis
254,932,939
false
null
package com.urielsalis.mccrashlib.parser import arrow.core.Either import arrow.core.Option import com.urielsalis.mccrashlib.Crash import com.urielsalis.mccrashlib.deobfuscator.getDeobfuscation import java.io.File /* Minecraft crashes are separated into sections starting and ending with -- "Minecraft Crash Report" contains the exception, "System Details" contains more information The exception starts with java.lang and it includes all lines until the first empty line "System Details" contains a : separated key value pair. We care about "Is Modded" */ private const val crashReportSection = "Minecraft Crash Report" private const val systemDetailsSection = "System Details" private const val isModded = "Is Modded" private const val minecraftVersion = "Minecraft Version" private const val minecraftVersionId = "Minecraft Version ID" private const val typeSection = "Type" private const val affectedLevelSection = "Affected level" private const val levelWasModded = "Level was modded" class MinecraftCrashParser : CrashParser { object SectionsNotFound : ParserError object NoExceptionFound : ParserError override fun parse(lines: List<String>, mappingsDirectory: File): Either<ParserError, Crash> { val sections = parseSections(lines) if (!sections.containsKey(crashReportSection) || !sections.containsKey(systemDetailsSection)) { return Either.left(SectionsNotFound) } val details = getDetails(sections[systemDetailsSection] ?: error("System details section not found")) val isModded = isGameModded(details) val affectedLevel = sections[affectedLevelSection]?.let(::getDetails) val wasLevelModded = affectedLevel?.let(::wasLevelModded) val exception = getException(sections[crashReportSection] ?: error("Crash report section not found")) val version = getMinecraftVersion(details) val type = getType(details) val isClient = type.contains("map_client.txt") val deobf = if (isModded || version == null) null else try { getDeobfuscation(version, lines.joinToString("\n"), isClient, mappingsDirectory) } catch (e: IllegalArgumentException) { // Ignore exception for missing mappings null } return exception.fold( { Either.left(NoExceptionFound) }, { Either.right( Crash.Minecraft( isModded, wasLevelModded, it, version, isClient, deobf, getException(deobf?.split("\n") ?: emptyList()).orNull() ) ) } ) } private fun getMinecraftVersion(details: Map<String, String>) = // Fall back to looking up "Minecraft Version"; older versions did not have "Minecraft Version ID" details[minecraftVersionId] ?: details[minecraftVersion] private fun getType(details: Map<String, String>) = details.getOrDefault(typeSection, "Client (map_client.txt)") private fun isGameModded(details: Map<String, String>) = details.containsKey(isModded) && with(details[isModded] ?: error("Is Modded not found")) { !contains("Probably Not", true) && !contains("Unknown", true) } private fun wasLevelModded(affectedLevelDetails: Map<String, String>): Boolean? = when (affectedLevelDetails[levelWasModded]) { "true" -> true "false" -> false else -> null } private fun getException(lines: List<String>): Option<String> { var foundStart = false val builder = StringBuilder() lines.map(String::trim).forEach { when { !foundStart -> if ( it.startsWith("java.lang") || it.startsWith("java.util") || it.startsWith("org.lwjgl") ) { foundStart = true builder.append(it) } else -> when { it.isBlank() -> return Option.just(builder.toString()) else -> builder.append("\n" + it) } } } return Option.empty() } private fun getDetails(list: List<String>) = list .map(String::trim) .associate { val pairs = it.split(":") pairs.first() to pairs.getOrElse(1) { "" }.removePrefix(" ") } private fun parseSections(lines: List<String>): Map<String, List<String>> { val sections = mutableMapOf<String, List<String>>() val currentLines = mutableListOf<String>() var sectionName = "" lines.map(String::trim).forEach { if (it.startsWith("--") && it.endsWith("--")) { sections[sectionName] = currentLines.toList() currentLines.clear() sectionName = it.replace("-", "").trim() } else { currentLines.add(it) } } sections[sectionName] = currentLines return sections } }
0
Kotlin
2
4
8c9f27db6751fe400d1bcc6ba49bfcf2df7cba5b
5,260
mc-crash-lib
MIT License
back/kotlin/app/delivery/feature/game/Launcher.kt
Suprajeff
787,329,771
false
{"Kotlin": 56340, "Swift": 53773, "Go": 48229, "TypeScript": 46088, "Dockerfile": 5262, "CSS": 2330, "HTML": 1887}
package delivery.feature.game import io.lettuce.core.RedisClient import io.lettuce.core.api.sync.RedisCommands import io.lettuce.core.api.async.RedisAsyncCommands import io.ktor.server.application.* import io.ktor.server.routing.* import core.database.redis.RedisData import core.data.implementation.redis.GameRepositoryImpl import core.service.game.GameStateChecker import core.service.game.GameLogic import core.domain.GameUseCases import delivery.utils.responses.GameResponses import delivery.feature.game.controllers.GameController import delivery.feature.game.endpoints.GameEndpoints fun launchGameFeature(application: Application, redisData: RedisData){ val gameRepository = GameRepositoryImpl(redisData) val gameChecker = GameStateChecker() val gameLogic = GameLogic(gameChecker) val gameUseCases = GameUseCases(gameRepository, gameLogic) val gameResponses = GameResponses() val gameController = GameController(gameUseCases, gameResponses) val gameRoutes = GameEndpoints(gameController, application).gameRoutes() }
0
Kotlin
0
0
d6a6f317f4d7a5eef6773fd7fdfe36a82c682291
1,059
tic_tac_toe
Apache License 2.0
app/src/main/kotlin/io/orangebuffalo/simpleaccounting/business/workspaces/impl/WorkspacesRepositoryExtImpl.kt
orange-buffalo
154,902,725
false
{"Kotlin": 1125040, "TypeScript": 575303, "Vue": 277186, "SCSS": 30742, "JavaScript": 6817, "HTML": 633, "CSS": 10}
package io.orangebuffalo.simpleaccounting.business.workspaces.impl import io.orangebuffalo.simpleaccounting.business.workspaces.Workspace import io.orangebuffalo.simpleaccounting.infra.jooq.fetchListOf import io.orangebuffalo.simpleaccounting.infra.jooq.fetchOneOrNull import io.orangebuffalo.simpleaccounting.services.persistence.model.Tables import io.orangebuffalo.simpleaccounting.business.workspaces.WorkspacesRepositoryExt import org.jooq.DSLContext import org.springframework.stereotype.Repository @Repository class WorkspacesRepositoryExtImpl( private val dslContext: DSLContext ) : WorkspacesRepositoryExt { private val workspace = Tables.WORKSPACE override fun findAllByOwnerUserName(userName: String): List<Workspace> { val owner = Tables.PLATFORM_USER return dslContext .select(*workspace.fields()) .from(workspace) .join(owner).on(owner.id.eq(workspace.ownerId)) .where(owner.userName.eq(userName)) .fetchListOf() } override fun findByIdAndOwnerUserName(workspaceId: Long, userName: String): Workspace? { val owner = Tables.PLATFORM_USER return dslContext .select(*workspace.fields()) .from(workspace) .join(owner).on(owner.id.eq(workspace.ownerId)) .where( owner.userName.eq(userName), workspace.id.eq(workspaceId) ) .fetchOneOrNull() } }
69
Kotlin
0
1
338561f53e937c14a46d17b29ceedee7f90af197
1,478
simple-accounting
Creative Commons Attribution 3.0 Unported
src/main/kotlin/no/nav/helse/arbeidsgiver/utils/LoggingUtils.kt
navikt
293,487,810
false
null
package no.nav.helse.arbeidsgiver.utils import org.slf4j.MDC internal fun withMDC(context: Map<String, String>, block: () -> Unit) { val contextMap = MDC.getCopyOfContextMap() ?: emptyMap() try { MDC.setContextMap(contextMap + context) block() } finally { MDC.setContextMap(contextMap) } }
8
Kotlin
0
0
1bf1c477de29b011c6be9936b4328aa5409aacd4
332
helse-arbeidsgiver-felles-backend
MIT License
androidApp/src/main/java/com/andriuswill/spacemissionkmp/android/presenter/launchdetails/LaunchDetailsViewModel.kt
andriuswill
739,092,112
false
{"Kotlin": 25081, "Swift": 920}
package com.andriuswill.spacemissionkmp.android.presenter.launchdetails import androidx.lifecycle.viewModelScope import com.andriuswill.spacemissionkmp.android.core.base.BaseViewModel import com.andriuswill.spacemissionkmp.android.core.base.Reducer import com.andriuswill.spacemissionkmp.domain.usecases.LaunchesUseCase import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class LaunchDetailsViewModel( private val launchesUseCase: LaunchesUseCase ) : BaseViewModel<LaunchDetailsState, LaunchDetailsAction>() { override val state: StateFlow<LaunchDetailsState> get() = reducer.state override fun updateState(newState: (LaunchDetailsState) -> LaunchDetailsState) { reducer.setState(newState.invoke(reducer.state.value)) } private val reducer = LaunchDetailsReducer(LaunchDetailsState.Initial) fun sendEvent(action: LaunchDetailsAction) { reducer.sendAction(action) } inner class LaunchDetailsReducer( initialValue: LaunchDetailsState ) : Reducer<LaunchDetailsState, LaunchDetailsAction>(initialValue) { override fun reduce(oldState: LaunchDetailsState, action: LaunchDetailsAction) { when(action){ is LaunchDetailsAction.LoadLaunchDetails -> Unit } } } fun loadLaunchDetails(){ viewModelScope.launch { } } }
0
Kotlin
0
1
f18d5d0cdd81391ddd0a49a3c435b651e3d0a4c4
1,388
SpaceMissionKMP
MIT License
presentation/src/main/java/com/nemesis/rio/presentation/app/AppModule.kt
N3-M3-S1S
370,791,918
false
null
package com.nemesis.rio.presentation.app import com.nemesis.rio.presentation.app.browser.UrlBrowser import com.nemesis.rio.presentation.app.clipboard.Clipboard import com.nemesis.rio.presentation.app.initialization.ApplicationInitializationState import com.nemesis.rio.presentation.app.messages.MessageManager import com.nemesis.rio.presentation.utils.LoadingStateController import com.nemesis.rio.presentation.view.databinding.DefaultBindingAdapters import com.nemesis.rio.utils.checksum.FileChecksumGenerator import com.nemesis.rio.utils.checksum.MD5FileChecksumGenerator import org.koin.dsl.bind import org.koin.dsl.factory import org.koin.dsl.module import org.koin.dsl.single import java.time.ZoneId import java.time.format.DateTimeFormatter val appModule = module { single<MessageManager>() single<Clipboard>() single<UrlBrowser>() single<ApplicationInitializationState>() factory<LoadingStateController>() single<MD5FileChecksumGenerator>() bind FileChecksumGenerator::class single { DefaultBindingAdapters().apply { setDateTimeFormatter(get()) } } single { DateTimeFormatter .ofPattern("dd.MM.yyyy HH:mm:ss") .withZone(ZoneId.systemDefault()) } }
0
Kotlin
0
0
62dc309a7b4b80ff36ea624bacfa7b00b5d8607e
1,225
rio
MIT License
app/src/main/java/com/e444er/cleanmovie/feature_splash/presentation/splash/SplashFragment.kt
e444er
597,756,971
false
null
package com.e444er.cleanmovie.feature_splash.presentation.splash import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDelegate import androidx.core.os.LocaleListCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import com.e444er.cleanmovie.R import com.e444er.cleanmovie.core.presentation.util.asString import com.e444er.cleanmovie.feature_splash.presentation.splash.event.SplashEvent import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @AndroidEntryPoint class SplashFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_splash, container, false) } private val viewModel: SplashViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.eventFlow.collectLatest { event -> when (event) { is SplashEvent.NavigateTo -> { findNavController().navigate(event.directions) } is SplashEvent.UpdateAppLanguage -> { AppCompatDelegate.setApplicationLocales( LocaleListCompat.forLanguageTags( event.language ) ) } is SplashEvent.UpdateUiMode -> { if (event.uiMode == AppCompatDelegate.MODE_NIGHT_YES) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } } } } } } } }
0
Kotlin
0
0
1c939de424b4eb254fd4258f4e56e4399bdfb3cd
2,687
KinoGoClean
Apache License 2.0
app/src/main/java/com/czech/muvies/utils/EpisodesListTransformer.kt
Czeach
264,795,366
false
null
package com.czech.muvies.utils import android.view.View import androidx.viewpager2.widget.ViewPager2 import kotlin.math.abs class EpisodesListTransformer : ViewPager2.PageTransformer { override fun transformPage(page: View, position: Float) { val absPos = abs(position) page.apply { translationY = absPos * 200f translationX = absPos * 400f } when { position < -1 -> page.alpha = 0.1f position <= 1 -> { page.alpha = 0.2f.coerceAtLeast(1 - absPos) } else -> page.alpha = 0.1f } } }
0
Kotlin
3
5
7f1af79d5da40fe3cc608dd45bb70226887e1922
639
Muvies
MIT License
src/main/kotlin/no/nav/personbruker/dittnav/api/oppgave/Oppgave.kt
navikt
202,547,457
false
null
@file:UseSerializers(ZonedDateTimeSerializer::class) package no.nav.personbruker.dittnav.api.oppgave import kotlinx.serialization.Serializable import kotlinx.serialization.UseSerializers import no.nav.personbruker.dittnav.api.common.serializer.ZonedDateTimeSerializer import java.time.ZonedDateTime @Serializable data class Oppgave( val forstBehandlet: ZonedDateTime, val fodselsnummer: String, val eventId: String, val grupperingsId: String, val tekst: String, val link: String, val produsent: String, val sikkerhetsnivaa: Int, val sistOppdatert: ZonedDateTime, val aktiv: Boolean, val eksternVarslingSendt: Boolean, val eksternVarslingKanaler: List<String> ) { private fun toMaskedOppgaveDTO(): OppgaveDTO = this.toOppgaveDTO() .copy(tekst = "***", link = "***", produsent = "***") private fun toOppgaveDTO(): OppgaveDTO = OppgaveDTO( forstBehandlet = forstBehandlet, eventId = eventId, tekst = tekst, link = link, produsent = produsent, sistOppdatert = sistOppdatert, sikkerhetsnivaa = sikkerhetsnivaa, aktiv = aktiv, grupperingsId = grupperingsId, eksternVarslingSendt = eksternVarslingSendt, eksternVarslingKanaler = eksternVarslingKanaler ) internal fun toOppgaveDTO(loginLevel: Int): OppgaveDTO { return if (loginLevel >= sikkerhetsnivaa) { toOppgaveDTO() } else { toMaskedOppgaveDTO() } } } @Serializable data class OppgaveDTO( val forstBehandlet: ZonedDateTime, val eventId: String, val tekst: String, val link: String, val produsent: String, val sistOppdatert: ZonedDateTime, val sikkerhetsnivaa: Int, val aktiv: Boolean, val grupperingsId: String, val eksternVarslingSendt: Boolean, val eksternVarslingKanaler: List<String> )
0
Kotlin
0
2
c63de5469d6828e684c1d7e4e117540ec316c37a
1,971
dittnav-api
MIT License
extension/music/src/main/kotlin/bogus/extension/music/Jukebox.kt
gavenda
470,871,977
false
null
package bogus.extension.music import bogus.extension.music.db.guilds import bogus.extension.music.player.* import bogus.util.asFMTLogger import bogus.util.escapedBackticks import bogus.util.idLong import com.kotlindiscord.kord.extensions.i18n.TranslationsProvider import com.kotlindiscord.kord.extensions.koin.KordExKoinComponent import dev.kord.common.entity.Snowflake import dev.kord.core.behavior.GuildBehavior import dev.kord.core.entity.Guild import dev.kord.core.entity.channel.GuildMessageChannel import io.micrometer.core.instrument.MeterRegistry import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mu.KotlinLogging import org.koin.core.component.inject import org.ktorm.database.Database import org.ktorm.dsl.eq import org.ktorm.entity.firstOrNull import java.util.* import java.util.concurrent.ConcurrentHashMap /** * Plays music via a play request. */ object Jukebox : KordExKoinComponent { private val log = KotlinLogging.logger {}.asFMTLogger() private val players = ConcurrentHashMap<Snowflake, MusicPlayer>() private val tp by inject<TranslationsProvider>() private val db by inject<Database>() private val registry by inject<MeterRegistry>() init { registry.gauge(Metric.SONGS_PLAYING, players.values) { it.map { player -> player.queued }.reduce { acc, queued -> acc + queued }.toDouble() } } /** * Register a guild to this [Jukebox]. * @param guildId the guild snowflake to register */ fun register(guildId: Snowflake) { players.computeIfAbsent(guildId) { val musicPlayer = if (LAVAKORD_ENABLED) { LinkMusicPlayer(guildId) } else { LavaMusicPlayer(guildId) } log.debug { message = "Music player created" context = mapOf( "guildId" to guildId ) } return@computeIfAbsent musicPlayer } } /** * Returns a player for the specified guild snowflake. * @param guildId the guild snowflake to retrieve a player from */ fun playerFor(guildId: Snowflake): MusicPlayer { return players[guildId] ?: error("Guild not registered") } private fun mutexFor(request: PlayRequest): Mutex { return playerFor(request.guild.id).mutex } suspend fun bind(guild: Guild) { val dbGuild = db.guilds.firstOrNull { it.discordGuildId eq guild.idLong } ?: return val textChannelId = dbGuild.textChannelId val lastMessageId = dbGuild.lastMessageId playerFor(guild.id).apply { if (textChannelId != null) { val textChannel = guild.getChannel(Snowflake(textChannelId)) as GuildMessageChannel if (lastMessageId != null) { val textMessage = textChannel.getMessage(Snowflake(lastMessageId)) textMessage.delete("Crash cleanup") } // Apply volume volumeTo(dbGuild.volume, update = false) dbGuild.lastMessageId = bind(textChannel)?.value?.toLong() dbGuild.flushChanges() log.info { message = "Guild bound" context = mapOf( "guildId" to guild.id ) } } } } suspend fun tryToDisconnect() { players.values.forEach { player -> val lastPlayMillis = player.lastPlayMillis if (!player.playing && System.currentTimeMillis() > lastPlayMillis) { player.disconnect() } } } suspend fun destroy() { players.forEach { (guildId, player) -> player.unbind() val dbGuild = db.guilds.firstOrNull { it.discordGuildId eq guildId.value.toLong() } ?: return@forEach dbGuild.lastMessageId = null dbGuild.flushChanges() } } data class PlayRequest( val respond: suspend (String) -> Unit, val respondMultiple: suspend (List<MusicTrack>, suspend (MusicTrack) -> String) -> Unit, val parseResult: IdentifierParser.IdentifierParseResult, val guild: GuildBehavior, val mention: String, val userId: Snowflake, val locale: Locale ) /** * Plays a play request immediately. * @return response, empty string if successful. */ suspend fun playNow(request: PlayRequest): String = mutexFor(request).withLock { val (respond, respondMultiple, parseResult, guild, mention, userId, locale) = request val identifiers = parseResult.identifiers if (identifiers.isEmpty()) { log.info { message = "No identifiers found" context = mapOf( "identifiers" to identifiers, "userId" to userId, "guildId" to guild.id ) } return tp.translate("response.jukebox.not-found", locale, TRANSLATION_BUNDLE) } else if (identifiers.size > 1) { return tp.translate("response.jukebox.no-cheating", locale, TRANSLATION_BUNDLE) } val identifier = identifiers.first() val item = guild.player.loader.loadItem(identifier) val trackLoaded: suspend (MusicTrack) -> String = { val track = it.copy(userId = userId, mention = mention) if (guild.player.playing) { val currentTrack = guild.player.playingTrack if (currentTrack != null) { guild.player.addFirst(currentTrack.makeClone()) } guild.player.addFirst(track) guild.player.skip() } else { guild.player.addFirst(track, update = true) } registry.counter(Metric.SONGS_QUEUED).increment() tp.translate( key = "response.jukebox.play-now", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(track.title.escapedBackticks) ) } when (item.loadType) { TrackLoadType.TRACK_LOADED -> { respond(trackLoaded(item.track)) } TrackLoadType.PLAYLIST_LOADED -> { respond(tp.translate("response.jukebox.no-cheating", locale, TRANSLATION_BUNDLE)) } TrackLoadType.SEARCH_RESULT -> { if (parseResult.spotify) { respond(trackLoaded(item.tracks.first())) } else { respondMultiple(item.tracks) { trackLoaded(it) } } } TrackLoadType.NO_MATCHES -> { respond( tp.translate( key = "response.jukebox.no-matches", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(identifier) ) ) } TrackLoadType.LOAD_FAILED -> { respond( tp.translate( key = "response.jukebox.error", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(item.error ?: "Loading failed") ) ) } } log.info { message = "Playing now" context = mapOf( "identifier" to identifier, "userId" to userId, "guildId" to guild.id ) } return "" } /** * Plays a play request next in the queue. * @return response, empty string if successful. */ suspend fun playNext(request: PlayRequest): String = mutexFor(request).withLock { val (respond, respondMultiple, parseResult, guild, mention, userId, locale) = request val identifiers = parseResult.identifiers if (identifiers.isEmpty()) { log.info { message = "No identifiers found" context = mapOf( "identifiers" to identifiers, "userId" to userId, "guildId" to guild.id ) } return tp.translate("response.jukebox.not-found", locale, TRANSLATION_BUNDLE) } else if (identifiers.size > 1) { return tp.translate("response.jukebox.no-cheating", locale, TRANSLATION_BUNDLE) } val identifier = identifiers.first() val item = guild.player.loader.loadItem(identifier) val trackLoaded: suspend (MusicTrack) -> String = { val track = it.copy(userId = userId, mention = mention) val started = guild.player.addFirst(track, update = true) // Update metrics registry.counter(Metric.SONGS_QUEUED).increment() if (started) { tp.translate( key = "response.jukebox.play-now", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(track.title.escapedBackticks) ) } else { tp.translate( key = "response.jukebox.play-next", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(track.title.escapedBackticks) ) } } when (item.loadType) { TrackLoadType.TRACK_LOADED -> { respond(trackLoaded(item.track)) } TrackLoadType.PLAYLIST_LOADED -> { respond(tp.translate("response.jukebox.no-cheating", locale, TRANSLATION_BUNDLE)) } TrackLoadType.SEARCH_RESULT -> { if (parseResult.spotify) { respond(trackLoaded(item.tracks.first())) } else { respondMultiple(item.tracks) { trackLoaded(it) } } } TrackLoadType.NO_MATCHES -> { respond( tp.translate( key = "response.jukebox.no-matches", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(identifier) ) ) } TrackLoadType.LOAD_FAILED -> { respond( tp.translate( key = "response.jukebox.error", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(item.error ?: "Loading failed") ) ) } } log.info { message = "Playing next" context = mapOf( "identifier" to identifier, "userId" to userId, "guildId" to guild.id ) } return "" } /** * Plays later and does a fire and forget operation. Will not wait for results to return. */ suspend fun playLaterSilently( identifier: String, guild: GuildBehavior, mention: String, userId: Snowflake ) { val trackLoaded: suspend (MusicTrack) -> Unit = { val track = it.copy(userId = userId, mention = mention) guild.player.add(track, update = true, play = false) // Update metrics registry.counter(Metric.SONGS_QUEUED).increment() } val item = guild.player.loader.loadItem(identifier) when (item.loadType) { TrackLoadType.TRACK_LOADED -> { trackLoaded(item.track) } TrackLoadType.PLAYLIST_LOADED -> { // Update metrics registry.counter(Metric.SONGS_QUEUED).increment(item.tracks.size.toDouble()) guild.player.add(*item.tracks.toTypedArray(), update = true) } TrackLoadType.SEARCH_RESULT -> { trackLoaded(item.tracks.first()) } TrackLoadType.NO_MATCHES -> { log.debug { message = "Nothing found" } } TrackLoadType.LOAD_FAILED -> { log.debug { message = "Nothing found" } } } } /** * Plays a play request later in the queue. * @return response, empty string if successful. */ suspend fun playLater(request: PlayRequest): String = mutexFor(request).withLock { val (respond, respondMultiple, parseResult, guild, mention, userId, locale) = request val identifiers = parseResult.identifiers if (identifiers.isEmpty()) { log.info { message = "No identifiers found" context = mapOf( "identifiers" to identifiers, "userId" to userId, "guildId" to guild.id ) } return tp.translate("response.jukebox.not-found", locale, TRANSLATION_BUNDLE) } else if (identifiers.size > 1) { CoroutineScope(Dispatchers.IO).launch { identifiers.forEach { identifier -> // Maintain order mutexFor(request).withLock { playLaterSilently( identifier = identifier, guild = guild, mention = mention, userId = userId ) } } } delay(2000) guild.player.attemptToPlay() return tp.translate( key = "response.jukebox.playlist-unknown-later", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(identifiers.size) ) } val identifier = identifiers.first() val item = guild.player.loader.loadItem(identifier) val trackLoaded: suspend (MusicTrack) -> String = { val track = it.copy(userId = userId, mention = mention) val started = guild.player.add(track, update = true) // Update metrics registry.counter(Metric.SONGS_QUEUED) if (started) { tp.translate( key = "response.jukebox.play-now", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(track.title.escapedBackticks) ) } else { tp.translate( key = "response.jukebox.play-later", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(track.title.escapedBackticks) ) } } when (item.loadType) { TrackLoadType.TRACK_LOADED -> { respond(trackLoaded(item.track)) } TrackLoadType.PLAYLIST_LOADED -> { val tracks = item.tracks .map { it.copy(userId = userId, mention = mention) } val started = guild.player.add(*tracks.toTypedArray(), update = true) val playlistName = item.playlistInfo.name.escapedBackticks // Update metrics registry.counter(Metric.SONGS_QUEUED).increment(item.tracks.size.toDouble()) if (started) { respond( tp.translate( key = "response.jukebox.playlist-now", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf( tracks.size, playlistName ) ) ) } else { respond( tp.translate( key = "response.jukebox.playlist-later", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf( tracks.size, playlistName ) ) ) } } TrackLoadType.SEARCH_RESULT -> { if (parseResult.spotify) { respond(trackLoaded(item.tracks.first())) } else { val tracks = item.tracks .map { it.copy(userId = userId, mention = mention) } respondMultiple(tracks) { trackLoaded(it) } } } TrackLoadType.NO_MATCHES -> { respond( tp.translate( key = "response.jukebox.no-matches", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(identifier) ) ) } TrackLoadType.LOAD_FAILED -> { respond( tp.translate( key = "response.jukebox.error", bundleName = TRANSLATION_BUNDLE, locale, replacements = arrayOf(item.error ?: "Loading failed") ) ) } } log.info { message = "Playing later" context = mapOf( "identifier" to identifier, "userId" to userId, "guildId" to guild.id ) } return "" } }
0
Kotlin
0
0
8dfe5cf64aa54a94a83c3e334ed6152860d3defd
18,466
studio-helper
MIT License
shared/src/commonMain/kotlin/com/vasylt/composekmm/contacts/presentation/components/ContactPhoto.kt
osisupermoses
734,461,368
false
null
package com.vasylt.composekmm.contacts.presentation.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Person import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.vasylt.composekmm.contacts.domain.Contact import com.vasylt.composekmm.core.presentation.rememberBitmapFromBytes @Composable fun ContactPhoto( contact: Contact?, modifier: Modifier = Modifier, iconSize: Dp = 25.dp ) { val bitmap = rememberBitmapFromBytes(contact?.photoBytes) val photoModifier = modifier.clip(RoundedCornerShape(35)) if(bitmap != null) { Image( bitmap = bitmap, contentDescription = contact?.firstName, modifier = photoModifier, contentScale = ContentScale.Crop ) } else { Box( modifier = photoModifier .background(MaterialTheme.colorScheme.secondaryContainer), contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Rounded.Person, contentDescription = contact?.firstName, modifier = Modifier.size(iconSize), tint = MaterialTheme.colorScheme.onSecondaryContainer ) } } }
0
Kotlin
0
0
b1313d5ed529aedf9819c45c316d118bf313c680
1,820
contact-list-app
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Bone.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.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.Bone: ImageVector get() { if (_bone != null) { return _bone!! } _bone = Builder(name = "Bone", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.5f, 24.0f) curveToRelative(-0.93f, 0.0f, -1.83f, -0.28f, -2.6f, -0.83f) curveToRelative(-0.82f, -0.58f, -1.42f, -1.42f, -1.7f, -2.37f) curveToRelative(-0.95f, -0.29f, -1.79f, -0.89f, -2.37f, -1.7f) curveToRelative(-0.73f, -1.03f, -0.99f, -2.29f, -0.73f, -3.55f) curveToRelative(0.36f, -1.75f, 1.79f, -3.15f, 3.56f, -3.48f) curveToRelative(1.16f, -0.21f, 2.33f, 0.02f, 3.3f, 0.65f) lineToRelative(5.81f, -5.74f) curveToRelative(-0.67f, -1.0f, -0.9f, -2.18f, -0.69f, -3.34f) curveToRelative(0.32f, -1.77f, 1.72f, -3.2f, 3.48f, -3.56f) curveToRelative(1.25f, -0.26f, 2.52f, 0.0f, 3.55f, 0.73f) curveToRelative(0.82f, 0.58f, 1.42f, 1.42f, 1.7f, 2.37f) curveToRelative(0.95f, 0.29f, 1.79f, 0.89f, 2.37f, 1.7f) curveToRelative(0.73f, 1.03f, 0.99f, 2.29f, 0.73f, 3.55f) curveToRelative(-0.36f, 1.75f, -1.79f, 3.15f, -3.56f, 3.48f) curveToRelative(-1.16f, 0.21f, -2.33f, -0.02f, -3.3f, -0.65f) lineToRelative(-5.81f, 5.74f) curveToRelative(0.67f, 1.0f, 0.9f, 2.18f, 0.69f, 3.34f) curveToRelative(-0.32f, 1.77f, -1.72f, 3.2f, -3.48f, 3.56f) curveToRelative(-0.32f, 0.07f, -0.64f, 0.1f, -0.95f, 0.1f) close() moveTo(4.5f, 14.0f) curveToRelative(-0.16f, 0.0f, -0.32f, 0.01f, -0.48f, 0.04f) curveToRelative(-0.96f, 0.18f, -1.76f, 0.96f, -1.96f, 1.91f) curveToRelative(-0.15f, 0.71f, 0.0f, 1.41f, 0.4f, 1.99f) curveToRelative(0.4f, 0.57f, 1.02f, 0.94f, 1.71f, 1.03f) curveToRelative(0.45f, 0.06f, 0.8f, 0.41f, 0.86f, 0.86f) curveToRelative(0.09f, 0.68f, 0.47f, 1.3f, 1.03f, 1.7f) curveToRelative(0.57f, 0.41f, 1.28f, 0.55f, 1.99f, 0.4f) curveToRelative(0.95f, -0.2f, 1.74f, -1.0f, 1.91f, -1.96f) curveToRelative(0.12f, -0.65f, 0.0f, -1.31f, -0.36f, -1.85f) curveToRelative(-0.54f, -0.83f, -0.45f, -1.87f, 0.22f, -2.54f) lineToRelative(5.78f, -5.78f) curveToRelative(0.67f, -0.67f, 1.72f, -0.76f, 2.54f, -0.22f) curveToRelative(0.54f, 0.35f, 1.2f, 0.48f, 1.85f, 0.36f) curveToRelative(0.96f, -0.18f, 1.76f, -0.96f, 1.96f, -1.91f) curveToRelative(0.15f, -0.71f, 0.0f, -1.41f, -0.4f, -1.99f) curveToRelative(-0.4f, -0.57f, -1.02f, -0.94f, -1.71f, -1.03f) curveToRelative(-0.45f, -0.06f, -0.8f, -0.41f, -0.86f, -0.86f) curveToRelative(-0.09f, -0.68f, -0.47f, -1.3f, -1.03f, -1.7f) curveToRelative(-0.57f, -0.41f, -1.28f, -0.55f, -1.99f, -0.4f) curveToRelative(-0.95f, 0.2f, -1.74f, 1.0f, -1.91f, 1.96f) curveToRelative(-0.12f, 0.65f, 0.0f, 1.31f, 0.36f, 1.85f) curveToRelative(0.54f, 0.83f, 0.45f, 1.87f, -0.22f, 2.54f) lineToRelative(-5.78f, 5.78f) curveToRelative(-0.67f, 0.67f, -1.72f, 0.76f, -2.54f, 0.22f) curveToRelative(-0.41f, -0.27f, -0.88f, -0.4f, -1.37f, -0.4f) close() } } .build() return _bone!! } private var _bone: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,523
icons
MIT License
src/main/kotlin/fr/phast/cql/services/utils/TranslatorOptionUtil.kt
phast-fr
424,529,437
false
{"Kotlin": 69053}
/* * MIT License * * Copyright (c) 2021 PHAST * * 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 fr.phast.cql.services.utils import org.cqframework.cql.cql2elm.CqlTranslator import org.cqframework.cql.elm.execution.Library import org.hl7.cql_annotations.r1.CqlToElmInfo import org.w3c.dom.NamedNodeMap import java.util.* object TranslatorOptionUtil { /** * Gets the translator options used to generate an elm Library. * * Returns null if the translator options could not be determined. * (for example, the Library was translated without annotations) * @param library The library to extracts the options from. * @return The set of options used to translate the library. */ fun getTranslatorOptions(library: Library): EnumSet<CqlTranslator.Options>? { Objects.requireNonNull(library, "library can not be null") if (library.annotation == null || library.annotation.isEmpty()) { return null } val translatorOptions = getTranslatorOptions(library.annotation) return parseTranslatorOptions(translatorOptions) } // TODO: This has some hackery to work around type serialization that's being tracked here: // https://github.com/DBCG/cql_engine/issues/436 // Once the deserializers are fixed this should only need engine annotation types. private fun getTranslatorOptions(annotations: List<Any>): String? { for (o in annotations) { // Library mapped through the Library mapper // The Library mapper currently uses the translator types instead of the engine // types because that's all there are. if (o is CqlToElmInfo) { return o.translatorOptions } // Library loaded from JSON if (o is LinkedHashMap<*, *>) { try { val lhm = o as LinkedHashMap<String, String> val options = lhm["translatorOptions"] if (options != null) { return options } } catch (e: Exception) { continue } } // Library read from XML // ElementNsImpl is a private class internal to the JVM // that we aren't allowed to use, hence all the reflection if (o.javaClass.simpleName == "ElementNSImpl") { return try { val elementNsClass: Class<*> = o.javaClass val method = elementNsClass.getMethod("getAttributes") val nodeMap = method.invoke(o) as NamedNodeMap val attributeNode = nodeMap.getNamedItem("translatorOptions") ?: continue attributeNode.nodeValue } catch (e: Exception) { continue } } } return null } /** * Parses a string representing CQL Translator Options into an EnumSet. The string is expected * to be a comma delimited list of values from the CqlTranslator.Options enumeration. * For example "EnableListPromotion, EnableListDemotion". * @param translatorOptions the string to parse * @return the set of options */ fun parseTranslatorOptions(translatorOptions: String?): EnumSet<CqlTranslator.Options>? { if (translatorOptions == null) { return null } val optionSet = EnumSet.noneOf(CqlTranslator.Options::class.java) val options = translatorOptions.trim { it <= ' ' }.split(",".toRegex()).toTypedArray() for (option in options) { optionSet.add(CqlTranslator.Options.valueOf(option)) } return optionSet } }
0
Kotlin
0
0
b8e3da27d0b7e76eb85596ae8a217e597a074d35
4,819
cql-services
MIT License
modules/cvauto-core/src/main/kotlin/com/waicool20/cvauto/core/template/ITemplate.kt
waicool20
219,472,930
false
null
package com.waicool20.cvauto.core.template import java.awt.image.BufferedImage import java.net.URI /** * Template that will be used for matching on screen elements */ interface ITemplate { /** * URI of the source for the image that this template is based on, since this is a URI * it can represent anything from a local file to an url of image on the internet. */ val source: URI /** * Score threshold for the template, ranges from 0.0 to 1.0, 0.0 means absolutely nothing in common * while 1.0 means 100% match. */ val threshold: Double? /** * This function is in charge of loading the image into memory * * @return [BufferedImage] representation of the template */ fun load(): BufferedImage }
0
Kotlin
1
2
d5dca3dab8f664eb0c830265434793ae52fb2fe7
775
CVAuto
MIT License
app/src/test/java/pl/droidsonroids/toast/data/mapper/SpeakersMapperTest.kt
DroidsOnRoids
105,771,016
false
null
package pl.droidsonroids.toast.data.mapper import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertThat import org.junit.Test import pl.droidsonroids.toast.data.api.speaker.ApiSpeaker import pl.droidsonroids.toast.data.dto.ImageDto import pl.droidsonroids.toast.data.dto.speaker.SpeakerDto import pl.droidsonroids.toast.data.dto.speaker.SpeakerTalkDto import pl.droidsonroids.toast.testApiImage import pl.droidsonroids.toast.testApiSpeakerDetails import pl.droidsonroids.toast.testApiSpeakerTalk import pl.droidsonroids.toast.testSpeakerTalkDto class SpeakersMapperTest { @Test fun shouldMapApiSpeakerToDto() { val id = 1L val name = "name" val job = "job" val avatar = testApiImage val apiSpeaker = ApiSpeaker(id, name, job, avatar) val speakerDto = apiSpeaker.toDto() assertThat(speakerDto.id, equalTo(id)) assertThat(speakerDto.name, equalTo(name)) assertThat(speakerDto.job, equalTo(job)) assertThat(speakerDto.avatar, equalTo(avatar.toDto())) } @Test fun shouldMapApiSpeakerDetailsToDto() { val speakerDto = testApiSpeakerDetails.toDto() with(testApiSpeakerDetails) { assertThat(speakerDto.id, equalTo(id)) assertThat(speakerDto.name, equalTo(name)) assertThat(speakerDto.job, equalTo(job)) assertThat(speakerDto.bio, equalTo(bio)) assertThat(speakerDto.avatar, equalTo(avatar.toDto())) assertThat(speakerDto.talks, equalTo(talks.map { it.toDto() })) } } @Test fun shouldMapSpeakerDtoToViewModel() { val id = 1L val name = "name" val job = "job" val avatar = ImageDto("bigImageUrl", "thumbImageUrl") val onClick: (Long, String, ImageDto?) -> Unit = mock() val speakerDto = SpeakerDto(id, name, job, avatar) val speakerItemViewModel = speakerDto.toViewModel(onClick) assertThat(speakerItemViewModel.id, equalTo(id)) assertThat(speakerItemViewModel.name, equalTo(name)) assertThat(speakerItemViewModel.job, equalTo(job)) assertThat(speakerItemViewModel.avatar, equalTo(avatar)) speakerItemViewModel.onClick() verify(onClick).invoke(id, name, avatar) } @Test fun shouldMapApiSpeakerTalkToDto() { val (id, title, description, _) = testApiSpeakerTalk.toDto() assertThat(id, equalTo(testApiSpeakerTalk.id)) assertThat(title, equalTo(testApiSpeakerTalk.title)) assertThat(description, equalTo(testApiSpeakerTalk.description)) } @Test fun shouldMapSpeakerTalkDtoToViewModel() { val onReadMoreClick: (SpeakerTalkDto) -> Unit = mock() val onEventClick: (Long, ImageDto?, Long) -> Unit = mock() val viewModel = testSpeakerTalkDto.toViewModel(onReadMoreClick, onEventClick) viewModel.let { assertThat(it.id, equalTo(testSpeakerTalkDto.id)) assertThat(it.title, equalTo(testSpeakerTalkDto.title)) assertThat(it.description, equalTo(testSpeakerTalkDto.description)) it.onReadMore() verify(onReadMoreClick).invoke(eq(it.toDto())) } } @Test fun shouldMapSpeakerTalkViewModelToDto() { val speakerTalkViewModel = testSpeakerTalkDto.toViewModel(mock(), mock(), mock()) val (id, title, description, _) = speakerTalkViewModel.toDto() assertThat(id, equalTo(speakerTalkViewModel.id)) assertThat(title, equalTo(speakerTalkViewModel.title)) assertThat(description, equalTo(speakerTalkViewModel.description)) } }
0
Kotlin
5
34
7ac5cab091da171ecd1683ff76c6f3ebd8a543fe
3,761
Toast-App
Apache License 2.0
reservation/reservation-domain-api/src/main/kotlin/com/mz/reservationsystem/domain/api/timeslot/TimeSlotEventsApi.kt
michalzeman
519,548,115
false
{"Kotlin": 323513, "Shell": 799, "Dockerfile": 531}
package com.mz.reservationsystem.domain.api.timeslot import com.mz.ddd.common.api.domain.DomainEvent import com.mz.ddd.common.api.domain.Id import com.mz.ddd.common.api.domain.instantNow import com.mz.ddd.common.api.domain.newId import kotlinx.datetime.Instant import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable sealed class TimeSlotEvent : DomainEvent { abstract val aggregateId: Id } @Serializable @SerialName("time-slot-booked") data class TimeSlotBooked( override val aggregateId: Id, val booked: Boolean, val reservationId: Id, override val correlationId: Id = newId(), override val eventId: Id = newId(), override val createdAt: Instant = instantNow() ) : TimeSlotEvent() @Serializable @SerialName("time-slot-created") data class TimeSlotCreated( override val aggregateId: Id, val startTime: Instant, val endTime: Instant, val booked: Boolean, override val correlationId: Id = newId(), override val createdAt: Instant = instantNow(), override val eventId: Id = newId() ) : TimeSlotEvent() @Serializable @SerialName("time-slot-updated") data class TimeSlotUpdated( override val aggregateId: Id, val startTime: Instant, val endTime: Instant, val booked: Boolean, val valid: Boolean, val reservationId: Id? = null, override val correlationId: Id = newId(), override val createdAt: Instant = instantNow(), override val eventId: Id = newId() ) : TimeSlotEvent()
0
Kotlin
0
2
a726878fe9393c29c864b612e85eff5d3c21f268
1,504
cqrs-reservation-reactive-system
Creative Commons Attribution 4.0 International
src/main/kotlin/dev/storozhenko/familybot/services/payment/processors/PidorLimitPaymentProcessor.kt
AngryJKirk
114,262,178
false
null
package dev.storozhenko.familybot.services.payment.processors import dev.storozhenko.familybot.getLogger import dev.storozhenko.familybot.models.dictionary.Phrase import dev.storozhenko.familybot.models.shop.PreCheckOutResponse import dev.storozhenko.familybot.models.shop.ShopItem import dev.storozhenko.familybot.models.shop.ShopPayload import dev.storozhenko.familybot.models.shop.SuccessPaymentResponse import dev.storozhenko.familybot.services.payment.PaymentProcessor import dev.storozhenko.familybot.services.settings.EasyKeyValueService import dev.storozhenko.familybot.services.settings.PidorTolerance import org.springframework.stereotype.Component @Component class PidorLimitPaymentProcessor( private val easyKeyValueService: EasyKeyValueService ) : PaymentProcessor { private val log = getLogger() override fun itemType() = ShopItem.DROP_PIDOR_LIMIT override fun preCheckOut(shopPayload: ShopPayload): PreCheckOutResponse { val pidorTolerance = easyKeyValueService.get(PidorTolerance, shopPayload.chatKey()) log.info("Doing pre checkout, shopPayload=$shopPayload, result is $pidorTolerance") return if (pidorTolerance == null || pidorTolerance == 0L) { PreCheckOutResponse.Error(Phrase.DROP_PIDOR_LIMIT_INVALID) } else { PreCheckOutResponse.Success() } } override fun processSuccess(shopPayload: ShopPayload): SuccessPaymentResponse { easyKeyValueService.remove(PidorTolerance, shopPayload.chatKey()) log.info("Removed pidor limit for $shopPayload") return SuccessPaymentResponse(Phrase.DROP_PIDOR_LIMIT_DONE) } }
0
Kotlin
4
97
aff071c72503ffb9ad276fb9cc33d8408196795d
1,647
familybot
Apache License 2.0
widget/src/main/java/com/angcyo/widget/span/IClickableSpan.kt
angcyo
229,037,615
false
{"Kotlin": 6722659, "JavaScript": 5194}
package com.angcyo.widget.span import android.view.MotionEvent import android.view.View import com.angcyo.library.L import com.angcyo.library.ex.actionToString /** * * Email:<EMAIL> * @author angcyo * @date 2020/01/11 */ interface IClickableSpan { fun isCanClick(): Boolean { return true } fun onClickSpan(view: View, span: IClickableSpan) { L.i(span) } fun onTouchEvent(view: View, span: IClickableSpan, event: MotionEvent) { L.v("$span ${event.actionToString()}") } }
0
Kotlin
6
5
10ad5753c3ff675d7f7513db5d98665bcf6f7418
527
UICore
MIT License