path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/tanasi/streamflix/adapters/viewholders/SeasonViewHolder.kt
stantanasi
511,319,545
false
null
package com.tanasi.streamflix.adapters.viewholders import android.view.animation.AnimationUtils import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import androidx.viewbinding.ViewBinding import com.bumptech.glide.Glide import com.tanasi.streamflix.R import com.tanasi.streamflix.databinding.ItemSeasonBinding import com.tanasi.streamflix.fragments.tv_show.TvShowFragmentDirections import com.tanasi.streamflix.models.Season class SeasonViewHolder( private val _binding: ViewBinding ) : RecyclerView.ViewHolder( _binding.root ) { private val context = itemView.context private lateinit var season: Season fun bind(season: Season) { this.season = season when (_binding) { is ItemSeasonBinding -> displayItem(_binding) } } private fun displayItem(binding: ItemSeasonBinding) { binding.root.apply { setOnClickListener { findNavController().navigate( TvShowFragmentDirections.actionTvShowToSeason( tvShowId = season.tvShow?.id ?: "", tvShowTitle = season.tvShow?.title ?: "", tvShowPoster = season.tvShow?.poster, tvShowBanner = season.tvShow?.banner, seasonId = season.id, seasonNumber = season.number, seasonTitle = season.title, ) ) } setOnFocusChangeListener { _, hasFocus -> val animation = when { hasFocus -> AnimationUtils.loadAnimation(context, R.anim.zoom_in) else -> AnimationUtils.loadAnimation(context, R.anim.zoom_out) } binding.root.startAnimation(animation) animation.fillAfter = true } } binding.ivSeasonPoster.apply { clipToOutline = true Glide.with(context) .load(season.poster) .centerCrop() .into(this) } binding.tvSeasonTitle.text = season.title } }
21
Kotlin
14
93
c9255fe9ee2ef3ed8bfbeef567950f1a63a51752
2,190
streamflix
Apache License 2.0
SafeDriveApp/app/src/main/java/com/example/safedrive/components/FaceAnalyzer.kt
Android-development-group-13
771,413,371
false
{"Kotlin": 102916}
package com.example.safedrive.components import android.content.Context import android.media.MediaPlayer import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.util.Log import android.widget.Toast import androidx.annotation.OptIn import androidx.annotation.RequiresApi import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.example.safedrive.R import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.FaceDetection import com.google.mlkit.vision.face.FaceDetectorOptions class FaceAnalyzer(private val context: Context) : ImageAnalysis.Analyzer { private val TAG = "FaceAnalyzer" private var leftEyeClosedStartTime: Long = 0 private var rightEyeClosedStartTime: Long = 0 private val realTimeOpts = FaceDetectorOptions.Builder() .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL) .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_NONE) .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL) .setMinFaceSize(0.20f) .enableTracking() .build() private val detector = FaceDetection.getClient(realTimeOpts) @RequiresApi(Build.VERSION_CODES.O) @OptIn(ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image mediaImage?.let { val inputImage = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) detector.process(inputImage) .addOnSuccessListener { faces -> if (faces.isNotEmpty()) { Log.d(TAG, "Face detected!") } faces.forEach { face -> val leftEyeOpenProbability = face.leftEyeOpenProbability val rightEyeOpenProbability = face.rightEyeOpenProbability if (leftEyeOpenProbability != null && rightEyeOpenProbability != null) { // Check for closed eyes if (leftEyeOpenProbability <= 0.5) { if (leftEyeClosedStartTime == 0L) { leftEyeClosedStartTime = System.currentTimeMillis() } else { val duration = System.currentTimeMillis() - leftEyeClosedStartTime if (duration >= 1000) { Log.d(TAG, "Left eye closed for 2 seconds") triggerAlerts() } } } else { leftEyeClosedStartTime = 0 } if (rightEyeOpenProbability <= 0.5) { if (rightEyeClosedStartTime == 0L) { rightEyeClosedStartTime = System.currentTimeMillis() } else { val duration = System.currentTimeMillis() - rightEyeClosedStartTime if (duration >= 1500) { Log.d(TAG, "Right eye closed for 2 seconds") triggerAlerts() } } } else { rightEyeClosedStartTime = 0 } } } } .addOnFailureListener { e -> Log.e(TAG, "Face detection failed: ${e.message}") } .addOnCompleteListener { imageProxy.close() } } } @RequiresApi(Build.VERSION_CODES.O) private fun triggerAlerts() { // Vibrate the device val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? vibrator?.let { if (it.hasVibrator()) { val vibrationEffect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE) it.vibrate(vibrationEffect) } } val mediaPlayer = MediaPlayer.create(context, R.raw.mixkit_bell) mediaPlayer.start() // Show a pop-up // Here you can implement your logic to show a pop-up // For example, using Toast or Snackbar Toast.makeText(context, "Alert: You are falling asleep!", Toast.LENGTH_SHORT).show() } }
3
Kotlin
0
0
6a748e78d14b24e001c37eef41705f3fa3c1799e
4,824
safedrive
MIT License
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/domain/model/account/Account.kt
ryanw-mobile
794,752,204
false
{"Kotlin": 1440473, "Ruby": 2466, "Swift": 693}
/* * Copyright (c) 2024. RW MobiMedia UK Limited * * Contributions made by other developers remain the property of their respective authors but are licensed * to RW MobiMedia UK Limited and others under the same licence terms as the main project, as outlined in * the LICENSE file. * * RW MobiMedia UK Limited reserves the exclusive right to distribute this application on app stores. * Reuse of this source code, with or without modifications, requires proper attribution to * RW MobiMedia UK Limited. Commercial distribution of this code or its derivatives without prior written * permission from RW MobiMedia UK Limited is prohibited. * * Please refer to the LICENSE file for the full terms and conditions. */ package com.rwmobi.kunigami.domain.model.account import androidx.compose.runtime.Immutable import androidx.compose.ui.util.fastAny import kotlinx.datetime.Instant @Immutable data class Account( val accountNumber: String, val fullAddress: String?, val postcode: String?, val movedInAt: Instant?, val movedOutAt: Instant?, val electricityMeterPoints: List<ElectricityMeterPoint>, ) { /** * Pick the active or last tariff code */ fun getDefaultLatestTariffCode(): String? { return electricityMeterPoints.getOrNull(0)?.getLatestAgreement()?.tariffCode } fun getDefaultLatestTariffCode(mpan: String?): String? { if (mpan == null) return null return electricityMeterPoints.find { it.mpan == mpan }?.getLatestAgreement()?.tariffCode } fun getDefaultMpan(): String? { return electricityMeterPoints.getOrNull(0)?.mpan } fun containsMpan(mpan: String?): Boolean { return electricityMeterPoints.any { it.mpan == mpan } } fun getElectricityMeterPoint(mpan: String): ElectricityMeterPoint? { return electricityMeterPoints.firstOrNull { it.mpan == mpan } } fun getElectricityMeterPoint(mpan: String, meterSerialNumber: String): ElectricityMeterPoint? { return electricityMeterPoints.firstOrNull { it.mpan == mpan && it.meters.fastAny { meter -> meter.serialNumber == meterSerialNumber } } } fun getDefaultMeterSerialNumber(): String? { return electricityMeterPoints.getOrNull(0) ?.meters?.getOrNull(0)?.serialNumber } fun containsMeterSerialNumber(mpan: String?, meterSerialNumber: String?): Boolean { if (mpan == null || meterSerialNumber == null) { return false } return electricityMeterPoints.firstOrNull { it.mpan == mpan && it.meters.fastAny { meter -> meter.serialNumber == meterSerialNumber } } != null } /*** * Returns true when the account has at least one electricity meter. * Does not mean it is the meter user prefers */ fun hasValidMeter(): Boolean { return electricityMeterPoints.isNotEmpty() && electricityMeterPoints[0].meters.isNotEmpty() } }
16
Kotlin
10
145
7f278204448e9c59ca028e520e9e5aca97fa1e13
3,103
OctoMeter
Creative Commons Attribution 4.0 International
app/src/main/java/com/ubuntuyouiwe/nexus/domain/repository/AuthRepository.kt
ubuntuyiw
670,182,275
false
null
package com.ubuntuyouiwe.nexus.domain.repository import android.content.Intent import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseUser import com.ubuntuyouiwe.nexus.domain.model.User import com.ubuntuyouiwe.nexus.domain.model.UserCredentials import com.ubuntuyouiwe.nexus.domain.model.roles.PurposeSelection import com.ubuntuyouiwe.nexus.domain.model.user_messaging_data.UserMessagingData import kotlinx.coroutines.flow.Flow interface AuthRepository { suspend fun sendPasswordResetEmail(email: String) suspend fun signUp(userCredentials: UserCredentials) suspend fun signIn(userCredentials: UserCredentials): User? suspend fun loginUserDatabase(uid: String?) suspend fun getUserMessagingData(id: String): Flow<UserMessagingData?> suspend fun logOut() suspend fun googleSignIn(data: Intent): User? fun googleSignInIntent(): Intent fun listenUserOnlineStatus(): Flow<User?> suspend fun getUserListener(id: String): Flow<User?> suspend fun updateDisplayName(name: String) suspend fun updatePurposeSelection(purposeSelection: PurposeSelection) suspend fun updateSystemMessage(systemMessage: String) suspend fun changePassword(password: String) suspend fun setSystemLanguage(code: String) suspend fun saveTokenToDatabase(onNewToken: String?) suspend fun removeTokenFromDatabase(tokenToRemove: String) suspend fun getDeviceToken(): String? }
0
null
0
9
4edd0040e8983f79eca4cce71ca3e60cc4ee31b7
1,455
Nexus
Apache License 2.0
adaptive-lib-auth/src/commonMain/kotlin/fun/adaptive/auth/model/AuthenticationResult.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2350876, "Java": 25297, "HTML": 7875, "JavaScript": 3880, "Shell": 687}
/* * Copyright © 2020-2024, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package `fun`.adaptive.auth.model import `fun`.adaptive.wireformat.builtin.EnumWireFormat enum class AuthenticationResult { UnknownPrincipal, UnknownSession, InvalidSecurityCode, NoCredential, NotActivated, Locked, Expired, Anonymized, InvalidCredentials, Success, SecondFactorSuccess; companion object : EnumWireFormat<AuthenticationResult>(entries) { override val wireFormatName: String get() = "fun.adaptive.auth.model.AuthenticationResult" } }
35
Kotlin
0
3
8716e7298c97a6b128f7a8c4817277f2de896e8c
644
adaptive
Apache License 2.0
src/main/kotlin/com/matt/belisle/commonmark/ast/inlineElements/AutoLink.kt
matt-belisle
198,909,271
false
null
package com.matt.belisle.commonmark.ast.inlineElements import com.matt.belisle.commonmark.parser.inlineParsingUtil.EntityReplacement import com.matt.belisle.commonmark.parser.inlineParsingUtil.Escaping //The given regex from the spec does not perform well in Java, this was found @ https://emailregex.com/ and enforces the RFC 5322 standard val EMAIL_REGEX: Regex = Regex("""[a-zA-Z0-9.!#${'$'}%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*"""); class AutoLink(private val str: String) : Inline(){ private val type: String = if(EMAIL_REGEX.matchEntire(str) != null) "mailto:" else "" override fun render(entities: Boolean): String { val replacedEntities = EntityReplacement.inspect(str, true) // render the entities val rendered = renderEntities(replacedEntities) //TODO encode the link url... 599 enforces but with the way a URI is defined this is difficult val encoded = if(type == "") Escaping.percentEncodeUrl(rendered) else rendered // this will need entity replacement obviously return "<a href=\"$type${encoded}\">$rendered</a>" } override fun renderTextContentOnly(entities: Boolean): String { return InlineString(str).render(entities) } }
0
Kotlin
0
2
e41623f64f3c5c24e40c0626209236b54957ba4e
1,306
CommonMarK
MIT License
j2k/tests/testData/ast/ifStatement/ifStatementWithoutElse.ide.kt
craastad
18,462,025
false
{"Markdown": 18, "XML": 405, "Ant Build System": 23, "Ignore List": 7, "Maven POM": 34, "Kotlin": 10194, "Java": 3675, "CSS": 10, "Shell": 6, "Batchfile": 6, "Java Properties": 9, "Gradle": 61, "INI": 6, "JavaScript": 42, "HTML": 77, "Text": 875, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "JAR Manifest": 1, "Protocol Buffer": 2}
if (1 > 0) { val n = 1 return n }
1
null
1
1
f41f48b1124e2f162295718850426193ab55f43f
33
kotlin
Apache License 2.0
domene/src/main/kotlin/no/nav/tiltakspenger/saksbehandling/domene/vilkår/tiltakdeltagelse/TiltakDeltagelseEx.kt
navikt
487,246,438
false
{"Kotlin": 634615, "Shell": 1309, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.saksbehandling.domene.vilkår.tiltakdeltagelse import no.nav.tiltakspenger.saksbehandling.domene.tiltak.Tiltak import java.time.LocalDateTime fun Tiltak.tilRegisterSaksopplysning(): TiltakDeltagelseSaksopplysning.Register = TiltakDeltagelseSaksopplysning.Register( tiltakNavn = gjennomføring.typeNavn, deltagelsePeriode = this.deltakelsesperiode, kilde = kilde, status = deltakelseStatus, girRett = gjennomføring.rettPåTiltakspenger, tidsstempel = LocalDateTime.now(), )
6
Kotlin
0
1
953198d54cd370b865f6ebe635a29c9e42cb817b
557
tiltakspenger-vedtak
MIT License
src/main/kotlin/com/vk/kphpstorm/exphptype/ExPhpTypeInstance.kt
VKCOM
284,436,466
false
{"Kotlin": 362747, "HTML": 55541, "CSS": 8147}
package com.vk.kphpstorm.exphptype import com.intellij.openapi.project.Project import com.jetbrains.php.PhpClassHierarchyUtils import com.jetbrains.php.PhpIndex import com.jetbrains.php.codeInsight.PhpCodeInsightUtil import com.jetbrains.php.lang.psi.elements.PhpPsiElement import com.jetbrains.php.lang.psi.resolve.types.PhpType /** * 'A', '\asdf\name' — are instances (not primitives!) */ class ExPhpTypeInstance(val fqn: String) : ExPhpType { override fun toString() = fqn override fun toHumanReadable(expr: PhpPsiElement) = if (fqn.startsWith('\\')) PhpCodeInsightUtil.createQualifiedName(PhpCodeInsightUtil.findScopeForUseOperator(expr)!!, fqn) else fqn override fun toPhpType(): PhpType { return PhpType().add(fqn) } override fun getSubkeyByIndex(indexKey: String): ExPhpType? { return null } override fun instantiateTemplate(nameMap: Map<String, ExPhpType>): ExPhpType { return nameMap[fqn] ?: this } override fun isAssignableFrom(rhs: ExPhpType, project: Project): Boolean = when (rhs) { is ExPhpTypeAny -> true is ExPhpTypePipe -> rhs.isAssignableTo(this, project) is ExPhpTypeNullable -> isAssignableFrom(rhs.inner, project) is ExPhpTypePrimitive -> rhs === ExPhpType.NULL || rhs === ExPhpType.OBJECT // rhs can be assigned if: rhs == lhs or rhs is child of lhs (no matter, lhs is interface or class) is ExPhpTypeInstance -> rhs.fqn == fqn || run { val phpIndex = PhpIndex.getInstance(project) val lhsClass = phpIndex.getAnyByFQN(fqn).firstOrNull() ?: return false var rhsIsChild = false phpIndex.getAnyByFQN(rhs.fqn).forEach { rhsClass -> PhpClassHierarchyUtils.processSuperWithoutMixins(rhsClass, true, true) { clazz -> if (PhpClassHierarchyUtils.classesEqual(lhsClass, clazz)) rhsIsChild = true !rhsIsChild } } rhsIsChild } else -> false } }
15
Kotlin
4
41
94322cbd0e795d4e70a4067c5e6c4b777706b3fa
2,116
kphpstorm
MIT License
app/src/main/java/top/xjunz/tasker/task/editor/AppletReferenceEditor.kt
xjunz
651,527,105
false
null
/* * Copyright (c) 2022 xjunz. All rights reserved. */ package top.xjunz.tasker.task.editor import android.util.ArrayMap import top.xjunz.tasker.engine.applet.base.Applet import top.xjunz.tasker.task.applet.option.descriptor.ArgumentDescriptor /** * @author xjunz 2022/11/28 */ class AppletReferenceEditor(private val revocable: Boolean = true) { private data class AppletArg(val applet: Applet, val which: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AppletArg if (applet != other.applet) return false if (which != other.which) return false return true } override fun hashCode(): Int { var result = applet.hashCode() result = 31 * result + which return result } } private val referenceRevocations = ArrayMap<AppletArg, () -> Unit>() private val referentRevocations = ArrayMap<AppletArg, () -> Unit>() private val varargReferentsRevocations = ArrayMap<Applet, () -> Unit>() private fun MutableMap<AppletArg, () -> Unit>.putIfNeeded( applet: Applet, which: Int, revocation: () -> Unit ) { if (revocable) { putIfAbsent(AppletArg(applet, which), revocation) } } private fun Map<Int, String>.putIfDistinct(key: Int, value: String): Boolean { if (this[key] == value) return false (this as MutableMap<Int, String>)[key] = value return true } private fun Applet.rawSetReferent(whichRet: Int, id: String?): Boolean { return if (id.isNullOrEmpty()) { rawRemoveReferent(whichRet) } else { if (referents === emptyMap<Int, String>()) { referents = ArrayMap() } referents.putIfDistinct(whichRet, id) } } private fun Applet.rawSetReference(whichArg: Int, ref: String?): Boolean { return if (ref.isNullOrEmpty()) { rawRemoveReference(whichArg) } else { if (references === emptyMap<Int, String>()) { references = ArrayMap() } references.putIfDistinct(whichArg, ref) } } private fun Applet.rawRemoveReference(which: Int): Boolean { if (references.isEmpty()) return false (references as MutableMap).remove(which) if (references.isEmpty()) references = emptyMap() return true } private fun Applet.rawRemoveReferent(which: Int): Boolean { if (referents.isEmpty()) return false (referents as MutableMap).remove(which) if (referents.isEmpty()) referents = emptyMap() return true } fun setValue(applet: Applet, whichArg: Int, value: Any?) { val prevValue = applet.value val prevReferent = applet.references[whichArg] applet.value = value if (applet.rawRemoveReference(whichArg)) { referenceRevocations.putIfNeeded(applet, whichArg) { applet.rawSetReference(whichArg, prevReferent) applet.value = prevValue } } } fun setVarargReferences(applet: Applet, referentNames: List<String>) { val prevReferences = applet.references val map = ArrayMap<Int, String>() var changed = false referentNames.forEachIndexed { index, s -> if (map[index] != s) { map[index] = s changed = true } } if (changed) { applet.references = map if (revocable) { varargReferentsRevocations.putIfAbsent(applet) { applet.references = prevReferences } } } } fun setReference(applet: Applet, arg: ArgumentDescriptor?, whichArg: Int, referent: String?) { val prevReferent = applet.references[whichArg] val prevValue = applet.value if (applet.rawSetReference(whichArg, referent) && arg != null) { // Clear its value once the arg is set to a reference if (!arg.isReferenceOnly) { applet.value = null } referenceRevocations.putIfNeeded(applet, whichArg) { applet.rawSetReference(whichArg, prevReferent) applet.value = prevValue } } } fun renameReference(applet: Applet, whichArg: Int, newReferent: String?) { val prevReferent = applet.references[whichArg] if (applet.rawSetReference(whichArg, newReferent)) { referenceRevocations.putIfNeeded(applet, whichArg) { applet.rawSetReference(whichArg, prevReferent) } } } fun setReferent(applet: Applet, whichResult: Int, referent: String?) { val prevReferent = applet.referents[whichResult] if (applet.rawSetReferent(whichResult, referent)) { referentRevocations.putIfNeeded(applet, whichResult) { applet.rawSetReferent(whichResult, prevReferent) } } } fun getReferenceChangedApplets(): Set<Applet> { return referenceRevocations.keys.map { it.applet }.toSet() } fun getReferentChangedApplets(): Set<Applet> { return referentRevocations.keys.map { it.applet }.toSet() } fun reset() { referenceRevocations.clear() referentRevocations.clear() varargReferentsRevocations.clear() } fun revokeAll() { referenceRevocations.forEach { (_, u) -> u.invoke() } referentRevocations.forEach { (_, u) -> u.invoke() } varargReferentsRevocations.forEach { (_, u) -> u.invoke() } reset() } }
0
Kotlin
0
2
e8eb03801cc28fcf62a4a25e9054c1a79101b728
5,877
AutoTask
Apache License 2.0
sources/app-kotlin/app/src/main/java/com/platanedev/platane/MainActivity.kt
PlataneDev
592,831,395
false
null
package com.platanedev.platane import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsControllerCompat import com.platanedev.platane.composable.NoRippleInteractionSource import com.platanedev.platane.composable.bounceClick import com.platanedev.platane.ui.theme.PlataneTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PlataneTheme { WindowCompat.setDecorFitsSystemWindows(getWindow(), false) WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars = false MainPage() } } } } @Composable fun MainPage() { val interactionSource = remember { MutableInteractionSource() } val context = LocalContext.current Box(modifier = Modifier .fillMaxSize() ){ Image(painter = painterResource(id = R.drawable.background_green), contentDescription = null, contentScale = ContentScale.FillHeight, modifier = Modifier.fillMaxSize()) Column( modifier = Modifier .fillMaxSize() .padding(vertical = 100.dp, horizontal = 10.dp), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ){ Image( painter = painterResource(id = R.drawable.logo_title_white), contentDescription = null ) Button(onClick = { context.startActivity(Intent(context, LoginActivity::class.java)) }, interactionSource = NoRippleInteractionSource(), modifier = Modifier .width(270.dp) .bounceClick() ) { Text(text = "Sign in", color= colorResource(id = R.color.green_light)) } Button(onClick = { context.startActivity(Intent(context, RegisterActivity::class.java))}, colors = ButtonDefaults.buttonColors(backgroundColor = Color.Transparent), elevation = null, modifier = Modifier .bounceClick(), interactionSource = NoRippleInteractionSource() ) { Text(text = "Sign up", color= colorResource(id = R.color.white)) } } } } @Preview(showBackground = true) @Composable fun MainPreview() { PlataneTheme { MainPage() } }
0
Kotlin
0
7
9eab3301891cae100d0ddd94b273a10d37efbfde
3,370
platane
MIT License
app/src/main/java/uk/co/sentinelweb/cuer/app/util/chromecast/CastDialogWrapper.kt
sentinelweb
220,796,368
false
{"Kotlin": 2627352, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
package uk.co.sentinelweb.cuer.app.util.chromecast import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentTransaction import androidx.mediarouter.app.MediaRouteChooserDialogFragment import androidx.mediarouter.app.MediaRouteDialogFactory import com.google.android.gms.cast.framework.CastContext import uk.co.sentinelweb.cuer.app.util.chromecast.listener.ChromecastContract class CastDialogWrapper( private val activity: FragmentActivity, private val chromeCastWrapper: ChromeCastWrapper ) : ChromecastContract.DialogWrapper { private val castContext: CastContext get() = chromeCastWrapper.getCastContext() override fun showRouteSelector() { castContext.mergedSelector.apply { val f: MediaRouteChooserDialogFragment = MediaRouteDialogFactory.getDefault().onCreateChooserDialogFragment() f.routeSelector = this //f.setUseDynamicGroup(false) val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction() transaction.add(f, CHOOSER_FRAGMENT_TAG) transaction.commitAllowingStateLoss() } } companion object { // reuses library tags in case media route button is somehow accessed (might not be possible) private const val CHOOSER_FRAGMENT_TAG = "android.support.v7.mediarouter:MediaRouteChooserDialogFragment" private const val CONTROLLER_FRAGMENT_TAG = "android.support.v7.mediarouter:MediaRouteControllerDialogFragment" } }
94
Kotlin
0
2
f74e211570fe3985ba45848b228e91a3a8593788
1,543
cuer
Apache License 2.0
wasabi-core/src/main/kotlin/org/wasabifx/wasabi/interceptors/Interceptor.kt
wasabifx
9,009,498
false
null
package org.wasabifx.wasabi.interceptors import org.wasabifx.wasabi.protocol.http.Response import org.wasabifx.wasabi.protocol.http.Request interface Interceptor { fun intercept(request: Request, response: Response): Boolean }
20
Kotlin
58
510
9148843ca0aa9c4f79ca1228df8f36d590d0a24b
232
wasabi
Apache License 2.0
presentation/src/main/java/com/kkkk/presentation/main/record/RecordFragment.kt
KKKK-Stempo
815,756,494
false
{"Kotlin": 162785}
package com.kkkk.presentation.main.record import android.annotation.SuppressLint import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.formatter.ValueFormatter import com.kkkk.core.base.BaseFragment import com.kkkk.core.extension.colorOf import com.kkkk.core.extension.setStatusBarColor import com.kkkk.core.extension.stringOf import com.kkkk.core.extension.toast import com.kkkk.core.state.UiState import com.kkkk.stempo.presentation.R import com.kkkk.stempo.presentation.databinding.FragmentRecordBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @AndroidEntryPoint class RecordFragment : BaseFragment<FragmentRecordBinding>(R.layout.fragment_record) { private val viewModel by activityViewModels<RecordViewModel>() override fun onViewCreated( view: View, savedInstanceState: Bundle?, ) { super.onViewCreated(view, savedInstanceState) binding.vm = viewModel observeReportMonth() observeChartEntry() observeStatistics() setStatusBarColor(R.color.white) viewModel.setGraphWithDate() } private fun observeReportMonth() { viewModel.reportMonth.observe(viewLifecycleOwner) { month -> binding.tvReportMonth.text = when (month) { 1 -> stringOf(R.string.report_tv_month_1) 3 -> stringOf(R.string.report_tv_month_3) 6 -> stringOf(R.string.report_tv_month_6) else -> return@observe } } } private fun observeChartEntry() { viewModel.chartEntry.flowWithLifecycle(lifecycle).onEach { state -> when (state) { is UiState.Success -> { setLoadingView(false) binding.ivChartEmpty.isVisible = false binding.chartReport.apply { data = LineData(LineDataSet(state.data, CHART_RECORD).setDataSettings()) invalidate() } setGraphSettings() } is UiState.Failure -> { setLoadingView(false) binding.ivChartEmpty.isVisible = true toast(stringOf(R.string.error_msg)) } is UiState.Loading -> setLoadingView(true) is UiState.Empty -> { setLoadingView(false) binding.ivChartEmpty.isVisible = true } } }.launchIn(lifecycleScope) } @SuppressLint("SetTextI18n") private fun observeStatistics() { viewModel.statistics.flowWithLifecycle(lifecycle).onEach { state -> when (state) { is UiState.Success -> { binding.tvStatisticsToday.text = getString(R.string.statistics_counter, state.data.todayWalkTrainingCount) binding.tvStatisticsWeek.text = getString(R.string.statistics_counter, state.data.weeklyWalkTrainingCount) binding.tvStatisticsSequence.text = getString( R.string.statistics_counter, state.data.consecutiveWalkTrainingDays ) } is UiState.Failure -> { toast(stringOf(R.string.error_msg)) } is UiState.Loading -> { } is UiState.Empty -> {} } }.launchIn(lifecycleScope) } private fun setLoadingView(isLoading: Boolean) { binding.layoutLoading.isVisible = isLoading if (isLoading) { binding.layoutChart.visibility = View.INVISIBLE setStatusBarColor(R.color.transparent_50) } else { binding.layoutChart.visibility = View.VISIBLE setStatusBarColor(R.color.white) } } private fun LineDataSet.setDataSettings(): LineDataSet { this.apply { color = colorOf(R.color.purple_50) circleRadius = 8f setCircleColor(colorOf(R.color.purple_50)) setDrawFilled(true) setDrawValues(false) lineWidth = 4F setDrawCircleHole(false) fillColor = colorOf(R.color.purple_10) fillAlpha = 255 isHighlightEnabled = false mode = LineDataSet.Mode.LINEAR } return this } private fun setGraphSettings() { binding.chartReport.apply { setXAxisSettings(this) setYAxisSettings(this) setCommonSettings(this) } } private fun setXAxisSettings(chart: LineChart) { chart.xAxis.apply { valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String? { return if (value.toInt() in viewModel.dateList.indices) { viewModel.dateList[value.toInt()] } else { "" } } } position = XAxis.XAxisPosition.BOTTOM granularity = 1f axisMinimum = 0.7f axisMaximum = viewModel.dateList.size - 0.8f setDrawGridLines(false) setDrawAxisLine(false) textSize = 15f textColor = colorOf(R.color.gray_600) } } private fun setYAxisSettings(chart: LineChart) { chart.axisLeft.apply { isEnabled = false axisMaximum = 100f } chart.axisRight.isEnabled = false } private fun setCommonSettings(chart: LineChart) { chart.apply { legend.isEnabled = false description.isEnabled = false setScaleEnabled(false) setDragEnabled(false) setExtraOffsets(0f, 0f, 0f, 20f) } } companion object { private const val CHART_RECORD = "CHART_RECORD" } }
0
Kotlin
0
6
3a4488fcc196e0df2c6106f7273b4ec7f2e699a1
6,501
stempo-android
MIT License
TwoPage/src/androidTest/java/com/microsoft/device/display/samples/twopage/PageSwipeTest.kt
microsoft
329,091,156
false
null
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.device.display.samples.twopage import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeLeft import androidx.compose.ui.test.swipeRight import com.microsoft.device.dualscreen.testing.compose.foldableRuleChain import com.microsoft.device.dualscreen.testing.compose.getString import com.microsoft.device.dualscreen.testing.filters.MockFoldingFeature import com.microsoft.device.dualscreen.testing.filters.SingleScreenTest import com.microsoft.device.dualscreen.testing.rules.FoldableTestRule import com.microsoft.device.dualscreen.testing.runner.FoldableJUnit4ClassRunner import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import org.junit.runner.RunWith @RunWith(FoldableJUnit4ClassRunner::class) class PageSwipeTest { private val composeTestRule = createAndroidComposeRule<MainActivity>() private val foldableTestRule = FoldableTestRule() @get:Rule val testRule: TestRule = foldableRuleChain(composeTestRule, foldableTestRule) /** * Tests that the pages swipe only between 1 and 4 in single screen mode */ @Test @SingleScreenTest fun app_singlescreen_pagesSwipeWithinLimits() { swipeOnePageAtATime() } /** * Tests that the pages swipe only between 1 and 4 when a horizontal fold is present */ @Test @MockFoldingFeature(orientation = MockFoldingFeature.FoldingFeatureOrientation.HORIZONTAL) fun app_horizontalFold_pagesSwipeWithinLimits() { swipeOnePageAtATime() } /** * Swipes forward through all four pages and asserts that each page is visible at the correct time, * then swipes backwards through all the pages again and asserts that each page is visible at the correct time */ private fun swipeOnePageAtATime() { val pageTags = listOf(R.string.page1_tag, R.string.page2_tag, R.string.page3_tag, R.string.page4_tag) // Swipe forwards for (page in 0..3) { // Assert current page is visible composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() // Swipe to next page composeTestRule.onRoot().performTouchInput { swipeLeft() } // Assert current page is no longer visible (unless on the last page) when (page) { 3 -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() else -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsNotDisplayed() } } // Swipe backwards for (page in 3 downTo 0) { // Assert current page is visible composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() // Swipe to previous page composeTestRule.onRoot().performTouchInput { swipeRight() } // Assert current page is no longer visible (unless on the first page) when (page) { 0 -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() else -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsNotDisplayed() } } } /** * Tests that the three dual-screen page pairs ([1,2], [2,3], and [3,4]) only swipe between each other when * a vertical fold is present */ @Test @MockFoldingFeature(orientation = MockFoldingFeature.FoldingFeatureOrientation.VERTICAL) fun app_verticalFold_pagesSwipeWithinLimits() { val pageTags = listOf(R.string.page1_tag, R.string.page2_tag, R.string.page3_tag, R.string.page4_tag) // Swipe forwards for (page in 0..2) { // Assert current pages are visible composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page + 1])).assertIsDisplayed() // Swipe to next page composeTestRule.onRoot().performTouchInput { swipeLeft() } // Assert current page is no longer visible (unless on the last page) when (page) { 2 -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() else -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsNotDisplayed() } } // Swipe backwards for (page in 3 downTo 1) { // Assert current pages are visible composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page - 1])).assertIsDisplayed() // Swipe to previous page composeTestRule.onRoot().performTouchInput { swipeRight() } // Assert current page is no longer visible (unless on the first page) when (page) { 1 -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsDisplayed() else -> composeTestRule.onNodeWithTag(composeTestRule.getString(pageTags[page])).assertIsNotDisplayed() } } } }
2
Kotlin
16
59
1ae8ef33490227dbd311fdc261d3cf270ccb2853
5,850
surface-duo-compose-samples
MIT License
src/commonMain/kotlin/net/kikuchy/cdpclient/domain/Audits.kt
kikuchy
338,851,036
false
null
package net.kikuchy.cdpclient.domain import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.map import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.encodeToJsonElement import net.kikuchy.cdpclient.CDPClient import net.kikuchy.cdpclient.Domain public val CDPClient.audits: Audits get() = getGeneratedDomain() ?: cacheGeneratedDomain(Audits(this)) /** * Audits domain allows investigation of page violations and possible improvements. */ public class Audits( private val client: CDPClient ) : Domain { @ExperimentalCoroutinesApi @ExperimentalSerializationApi public val issueAdded: Flow<IssueAddedParameter> = client .events .filter { it.method == "issueAdded" } .map { it.params } .filterNotNull() .map { Json.decodeFromJsonElement(it) } /** * Returns the response body and size if it were re-encoded with the specified settings. Only * applies to images. */ @ExperimentalCoroutinesApi @ExperimentalSerializationApi public suspend fun getEncodedResponse(args: GetEncodedResponseParameter): GetEncodedResponseReturn { val parameter = Json { encodeDefaults = false }.encodeToJsonElement(args) val result = client.callCommand("Audits.getEncodedResponse", parameter) return result!!.let { Json.decodeFromJsonElement(it) } } /** * Returns the response body and size if it were re-encoded with the specified settings. Only * applies to images. */ @ExperimentalCoroutinesApi @ExperimentalSerializationApi public suspend fun getEncodedResponse( requestId: String, encoding: String, quality: Double? = null, sizeOnly: Boolean? = null ): GetEncodedResponseReturn { val parameter = GetEncodedResponseParameter(requestId = requestId, encoding = encoding, quality = quality, sizeOnly = sizeOnly) return getEncodedResponse(parameter) } /** * Disables issues domain, prevents further issues from being reported to the client. */ @ExperimentalCoroutinesApi @ExperimentalSerializationApi public suspend fun disable(): Unit { val parameter = null client.callCommand("Audits.disable", parameter) } /** * Enables issues domain, sends the issues collected so far to the client by means of the * `issueAdded` event. */ @ExperimentalCoroutinesApi @ExperimentalSerializationApi public suspend fun enable(): Unit { val parameter = null client.callCommand("Audits.enable", parameter) } /** * Runs the contrast check for the target page. Found issues are reported * using Audits.issueAdded event. */ @ExperimentalCoroutinesApi @ExperimentalSerializationApi public suspend fun checkContrast(): Unit { val parameter = null client.callCommand("Audits.checkContrast", parameter) } /** * Information about a cookie that is affected by an inspector issue. */ @Serializable public data class AffectedCookie( /** * The following three properties uniquely identify a cookie */ public val name: String, public val path: String, public val domain: String ) /** * Information about a request that is affected by an inspector issue. */ @Serializable public data class AffectedRequest( /** * The unique request id. */ public val requestId: String, public val url: String? = null ) /** * Information about the frame affected by an inspector issue. */ @Serializable public data class AffectedFrame( public val frameId: String ) @Serializable public enum class SameSiteCookieExclusionReason { @SerialName("ExcludeSameSiteUnspecifiedTreatedAsLax") EXCLUDESAMESITEUNSPECIFIEDTREATEDASLAX, @SerialName("ExcludeSameSiteNoneInsecure") EXCLUDESAMESITENONEINSECURE, @SerialName("ExcludeSameSiteLax") EXCLUDESAMESITELAX, @SerialName("ExcludeSameSiteStrict") EXCLUDESAMESITESTRICT, } @Serializable public enum class SameSiteCookieWarningReason { @SerialName("WarnSameSiteUnspecifiedCrossSiteContext") WARNSAMESITEUNSPECIFIEDCROSSSITECONTEXT, @SerialName("WarnSameSiteNoneInsecure") WARNSAMESITENONEINSECURE, @SerialName("WarnSameSiteUnspecifiedLaxAllowUnsafe") WARNSAMESITEUNSPECIFIEDLAXALLOWUNSAFE, @SerialName("WarnSameSiteStrictLaxDowngradeStrict") WARNSAMESITESTRICTLAXDOWNGRADESTRICT, @SerialName("WarnSameSiteStrictCrossDowngradeStrict") WARNSAMESITESTRICTCROSSDOWNGRADESTRICT, @SerialName("WarnSameSiteStrictCrossDowngradeLax") WARNSAMESITESTRICTCROSSDOWNGRADELAX, @SerialName("WarnSameSiteLaxCrossDowngradeStrict") WARNSAMESITELAXCROSSDOWNGRADESTRICT, @SerialName("WarnSameSiteLaxCrossDowngradeLax") WARNSAMESITELAXCROSSDOWNGRADELAX, } @Serializable public enum class SameSiteCookieOperation { @SerialName("SetCookie") SETCOOKIE, @SerialName("ReadCookie") READCOOKIE, } /** * This information is currently necessary, as the front-end has a difficult * time finding a specific cookie. With this, we can convey specific error * information without the cookie. */ @Serializable public data class SameSiteCookieIssueDetails( public val cookie: AffectedCookie, public val cookieWarningReasons: List<SameSiteCookieWarningReason>, public val cookieExclusionReasons: List<SameSiteCookieExclusionReason>, /** * Optionally identifies the site-for-cookies and the cookie url, which * may be used by the front-end as additional context. */ public val operation: SameSiteCookieOperation, public val siteForCookies: String? = null, public val cookieUrl: String? = null, public val request: AffectedRequest? = null ) @Serializable public enum class MixedContentResolutionStatus { @SerialName("MixedContentBlocked") MIXEDCONTENTBLOCKED, @SerialName("MixedContentAutomaticallyUpgraded") MIXEDCONTENTAUTOMATICALLYUPGRADED, @SerialName("MixedContentWarning") MIXEDCONTENTWARNING, } @Serializable public enum class MixedContentResourceType { @SerialName("Audio") AUDIO, @SerialName("Beacon") BEACON, @SerialName("CSPReport") CSPREPORT, @SerialName("Download") DOWNLOAD, @SerialName("EventSource") EVENTSOURCE, @SerialName("Favicon") FAVICON, @SerialName("Font") FONT, @SerialName("Form") FORM, @SerialName("Frame") FRAME, @SerialName("Image") IMAGE, @SerialName("Import") IMPORT, @SerialName("Manifest") MANIFEST, @SerialName("Ping") PING, @SerialName("PluginData") PLUGINDATA, @SerialName("PluginResource") PLUGINRESOURCE, @SerialName("Prefetch") PREFETCH, @SerialName("Resource") RESOURCE, @SerialName("Script") SCRIPT, @SerialName("ServiceWorker") SERVICEWORKER, @SerialName("SharedWorker") SHAREDWORKER, @SerialName("Stylesheet") STYLESHEET, @SerialName("Track") TRACK, @SerialName("Video") VIDEO, @SerialName("Worker") WORKER, @SerialName("XMLHttpRequest") XMLHTTPREQUEST, @SerialName("XSLT") XSLT, } @Serializable public data class MixedContentIssueDetails( /** * The type of resource causing the mixed content issue (css, js, iframe, * form,...). Marked as optional because it is mapped to from * blink::mojom::RequestContextType, which will be replaced * by network::mojom::RequestDestination */ public val resourceType: MixedContentResourceType? = null, /** * The way the mixed content issue is being resolved. */ public val resolutionStatus: MixedContentResolutionStatus, /** * The unsafe http url causing the mixed content issue. */ public val insecureURL: String, /** * The url responsible for the call to an unsafe url. */ public val mainResourceURL: String, /** * The mixed content request. * Does not always exist (e.g. for unsafe form submission urls). */ public val request: AffectedRequest? = null, /** * Optional because not every mixed content issue is necessarily linked to a frame. */ public val frame: AffectedFrame? = null ) /** * Enum indicating the reason a response has been blocked. These reasons are * refinements of the net error BLOCKED_BY_RESPONSE. */ @Serializable public enum class BlockedByResponseReason { @SerialName("CoepFrameResourceNeedsCoepHeader") COEPFRAMERESOURCENEEDSCOEPHEADER, @SerialName("CoopSandboxedIFrameCannotNavigateToCoopPage") COOPSANDBOXEDIFRAMECANNOTNAVIGATETOCOOPPAGE, @SerialName("CorpNotSameOrigin") CORPNOTSAMEORIGIN, @SerialName("CorpNotSameOriginAfterDefaultedToSameOriginByCoep") CORPNOTSAMEORIGINAFTERDEFAULTEDTOSAMEORIGINBYCOEP, @SerialName("CorpNotSameSite") CORPNOTSAMESITE, } /** * Details for a request that has been blocked with the BLOCKED_BY_RESPONSE * code. Currently only used for COEP/COOP, but may be extended to include * some CSP errors in the future. */ @Serializable public data class BlockedByResponseIssueDetails( public val request: AffectedRequest, public val parentFrame: AffectedFrame? = null, public val blockedFrame: AffectedFrame? = null, public val reason: BlockedByResponseReason ) @Serializable public enum class HeavyAdResolutionStatus { @SerialName("HeavyAdBlocked") HEAVYADBLOCKED, @SerialName("HeavyAdWarning") HEAVYADWARNING, } @Serializable public enum class HeavyAdReason { @SerialName("NetworkTotalLimit") NETWORKTOTALLIMIT, @SerialName("CpuTotalLimit") CPUTOTALLIMIT, @SerialName("CpuPeakLimit") CPUPEAKLIMIT, } @Serializable public data class HeavyAdIssueDetails( /** * The resolution status, either blocking the content or warning. */ public val resolution: HeavyAdResolutionStatus, /** * The reason the ad was blocked, total network or cpu or peak cpu. */ public val reason: HeavyAdReason, /** * The frame that was blocked. */ public val frame: AffectedFrame ) @Serializable public enum class ContentSecurityPolicyViolationType { @SerialName("kInlineViolation") KINLINEVIOLATION, @SerialName("kEvalViolation") KEVALVIOLATION, @SerialName("kURLViolation") KURLVIOLATION, @SerialName("kTrustedTypesSinkViolation") KTRUSTEDTYPESSINKVIOLATION, @SerialName("kTrustedTypesPolicyViolation") KTRUSTEDTYPESPOLICYVIOLATION, } @Serializable public data class SourceCodeLocation( public val scriptId: String? = null, public val url: String, public val lineNumber: Int, public val columnNumber: Int ) @Serializable public data class ContentSecurityPolicyIssueDetails( /** * The url not included in allowed sources. */ public val blockedURL: String? = null, /** * Specific directive that is violated, causing the CSP issue. */ public val violatedDirective: String, public val isReportOnly: Boolean, public val contentSecurityPolicyViolationType: ContentSecurityPolicyViolationType, public val frameAncestor: AffectedFrame? = null, public val sourceCodeLocation: SourceCodeLocation? = null, public val violatingNodeId: Int? = null ) @Serializable public enum class SharedArrayBufferIssueType { @SerialName("TransferIssue") TRANSFERISSUE, @SerialName("CreationIssue") CREATIONISSUE, } /** * Details for a issue arising from an SAB being instantiated in, or * transfered to a context that is not cross-origin isolated. */ @Serializable public data class SharedArrayBufferIssueDetails( public val sourceCodeLocation: SourceCodeLocation, public val isWarning: Boolean, public val type: SharedArrayBufferIssueType ) @Serializable public enum class TwaQualityEnforcementViolationType { @SerialName("kHttpError") KHTTPERROR, @SerialName("kUnavailableOffline") KUNAVAILABLEOFFLINE, @SerialName("kDigitalAssetLinks") KDIGITALASSETLINKS, } @Serializable public data class TrustedWebActivityIssueDetails( /** * The url that triggers the violation. */ public val url: String, public val violationType: TwaQualityEnforcementViolationType, public val httpStatusCode: Int? = null, /** * The package name of the Trusted Web Activity client app. This field is * only used when violation type is kDigitalAssetLinks. */ public val packageName: String? = null, /** * The signature of the Trusted Web Activity client app. This field is only * used when violation type is kDigitalAssetLinks. */ public val signature: String? = null ) @Serializable public data class LowTextContrastIssueDetails( public val violatingNodeId: Int, public val violatingNodeSelector: String, public val contrastRatio: Double, public val thresholdAA: Double, public val thresholdAAA: Double, public val fontSize: String, public val fontWeight: String ) /** * Details for a CORS related issue, e.g. a warning or error related to * CORS RFC1918 enforcement. */ @Serializable public data class CorsIssueDetails( public val corsErrorStatus: Network.CorsErrorStatus, public val isWarning: Boolean, public val request: AffectedRequest, public val resourceIPAddressSpace: Network.IPAddressSpace? = null, public val clientSecurityState: Network.ClientSecurityState? = null ) /** * A unique identifier for the type of issue. Each type may use one of the * optional fields in InspectorIssueDetails to convey more specific * information about the kind of issue. */ @Serializable public enum class InspectorIssueCode { @SerialName("SameSiteCookieIssue") SAMESITECOOKIEISSUE, @SerialName("MixedContentIssue") MIXEDCONTENTISSUE, @SerialName("BlockedByResponseIssue") BLOCKEDBYRESPONSEISSUE, @SerialName("HeavyAdIssue") HEAVYADISSUE, @SerialName("ContentSecurityPolicyIssue") CONTENTSECURITYPOLICYISSUE, @SerialName("SharedArrayBufferIssue") SHAREDARRAYBUFFERISSUE, @SerialName("TrustedWebActivityIssue") TRUSTEDWEBACTIVITYISSUE, @SerialName("LowTextContrastIssue") LOWTEXTCONTRASTISSUE, @SerialName("CorsIssue") CORSISSUE, } /** * This struct holds a list of optional fields with additional information * specific to the kind of issue. When adding a new issue code, please also * add a new optional field to this type. */ @Serializable public data class InspectorIssueDetails( public val sameSiteCookieIssueDetails: SameSiteCookieIssueDetails? = null, public val mixedContentIssueDetails: MixedContentIssueDetails? = null, public val blockedByResponseIssueDetails: BlockedByResponseIssueDetails? = null, public val heavyAdIssueDetails: HeavyAdIssueDetails? = null, public val contentSecurityPolicyIssueDetails: ContentSecurityPolicyIssueDetails? = null, public val sharedArrayBufferIssueDetails: SharedArrayBufferIssueDetails? = null, public val twaQualityEnforcementDetails: TrustedWebActivityIssueDetails? = null, public val lowTextContrastIssueDetails: LowTextContrastIssueDetails? = null, public val corsIssueDetails: CorsIssueDetails? = null ) /** * An inspector issue reported from the back-end. */ @Serializable public data class InspectorIssue( public val code: InspectorIssueCode, public val details: InspectorIssueDetails ) public data class IssueAddedParameter( public val issue: InspectorIssue ) @Serializable public data class GetEncodedResponseParameter( /** * Identifier of the network request to get content for. */ public val requestId: String, /** * The encoding to use. */ public val encoding: String, /** * The quality of the encoding (0-1). (defaults to 1) */ public val quality: Double? = null, /** * Whether to only return the size information (defaults to false). */ public val sizeOnly: Boolean? = null ) @Serializable public data class GetEncodedResponseReturn( /** * The encoded body as a base64 string. Omitted if sizeOnly is true. (Encoded as a base64 string * when passed over JSON) */ public val body: String?, /** * Size before re-encoding. */ public val originalSize: Int, /** * Size after re-encoding. */ public val encodedSize: Int ) }
0
Kotlin
0
0
339ced4bd70f81afe30350ba58c0b518b1dd8cde
17,128
cdpclient
Apache License 2.0
app/src/main/java/com/playme/home/ui/PlayerStateCallback.kt
Devendra-Mehra
298,543,057
false
null
package com.playme.home.ui interface PlayerStateCallback { fun onIsPlayingChanged(isPlaying: Boolean) fun onPlayerError() }
0
Kotlin
0
0
bed76a5b7b89f6910b9a783776a4afaa29a22c22
134
PLAYme
Apache License 2.0
src/main/kotlin/entities/Matricula.kt
rafamaneschy
401,841,901
false
{"Kotlin": 11301, "Assembly": 36}
package entities import java.time.LocalDate class Matricula(var aluno: Aluno, var curso: Curso) { var dataDeMatricula:LocalDate = LocalDate.now() override fun toString(): String { return "$aluno | $curso | $dataDeMatricula" } }
0
Kotlin
0
0
e722e9d0c256cffc6caa8f947ec19c81bd0327ee
257
desafioKotlin-DigitalHouse
MIT License
material/src/main/java/com/m3u/material/components/mask/MaskInterceptor.kt
realOxy
592,741,804
false
{"Kotlin": 734765}
package com.m3u.material.components.mask typealias MaskInterceptor = (Boolean) -> Boolean
19
Kotlin
9
95
67e7185408a544094c7b4403f8309a52dad4aca0
91
M3UAndroid
Apache License 2.0
cache/src/main/kotlin/xlitekt/cache/provider/font/FontEntryType.kt
runetopic
448,110,155
false
null
package xlitekt.cache.provider.font import kotlinx.serialization.Serializable import xlitekt.cache.provider.EntryType /** * @author <NAME> */ @Serializable data class FontEntryType( override val id: Int, var name: String? = null, var ascent: Int = 0, var offsetsX: IntArray? = null, var offsetsY: IntArray? = null, var widths: IntArray? = null, var heights: IntArray? = null, var kerning: ByteArray? = null, var maxAscent: Int = 0, var maxDescent: Int = 0 ) : EntryType(id)
0
Kotlin
3
8
c896a2957470769a212961ba3e4331f04fc785df
518
xlitekt
MIT License
cache/src/main/kotlin/xlitekt/cache/provider/font/FontEntryType.kt
runetopic
448,110,155
false
null
package xlitekt.cache.provider.font import kotlinx.serialization.Serializable import xlitekt.cache.provider.EntryType /** * @author <NAME> */ @Serializable data class FontEntryType( override val id: Int, var name: String? = null, var ascent: Int = 0, var offsetsX: IntArray? = null, var offsetsY: IntArray? = null, var widths: IntArray? = null, var heights: IntArray? = null, var kerning: ByteArray? = null, var maxAscent: Int = 0, var maxDescent: Int = 0 ) : EntryType(id)
0
Kotlin
3
8
c896a2957470769a212961ba3e4331f04fc785df
518
xlitekt
MIT License
v2-emblem/src/commonMain/kotlin/com/bselzer/gw2/v2/emblem/constant/Parameters.kt
Woody230
388,820,096
false
{"Kotlin": 750899}
package com.bselzer.gw2.v2.emblem.constant internal object Parameters { /** * The options. */ const val OPTIONS = "options" }
2
Kotlin
0
2
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
144
GW2Wrapper
Apache License 2.0
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/finance/Coupon5Line.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.finance 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 com.woowla.compose.icon.collections.remix.remix.FinanceGroup public val FinanceGroup.Coupon5Line: ImageVector get() { if (_coupon5Line != null) { return _coupon5Line!! } _coupon5Line = Builder(name = "Coupon5Line", 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(21.005f, 14.0f) verticalLineTo(21.0f) curveTo(21.005f, 21.552f, 20.557f, 22.0f, 20.005f, 22.0f) horizontalLineTo(4.005f) curveTo(3.453f, 22.0f, 3.005f, 21.552f, 3.005f, 21.0f) verticalLineTo(14.0f) curveTo(4.109f, 14.0f, 5.005f, 13.104f, 5.005f, 12.0f) curveTo(5.005f, 10.895f, 4.109f, 10.0f, 3.005f, 10.0f) verticalLineTo(3.0f) curveTo(3.005f, 2.447f, 3.453f, 2.0f, 4.005f, 2.0f) horizontalLineTo(20.005f) curveTo(20.557f, 2.0f, 21.005f, 2.447f, 21.005f, 3.0f) verticalLineTo(10.0f) curveTo(19.9f, 10.0f, 19.005f, 10.895f, 19.005f, 12.0f) curveTo(19.005f, 13.104f, 19.9f, 14.0f, 21.005f, 14.0f) close() moveTo(19.005f, 15.465f) curveTo(17.809f, 14.773f, 17.005f, 13.48f, 17.005f, 12.0f) curveTo(17.005f, 10.519f, 17.809f, 9.227f, 19.005f, 8.535f) verticalLineTo(4.0f) horizontalLineTo(5.005f) verticalLineTo(8.535f) curveTo(6.2f, 9.227f, 7.005f, 10.519f, 7.005f, 12.0f) curveTo(7.005f, 13.48f, 6.2f, 14.773f, 5.005f, 15.465f) verticalLineTo(20.0f) horizontalLineTo(19.005f) verticalLineTo(15.465f) close() moveTo(9.005f, 6.0f) horizontalLineTo(15.005f) verticalLineTo(8.0f) horizontalLineTo(9.005f) verticalLineTo(6.0f) close() moveTo(9.005f, 16.0f) horizontalLineTo(15.005f) verticalLineTo(18.0f) horizontalLineTo(9.005f) verticalLineTo(16.0f) close() } } .build() return _coupon5Line!! } private var _coupon5Line: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,184
compose-icon-collections
MIT License
app/src/main/kotlin/app/newproj/lbrytv/service/OdyseeService.kt
linimin
434,503,024
false
null
/* * MIT License * * Copyright (c) 2022 <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 app.newproj.lbrytv.service import app.newproj.lbrytv.data.dto.OdyseeServiceResponse import app.newproj.lbrytv.data.dto.RecommendedContent import com.google.gson.reflect.TypeToken import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import retrofit2.http.GET import java.lang.reflect.Type interface OdyseeService { @GET("\$/api/content/v1/get") suspend fun recommendedContent(): Map<String, Map<String, RecommendedContent>> } object OdyseeServiceBodyConverterFactory : Converter.Factory() { override fun responseBodyConverter( type: Type, annotations: Array<out Annotation>, retrofit: Retrofit, ): Converter<ResponseBody, *> = ResponseBodyConverter( delegate = retrofit.nextResponseBodyConverter<OdyseeServiceResponse<*>>( this, TypeToken.getParameterized(OdyseeServiceResponse::class.java, type).type, annotations ) ) private class ResponseBodyConverter<T>( private val delegate: Converter<ResponseBody, OdyseeServiceResponse<out T>>, ) : Converter<ResponseBody, T> { override fun convert(value: ResponseBody): T? = delegate.convert(value)?.data } }
7
Kotlin
3
23
75bed7e7bae0b1ddaa2b5356b82dbec62c25776e
2,376
lbry-androidtv
MIT License
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Card.kt
androidx
256,589,781
false
{"Kotlin": 102794437, "Java": 64412412, "C++": 9138104, "AIDL": 617598, "Python": 310931, "Shell": 189529, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18033, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.Composable import androidx.compose.runtime.NonRestartableComposable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * <a href="https://material.io/components/cards" class="external" target="_blank">Material Design card</a>. * * Cards contain content and actions about a single subject. * * ![Cards image](https://developer.android.com/images/reference/androidx/compose/material/cards.png) * * This version of Card will block clicks behind it. For clickable card, please use another * overload that accepts `onClick` as a parameter. * * @sample androidx.compose.material.samples.CardSample * * @param modifier Modifier to be applied to the layout of the card. * @param shape Defines the card's shape as well its shadow. A shadow is only * displayed if the [elevation] is greater than zero. * @param backgroundColor The background color. * @param contentColor The preferred content color provided by this card to its children. * Defaults to either the matching content color for [backgroundColor], or if [backgroundColor] * is not a color from the theme, this will keep the same value set above this card. * @param border Optional border to draw on top of the card * @param elevation The z-coordinate at which to place this card. This controls * the size of the shadow below the card. */ @Composable @NonRestartableComposable fun Card( modifier: Modifier = Modifier, shape: Shape = MaterialTheme.shapes.medium, backgroundColor: Color = MaterialTheme.colors.surface, contentColor: Color = contentColorFor(backgroundColor), border: BorderStroke? = null, elevation: Dp = 1.dp, content: @Composable () -> Unit ) { Surface( modifier = modifier, shape = shape, color = backgroundColor, contentColor = contentColor, elevation = elevation, border = border, content = content ) } /** * Cards are [Surface]s that display content and actions on a single topic. * * This version of Card provides click handling as well. If you do not want Card to handle * clicks, consider using another overload. * * @sample androidx.compose.material.samples.ClickableCardSample * * @param onClick callback to be called when the card is clicked * @param modifier Modifier to be applied to the layout of the card. * @param enabled Controls the enabled state of the card. When `false`, this card will not * be clickable * @param shape Defines the card's shape as well its shadow. A shadow is only * displayed if the [elevation] is greater than zero. * @param backgroundColor The background color. * @param contentColor The preferred content color provided by this card to its children. * Defaults to either the matching content color for [backgroundColor], or if [backgroundColor] * is not a color from the theme, this will keep the same value set above this card. * @param border Optional border to draw on top of the card * @param elevation The z-coordinate at which to place this card. This controls * the size of the shadow below the card. * @param interactionSource an optional hoisted [MutableInteractionSource] for observing and * emitting [Interaction]s for this card. You can use this to change the card's * appearance or preview the card in different states. Note that if `null` is provided, * interactions will still happen internally. */ @ExperimentalMaterialApi @Composable @NonRestartableComposable fun Card( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = MaterialTheme.shapes.medium, backgroundColor: Color = MaterialTheme.colors.surface, contentColor: Color = contentColorFor(backgroundColor), border: BorderStroke? = null, elevation: Dp = 1.dp, interactionSource: MutableInteractionSource? = null, content: @Composable () -> Unit ) { Surface( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, color = backgroundColor, contentColor = contentColor, border = border, elevation = elevation, interactionSource = interactionSource, content = content ) }
28
Kotlin
937
5,108
89ec14e39cf771106a8719337062572717cbad31
5,184
androidx
Apache License 2.0
cosmos-sdk/src/commonMain/kotlin/cosmos/base/store/v1beta1/commit_info.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from cosmos/base/store/v1beta1/commit_info.proto @file:ProtobufSyntax(syntax = "PROTO3") @file:GeneratorVersion(version = "0.3.1") package cosmos.base.store.v1beta1 import google.protobuf.Timestamp import kotlin.ByteArray import kotlin.Long import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.`annotation`.ProtobufIndex import kr.jadekim.protobuf.`annotation`.ProtobufSyntax import kr.jadekim.protobuf.kotlinx.ProtobufConverterEncoder import kr.jadekim.protobuf.kotlinx.ProtobufMapperDecoder import kr.jadekim.protobuf.type.ProtobufMessage @Serializable(with = CommitInfo.KotlinxSerializer::class) @SerialName(value = CommitInfo.TYPE_URL) public data class CommitInfo( @ProtobufIndex(index = 1) public val version: Long, @ProtobufIndex(index = 2) public val storeInfos: List<StoreInfo>, @ProtobufIndex(index = 3) public val timestamp: Timestamp, ) : ProtobufMessage { public companion object { public const val TYPE_URL: String = "/cosmos.base.store.v1beta1.CommitInfo" } public object KotlinxSerializer : KSerializer<CommitInfo> { private val delegator: KSerializer<CommitInfo> = CommitInfo.serializer() public override val descriptor: SerialDescriptor = delegator.descriptor public override fun serialize(encoder: Encoder, `value`: CommitInfo): Unit { if (encoder is ProtobufConverterEncoder) { encoder.encodeValue(CommitInfoConverter.serialize(value)) return } delegator.serialize(encoder, value) } public override fun deserialize(decoder: Decoder): CommitInfo { if (decoder is ProtobufMapperDecoder) { return CommitInfoConverter.deserialize(decoder.decodeByteArray()) } return delegator.deserialize(decoder) } } } @Serializable(with = StoreInfo.KotlinxSerializer::class) @SerialName(value = StoreInfo.TYPE_URL) public data class StoreInfo( @ProtobufIndex(index = 1) public val name: String, @ProtobufIndex(index = 2) public val commitId: CommitID, ) : ProtobufMessage { public companion object { public const val TYPE_URL: String = "/cosmos.base.store.v1beta1.StoreInfo" } public object KotlinxSerializer : KSerializer<StoreInfo> { private val delegator: KSerializer<StoreInfo> = StoreInfo.serializer() public override val descriptor: SerialDescriptor = delegator.descriptor public override fun serialize(encoder: Encoder, `value`: StoreInfo): Unit { if (encoder is ProtobufConverterEncoder) { encoder.encodeValue(StoreInfoConverter.serialize(value)) return } delegator.serialize(encoder, value) } public override fun deserialize(decoder: Decoder): StoreInfo { if (decoder is ProtobufMapperDecoder) { return StoreInfoConverter.deserialize(decoder.decodeByteArray()) } return delegator.deserialize(decoder) } } } @Serializable(with = CommitID.KotlinxSerializer::class) @SerialName(value = CommitID.TYPE_URL) public data class CommitID( @ProtobufIndex(index = 1) public val version: Long, @ProtobufIndex(index = 2) public val hash: ByteArray, ) : ProtobufMessage { public companion object { public const val TYPE_URL: String = "/cosmos.base.store.v1beta1.CommitID" } public object KotlinxSerializer : KSerializer<CommitID> { private val delegator: KSerializer<CommitID> = CommitID.serializer() public override val descriptor: SerialDescriptor = delegator.descriptor public override fun serialize(encoder: Encoder, `value`: CommitID): Unit { if (encoder is ProtobufConverterEncoder) { encoder.encodeValue(CommitIDConverter.serialize(value)) return } delegator.serialize(encoder, value) } public override fun deserialize(decoder: Decoder): CommitID { if (decoder is ProtobufMapperDecoder) { return CommitIDConverter.deserialize(decoder.decodeByteArray()) } return delegator.deserialize(decoder) } } }
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
4,323
chameleon.proto
Apache License 2.0
app/src/main/kotlin/com/thundermaps/apilib/android/api/resources/DeviceInfoLogs.kt
SaferMe
240,105,080
false
null
package com.thundermaps.apilib.android.api.resources import com.google.gson.annotations.Expose data class DeviceInfoLogs( @Expose val os_version: String = "", @Expose val device_model: String = "", @Expose val scan_timestamps: ArrayList<String> = ArrayList() ) : SaferMeDatum { override fun toString(): String { val sb = StringBuilder() sb.append("os_version $os_version \n") sb.append("device_model $device_model \n") sb.append("scans: ") for (scan in scan_timestamps) { sb.append("$scan, \n") } return sb.toString() } } data class DeviceInfoLog( @Expose val device_info_log: DeviceInfoLogs ) : SaferMeDatum { override fun toString(): String { return device_info_log.toString() } } interface DeviceInfoLogsResource : Creatable<DeviceInfoLog>
1
Kotlin
0
0
54b14f86140b409d158a20797ec14d9b4f66216a
873
saferme-api-client-android
MIT License
core/oauth2/impl/src/commonMain/kotlin/ru/kyamshanov/mission/oauth2/AuthenticationApi.kt
KYamshanov
656,042,097
false
{"Kotlin": 435157, "Batchfile": 2703, "HTML": 199, "Dockerfile": 195}
package ru.kyamshanov.mission.oauth2 import ru.kyamshanov.mission.oauth2.data.model.TokensRsDto internal interface AuthenticationApi { suspend fun token(authorizationCode: String, codeVerifier: String, callbackPort : Int): Result<TokensRsDto> suspend fun token(refreshToken: String): TokensRsDto }
7
Kotlin
0
1
f749be22ac5e994b97e8edb6e610c05d3ecded36
310
Mission-app
Apache License 2.0
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/create/ui/CreateScreen.kt
mrebollob
46,619,950
false
{"Kotlin": 142333, "Swift": 29488, "Ruby": 1908}
package com.mrebollob.loteria.android.presentation.create.ui import android.content.res.Configuration import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.ScaffoldState import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.mrebollob.loteria.android.R import com.mrebollob.loteria.android.analytics.AnalyticsEvent import com.mrebollob.loteria.android.analytics.AnalyticsManager import com.mrebollob.loteria.android.analytics.AnalyticsParameter import com.mrebollob.loteria.android.analytics.AnalyticsScreen import com.mrebollob.loteria.android.presentation.create.CreateUiState import com.mrebollob.loteria.android.presentation.create.CreateViewModel import com.mrebollob.loteria.android.presentation.platform.extension.supportWideScreen import com.mrebollob.loteria.android.presentation.platform.ui.components.LotterySnackbarHost import com.mrebollob.loteria.android.presentation.platform.ui.components.OutlinedBoxTextField import com.mrebollob.loteria.android.presentation.platform.ui.layout.BaseScaffold import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme @Composable fun CreateScreen( createViewModel: CreateViewModel, analyticsManager: AnalyticsManager, onBackClick: (() -> Unit) ) { val uiState by createViewModel.uiState.collectAsState() CreateScreen( uiState = uiState, onNameValueChange = { createViewModel.onNameValueChange(it) }, onNumberValueChange = { createViewModel.onNumberValueChange(it) }, onBetValueChange = { createViewModel.onBetValueChange(it) }, onSaveTicketClick = { analyticsManager.trackEvent( AnalyticsEvent.SAVE_NEW_TICKET_CLICK, AnalyticsParameter.CURRENT_LOCATION.withScreenValue(AnalyticsScreen.TICKET_FORM) ) createViewModel.onSaveTicketClick() }, onErrorDismiss = { createViewModel.errorShown(it) }, onBackClick = onBackClick ) } @Composable fun CreateScreen( scaffoldState: ScaffoldState = rememberScaffoldState(), uiState: CreateUiState, onNameValueChange: (String) -> Unit, onNumberValueChange: (String) -> Unit, onBetValueChange: (String) -> Unit, onSaveTicketClick: (() -> Unit), onErrorDismiss: (Long) -> Unit, onBackClick: (() -> Unit) ) { val focusRequester = remember { FocusRequester() } val focusManager = LocalFocusManager.current BaseScaffold( modifier = Modifier.supportWideScreen(), scaffoldState = scaffoldState, toolbarText = stringResource(id = R.string.create_screen_title), snackbarHost = { LotterySnackbarHost(hostState = it) }, onBackClick = onBackClick, content = { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { OutlinedBoxTextField( textFieldModifier = Modifier .focusRequester(focusRequester) .focusable(), label = stringResource(R.string.create_screen_ticket_name), value = uiState.name, keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = ImeAction.Next, keyboardType = KeyboardType.Text, autoCorrect = true, ), keyboardActions = KeyboardActions( onNext = { focusManager.moveFocus(FocusDirection.Down) } ), onValueChange = onNameValueChange, ) OutlinedBoxTextField( modifier = Modifier.padding(top = 16.dp), label = stringResource(R.string.create_screen_ticket_number), value = uiState.number, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Next, keyboardType = KeyboardType.Number, autoCorrect = false, ), keyboardActions = KeyboardActions( onNext = { focusManager.moveFocus(FocusDirection.Down) } ), onValueChange = onNumberValueChange, ) OutlinedBoxTextField( modifier = Modifier.padding(top = 16.dp), label = stringResource(R.string.create_screen_ticket_bet), value = uiState.bet, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done, keyboardType = KeyboardType.Number, autoCorrect = false, ), keyboardActions = KeyboardActions( onDone = { focusManager.clearFocus() if (uiState.isValidForm) { onSaveTicketClick() } } ), onValueChange = onBetValueChange, ) Button( modifier = Modifier .fillMaxWidth() .clipToBounds() .padding(top = 32.dp), shape = RoundedCornerShape(24.dp), onClick = { focusManager.clearFocus() onSaveTicketClick() }, enabled = uiState.isValidForm ) { Text( modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), text = stringResource(R.string.create_screen_ticket_save), style = MaterialTheme.typography.subtitle1 ) } } } ) if (uiState.errorMessages.isNotEmpty()) { val errorMessage = remember(uiState) { uiState.errorMessages[0] } val errorMessageText: String = stringResource(errorMessage.messageId) val retryMessageText = stringResource(id = R.string.ok_text) val onErrorDismissState by rememberUpdatedState(onErrorDismiss) LaunchedEffect(errorMessageText, retryMessageText, scaffoldState) { scaffoldState.snackbarHostState.showSnackbar( message = errorMessageText, actionLabel = retryMessageText ) onErrorDismissState(errorMessage.id) } } } @Preview("Create screen") @Preview("Create screen (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun PreviewCreateScreen() { val uiState = CreateUiState( name = "Familia", number = "0", bet = "20.5", isValidForm = true, isLoading = false, errorMessages = emptyList(), ) LotteryTheme { CreateScreen( uiState = uiState, onNameValueChange = {}, onNumberValueChange = {}, onBetValueChange = {}, onSaveTicketClick = {}, onErrorDismiss = {}, onBackClick = {} ) } }
0
Kotlin
0
0
2fe351ceaa6a3fc40faf2d57e32325bff6d5235b
8,821
LoteriadeNavidad
Apache License 2.0
tooling-country/src/commonMain/kotlin/dev/datlag/tooling/country/BritishIndianOceanTerritory.kt
DatL4g
739,165,922
false
{"Kotlin": 535226}
package dev.datlag.tooling.country import dev.datlag.tooling.country.serializer.CountryAsAlpha2StringSerializer import kotlinx.serialization.Serializable data object BritishIndianOceanTerritory : Country { override val codeAlpha2: Country.Code.Alpha2 = Country.Code.Alpha2("IO") override val codeAlpha3: Country.Code.Alpha3 = Country.Code.Alpha3("IOT") override val codeNumeric: Country.Code.Numeric = Country.Code.Numeric(86) }
0
Kotlin
0
3
11f8ee76909f12d96e4f1889e8b6daa7ae28ddd2
443
tooling
Apache License 2.0
hubdle-project-gradle-plugin/main/kotlin/com/javiersc/hubdle/project/extensions/kotlin/multiplatform/targets/wasm/HubdleKotlinMultiplatformWAsm32Extension.kt
JavierSegoviaCordoba
348,863,451
false
null
package com.javiersc.hubdle.project.extensions.kotlin.multiplatform.targets.wasm import com.javiersc.hubdle.project.extensions.HubdleDslMarker import com.javiersc.hubdle.project.extensions._internal.Configurable.Priority import com.javiersc.hubdle.project.extensions.apis.HubdleEnableableExtension import com.javiersc.hubdle.project.extensions.kotlin.multiplatform.hubdleKotlinMultiplatform import com.javiersc.hubdle.project.extensions.kotlin.shared.HubdleKotlinMinimalSourceSetConfigurableExtension import javax.inject.Inject import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.kotlin.dsl.configure import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension @HubdleDslMarker public open class HubdleKotlinMultiplatformWAsm32Extension @Inject constructor( project: Project, ) : HubdleKotlinMinimalSourceSetConfigurableExtension(project) { override val project: Project get() = super.project override val isEnabled: Property<Boolean> = property { false } override val priority: Priority = Priority.P3 public override val targetName: String = "wasm32" override val requiredExtensions: Set<HubdleEnableableExtension> get() = setOf(hubdleKotlinMultiplatform.wasm) override fun Project.defaultConfiguration() { configurable { configure<KotlinMultiplatformExtension> { wasm32() } } } }
16
Kotlin
8
16
3fb3299d206b6aa2ec380e6deb9724bc95e53b8b
1,390
hubdle
Apache License 2.0
desktop/src/jvmMain/kotlin/utils/withJUniqueLock.kt
EwoudVanPareren
682,550,040
false
{"Kotlin": 145914}
package utils import it.sauronsoftware.junique.AlreadyLockedException import it.sauronsoftware.junique.JUnique import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow private const val MESSAGE_OPEN = "open" /** * Ensure that only one instance of the application can run at a time for * this user on this machine. * * @param [id] the unique ID of the application * @param [block] the code to execute if this is the first/only instance * at the moment. Typically, this would contain the application's * main code. Once this block finishes, the one-instance lock is * released. */ fun withJUniqueLock(id: String, block: (openAttempt: Flow<Unit>) -> Unit) { try { val messages = MutableSharedFlow<Unit>( extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST ) JUnique.acquireLock(id) { message -> if (message == MESSAGE_OPEN) { messages.tryEmit(Unit) } null } try { block(messages) } finally { JUnique.releaseLock(id) } } catch (e: AlreadyLockedException) { JUnique.sendMessage(id, MESSAGE_OPEN) } }
8
Kotlin
0
0
babd866b5d916f159538203d6aaef5a6ba7294a4
1,300
SaltThePassManager
MIT License
dsl/config/src/main/kotlin/software/amazon/awscdk/dsl/services/config/dsl.kt
aws-cdk-dsl
176,878,480
false
{"Kotlin": 3500307}
package software.amazon.awscdk.dsl.services.config /** * @see software.amazon.awscdk.services.config.CfnConfigRule */ fun software.amazon.awscdk.Construct.cfnConfigRule(id: String, props: software.amazon.awscdk.services.config.CfnConfigRuleProps? = null, init: (software.amazon.awscdk.services.config.CfnConfigRule.() -> Unit)? = null) : software.amazon.awscdk.services.config.CfnConfigRule { val obj = software.amazon.awscdk.services.config.CfnConfigRule(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator */ fun software.amazon.awscdk.Construct.cfnConfigurationAggregator(id: String, props: software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps? = null, init: (software.amazon.awscdk.services.config.CfnConfigurationAggregator.() -> Unit)? = null) : software.amazon.awscdk.services.config.CfnConfigurationAggregator { val obj = software.amazon.awscdk.services.config.CfnConfigurationAggregator(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannel */ fun software.amazon.awscdk.Construct.cfnDeliveryChannel(id: String, props: software.amazon.awscdk.services.config.CfnDeliveryChannelProps? = null, init: (software.amazon.awscdk.services.config.CfnDeliveryChannel.() -> Unit)? = null) : software.amazon.awscdk.services.config.CfnDeliveryChannel { val obj = software.amazon.awscdk.services.config.CfnDeliveryChannel(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorder */ fun software.amazon.awscdk.Construct.cfnConfigurationRecorder(id: String, props: software.amazon.awscdk.services.config.CfnConfigurationRecorderProps? = null, init: (software.amazon.awscdk.services.config.CfnConfigurationRecorder.() -> Unit)? = null) : software.amazon.awscdk.services.config.CfnConfigurationRecorder { val obj = software.amazon.awscdk.services.config.CfnConfigurationRecorder(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.config.CfnAggregationAuthorization */ fun software.amazon.awscdk.Construct.cfnAggregationAuthorization(id: String, props: software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps? = null, init: (software.amazon.awscdk.services.config.CfnAggregationAuthorization.() -> Unit)? = null) : software.amazon.awscdk.services.config.CfnAggregationAuthorization { val obj = software.amazon.awscdk.services.config.CfnAggregationAuthorization(this, id, props) init?.invoke(obj) return obj } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder */ fun cfnConfigRuleProps(init: software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigRuleProps { val builder = software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withScope */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.scope: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on scope is not supported.") set(value) { this.withScope(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withSource */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.source: software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty get() = throw NoSuchFieldException("Get on source is not supported.") set(value) { this.withSource(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withDescription */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.description: String get() = throw NoSuchFieldException("Get on description is not supported.") set(value) { this.withDescription(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withMaximumExecutionFrequency */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.maximumExecutionFrequency: String get() = throw NoSuchFieldException("Get on maximumExecutionFrequency is not supported.") set(value) { this.withMaximumExecutionFrequency(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withConfigRuleName */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.configRuleName: String get() = throw NoSuchFieldException("Get on configRuleName is not supported.") set(value) { this.withConfigRuleName(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.withInputParameters */ var software.amazon.awscdk.services.config.CfnConfigRuleProps.Builder.inputParameters: com.fasterxml.jackson.databind.node.ObjectNode get() = throw NoSuchFieldException("Get on inputParameters is not supported.") set(value) { this.withInputParameters(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder */ fun organizationAggregationSourceProperty(init: software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty { val builder = software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder.withRoleArn */ var software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder.roleArn: String get() = throw NoSuchFieldException("Get on roleArn is not supported.") set(value) { this.withRoleArn(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder.withAllAwsRegions */ var software.amazon.awscdk.services.config.CfnConfigurationAggregator.OrganizationAggregationSourceProperty.Builder.allAwsRegions: Boolean get() = throw NoSuchFieldException("Get on allAwsRegions is not supported.") set(value) { this.withAllAwsRegions(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty.Builder */ fun accountAggregationSourceProperty(init: software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty { val builder = software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty.Builder.withAllAwsRegions */ var software.amazon.awscdk.services.config.CfnConfigurationAggregator.AccountAggregationSourceProperty.Builder.allAwsRegions: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on allAwsRegions is not supported.") set(value) { this.withAllAwsRegions(value) } /** * @see software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder */ fun cfnAggregationAuthorizationProps(init: software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps { val builder = software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder.withAuthorizedAccountId */ var software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder.authorizedAccountId: String get() = throw NoSuchFieldException("Get on authorizedAccountId is not supported.") set(value) { this.withAuthorizedAccountId(value) } /** * @see software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder.withAuthorizedAwsRegion */ var software.amazon.awscdk.services.config.CfnAggregationAuthorizationProps.Builder.authorizedAwsRegion: String get() = throw NoSuchFieldException("Get on authorizedAwsRegion is not supported.") set(value) { this.withAuthorizedAwsRegion(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder */ fun cfnConfigurationRecorderProps(init: software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigurationRecorderProps { val builder = software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.withRoleArn */ var software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.roleArn: String get() = throw NoSuchFieldException("Get on roleArn is not supported.") set(value) { this.withRoleArn(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.withRecordingGroup */ var software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.recordingGroup: software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty get() = throw NoSuchFieldException("Get on recordingGroup is not supported.") set(value) { this.withRecordingGroup(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.withName */ var software.amazon.awscdk.services.config.CfnConfigurationRecorderProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder */ fun recordingGroupProperty(init: software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty { val builder = software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder.withAllSupported */ var software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder.allSupported: Boolean get() = throw NoSuchFieldException("Get on allSupported is not supported.") set(value) { this.withAllSupported(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder.withIncludeGlobalResourceTypes */ var software.amazon.awscdk.services.config.CfnConfigurationRecorder.RecordingGroupProperty.Builder.includeGlobalResourceTypes: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on includeGlobalResourceTypes is not supported.") set(value) { this.withIncludeGlobalResourceTypes(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder */ fun cfnConfigurationAggregatorProps(init: software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps { val builder = software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.withConfigurationAggregatorName */ var software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.configurationAggregatorName: String get() = throw NoSuchFieldException("Get on configurationAggregatorName is not supported.") set(value) { this.withConfigurationAggregatorName(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.withAccountAggregationSources */ var software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.accountAggregationSources: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on accountAggregationSources is not supported.") set(value) { this.withAccountAggregationSources(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.withOrganizationAggregationSource */ var software.amazon.awscdk.services.config.CfnConfigurationAggregatorProps.Builder.organizationAggregationSource: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on organizationAggregationSource is not supported.") set(value) { this.withOrganizationAggregationSource(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder */ fun sourceProperty(init: software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty { val builder = software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.withSourceIdentifier */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.sourceIdentifier: String get() = throw NoSuchFieldException("Get on sourceIdentifier is not supported.") set(value) { this.withSourceIdentifier(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.withOwner */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.owner: String get() = throw NoSuchFieldException("Get on owner is not supported.") set(value) { this.withOwner(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.withSourceDetails */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceProperty.Builder.sourceDetails: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on sourceDetails is not supported.") set(value) { this.withSourceDetails(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder */ fun cfnDeliveryChannelProps(init: software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnDeliveryChannelProps { val builder = software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.withSnsTopicArn */ var software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.snsTopicArn: String get() = throw NoSuchFieldException("Get on snsTopicArn is not supported.") set(value) { this.withSnsTopicArn(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.withS3KeyPrefix */ var software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.s3KeyPrefix: String get() = throw NoSuchFieldException("Get on s3KeyPrefix is not supported.") set(value) { this.withS3KeyPrefix(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.withName */ var software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.name: String get() = throw NoSuchFieldException("Get on name is not supported.") set(value) { this.withName(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.withS3BucketName */ var software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.s3BucketName: String get() = throw NoSuchFieldException("Get on s3BucketName is not supported.") set(value) { this.withS3BucketName(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.withConfigSnapshotDeliveryProperties */ var software.amazon.awscdk.services.config.CfnDeliveryChannelProps.Builder.configSnapshotDeliveryProperties: software.amazon.awscdk.Token get() = throw NoSuchFieldException("Get on configSnapshotDeliveryProperties is not supported.") set(value) { this.withConfigSnapshotDeliveryProperties(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder */ fun sourceDetailProperty(init: software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty { val builder = software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.withMessageType */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.messageType: String get() = throw NoSuchFieldException("Get on messageType is not supported.") set(value) { this.withMessageType(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.withEventSource */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.eventSource: String get() = throw NoSuchFieldException("Get on eventSource is not supported.") set(value) { this.withEventSource(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.withMaximumExecutionFrequency */ var software.amazon.awscdk.services.config.CfnConfigRule.SourceDetailProperty.Builder.maximumExecutionFrequency: String get() = throw NoSuchFieldException("Get on maximumExecutionFrequency is not supported.") set(value) { this.withMaximumExecutionFrequency(value) } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty.Builder */ fun configSnapshotDeliveryPropertiesProperty(init: software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty { val builder = software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty.Builder.withDeliveryFrequency */ var software.amazon.awscdk.services.config.CfnDeliveryChannel.ConfigSnapshotDeliveryPropertiesProperty.Builder.deliveryFrequency: String get() = throw NoSuchFieldException("Get on deliveryFrequency is not supported.") set(value) { this.withDeliveryFrequency(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder */ fun scopeProperty(init: software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.() -> Unit): software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty { val builder = software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder() builder.init() return builder.build() } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.withComplianceResourceId */ var software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.complianceResourceId: String get() = throw NoSuchFieldException("Get on complianceResourceId is not supported.") set(value) { this.withComplianceResourceId(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.withTagKey */ var software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.tagKey: String get() = throw NoSuchFieldException("Get on tagKey is not supported.") set(value) { this.withTagKey(value) } /** * @see software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.withTagValue */ var software.amazon.awscdk.services.config.CfnConfigRule.ScopeProperty.Builder.tagValue: String get() = throw NoSuchFieldException("Get on tagValue is not supported.") set(value) { this.withTagValue(value) }
2
Kotlin
0
31
054694dc9793b7455c517af6afd666ec742594d4
21,022
aws-cdk-kotlin-dsl
MIT License
sub-foo/src/main/kotlin/io/androidalatan/lifecycle/template/foobar/sub/foo/FooUi.kt
android-alatan
606,930,016
false
null
package io.androidalatan.lifecycle.template.foobar.sub.foo import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import io.androidalatan.lifecycle.handler.compose.cache.cached object FooUi { @Composable fun Content(fooViewModel: FooViewModel = cached()) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { val text by fooViewModel.text.observeAsState(initial = "") Text(text = text) } } }
0
Kotlin
0
1
325d2b639743899acbf6a5acb2c55f4dd410b466
795
LifecycleComponentTemplate
MIT License
app/src/main/java/com/ss/moviehub/ui/details/DetailsFragment.kt
Abdulrahman-AlGhamdi
303,362,695
false
null
package com.ss.moviehub.ui.details import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import coil.load import com.ss.moviehub.R import com.ss.moviehub.databinding.FragmentDetailsBinding import com.ss.moviehub.repository.details.DetailsRepository.* import com.ss.moviehub.repository.details.DetailsRepository.DetailsStatus.* import com.ss.moviehub.utils.showSnackBar import com.ss.moviehub.utils.viewBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch @AndroidEntryPoint class DetailsFragment : Fragment(R.layout.fragment_details) { private val binding by viewBinding(FragmentDetailsBinding::bind) private val viewModel: DetailsViewModel by viewModels() private val arguments by navArgs<DetailsFragmentArgs>() private lateinit var detailsJob: Job override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) init() bindMovieDetails() checkIsMovieInLibrary() } private fun init() { viewModel.checkIsOnLibrary(arguments.movie.id) } private fun bindMovieDetails() { binding.title.text = arguments.movie.title binding.overview.text = arguments.movie.overview binding.releaseDate.text = arguments.movie.releaseDate binding.poster.load("https://image.tmdb.org/t/p/w342${arguments.movie.posterPath}") binding.backdrop.load("https://image.tmdb.org/t/p/w342${arguments.movie.backdropPath}") arguments.movie.voteAverage.let { binding.ratingBar.rating = it.toFloat() binding.ratingNumber.text = it.toString() } } private fun checkIsMovieInLibrary() { detailsJob = lifecycleScope.launch(Dispatchers.Main) { viewModel.checkIsOnLibrary.collect { if (it !is CheckResult) return@collect if (!it.isOnLibrary) { binding.movieAction.text = getString(R.string.add_to_library) binding.movieAction.setOnClickListener { viewModel.addMovie(arguments.movie) requireView().showSnackBar(getString(R.string.successfully_added)) } } else { binding.movieAction.text = getString(R.string.delete_from_library) binding.movieAction.setOnClickListener { viewModel.removeMovie(arguments.movie) requireView().showSnackBar( message = getString(R.string.successfully_deleted), actionMessage = getString(R.string.undo) ) { viewModel.addMovie(arguments.movie) } } } } } } override fun onDestroyView() { if (::detailsJob.isInitialized) detailsJob.cancel() super.onDestroyView() } }
0
Kotlin
0
0
30957e2c5964d72a86ae5b96a0bce64d4ef3235f
3,210
MovieHub
Apache License 2.0
src/main/kotlin/org/xbery/artbeams/common/antispam/recaptcha/domain/RecaptchaResult.kt
beranradek
354,546,253
false
{"Kotlin": 598596, "JavaScript": 286267, "FreeMarker": 115245, "CSS": 13845, "Procfile": 109}
package org.xbery.artbeams.common.antispam.recaptcha.domain /** * @author <NAME> */ data class RecaptchaResult( /** * Whether this request was a valid reCAPTCHA token for your site. */ val success: Boolean, /** * reCAPTCHA learns by seeing real traffic on your site. For this reason, scores in a staging * environment or soon after implementing may differ from production. As reCAPTCHA v3 doesn't * ever interrupt the user flow, you can first run reCAPTCHA without taking action and then * decide on thresholds by looking at your traffic in the admin console. * 1.0 is very likely a good interaction, 0.0 is very likely a bot. * By default, you can use a threshold of 0.5. */ val score: Double )
0
Kotlin
1
2
20bcb95271673620232dbcf2e2f22f51c68cea80
760
artbeams
Apache License 2.0
app/src/main/java/com/app/mycamapp/MainActivity.kt
sadman15019
540,469,505
false
null
package com.app.mycamapp import android.Manifest import android.content.ContentValues import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.CountDownTimer import android.provider.MediaStore import androidx.appcompat.app.AppCompatActivity import androidx.camera.video.Recorder import androidx.camera.video.Recording import androidx.camera.video.VideoCapture import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import android.widget.Toast import androidx.camera.lifecycle.ProcessCameraProvider import android.util.Log import android.view.LayoutInflater import android.widget.Button import android.widget.TextView import androidx.camera.core.* import androidx.camera.video.FallbackStrategy import androidx.camera.video.MediaStoreOutputOptions import androidx.camera.video.Quality import androidx.camera.video.QualitySelector import androidx.camera.video.VideoRecordEvent import androidx.core.content.PermissionChecker import androidx.core.view.isVisible import com.app.mycamapp.databinding.ActivityMainBinding import com.app.mycamapp.databinding.ActivityMainBinding.inflate import java.nio.ByteBuffer import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { private lateinit var viewBinding: ActivityMainBinding lateinit var textView: TextView private var videoCapture:VideoCapture<Recorder>? = null private var recording: Recording? = null private lateinit var cameraExecutor: ExecutorService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding= inflate(layoutInflater) viewBinding.pause.isVisible=false viewBinding.stopbtn.isVisible=false setContentView(viewBinding.root) if (allPermissionsGranted()) { startCamera() } else { ActivityCompat.requestPermissions( this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS) } viewBinding.button.setOnClickListener { captureVideo() } viewBinding.stopbtn.setOnClickListener{ stopVideo() } cameraExecutor = Executors.newSingleThreadExecutor() } private fun stopVideo() { val curRecording = recording if (curRecording != null) { // Stop the current recording session. curRecording.stop() recording = null viewBinding.stopbtn.isVisible=false viewBinding.pause.isVisible=false return } val videoCapture = this.videoCapture ?: return viewBinding.button.isEnabled=false viewBinding.pause.isVisible=true viewBinding.stopbtn.isVisible=true // create and start a new recording session val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { viewBinding.button.apply { isEnabled = false } viewBinding.pause.apply { isEnabled=true } viewBinding.stopbtn.apply { isEnabled=true } } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { val msg = "Video capture succeeded: " + "${recordEvent.outputResults.outputUri}" Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT) .show() Log.d(TAG, msg) } else { recording?.close() recording = null Log.e(TAG, "Video capture ends with error: " + "${recordEvent.error}") } viewBinding.button.apply { isEnabled = true } viewBinding.pause.apply { isEnabled=false} viewBinding.stopbtn.apply { isEnabled=false } } } } } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } private fun captureVideo() { val videoCapture = this.videoCapture ?: return viewBinding.button.isEnabled=false viewBinding.pause.isVisible=true viewBinding.stopbtn.isVisible=true // create and start a new recording session val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { viewBinding.button.apply { isEnabled = false } viewBinding.pause.apply { isEnabled=true } viewBinding.stopbtn.apply { isEnabled=true } //start counter textView = findViewById(R.id.textView) // time count down for 30 seconds, // with 1 second as countDown interval object : CountDownTimer(15000, 1000) { // Callback function, fired on regular interval override fun onTick(millisUntilFinished: Long) { textView.setText("seconds remaining: " + millisUntilFinished / 1000) } // Callback function, fired // when the time is up override fun onFinish() { textView.setText("") stopVideo() } }.start() } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { val msg = "Video capture succeeded: " + "${recordEvent.outputResults.outputUri}" Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT) .show() Log.d(TAG, msg) } else { recording?.close() recording = null Log.e(TAG, "Video capture ends with error: " + "${recordEvent.error}") } viewBinding.button.apply { isEnabled = true } viewBinding.pause.apply { isEnabled=false} viewBinding.stopbtn.apply { isEnabled=false } } } } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener(Runnable { val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(viewBinding.viewFinder.surfaceProvider) } val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.HIGHEST)) .build() videoCapture = VideoCapture.withOutput(recorder) // For querying information and states. try { cameraProvider.unbindAll() val camera = cameraProvider.bindToLifecycle( this, cameraSelector, preview,videoCapture) val cameraControl = camera.cameraControl // For querying information and states. val cameraInfo = camera.cameraInfo cameraControl.enableTorch(true); } catch(exc: Exception) { Log.e(TAG, "Use case binding failed", exc)} }, ContextCompat.getMainExecutor(this)) } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CamApp" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private const val REQUEST_CODE_PERMISSIONS = 10 private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA ).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CODE_PERMISSIONS) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show() finish() } } } }
0
Kotlin
0
0
0c157d2dbcf9cd09e837843dd1e1a466e1159c5f
11,439
camapp
MIT License
core/src/com/lyeeedar/Systems/StatisticsSystem.kt
Lyeeedar
83,986,995
false
null
package com.lyeeedar.Systems import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.lyeeedar.AI.Tasks.TaskInterrupt import com.lyeeedar.Components.* import com.lyeeedar.Global import com.lyeeedar.Renderables.Animation.BlinkAnimation import com.lyeeedar.Renderables.Sprite.Sprite import com.lyeeedar.Util.AssetManager import com.lyeeedar.Util.Colour class StatisticsSystem : AbstractSystem(Family.one(StatisticsComponent::class.java).get()) { val blockEffect = AssetManager.loadParticleEffect("Block") val blockBrokenEffect = AssetManager.loadParticleEffect("BlockBroken") val hitEffect = AssetManager.loadParticleEffect("Hit") override fun doUpdate(deltaTime: Float) { for (entity in entities) { processEntity(entity) } } override fun onTurn() { for (e in entities) { if (e.stats().regeneratingHP > 0f) { e.stats().regenerationTimer++ if (e.stats().regenerationTimer > 4) { val toregen = Math.min(1f, e.stats().regeneratingHP) e.stats().hp += toregen } } } super.onTurn() } fun processEntity(entity: Entity) { val stats = entity.stats()!! if (stats.hp <= 0) { if (entity.getComponent(MarkedForDeletionComponent::class.java) == null) entity.add(MarkedForDeletionComponent()) } if (stats.tookDamage) { if (stats.showHp) { val sprite = entity.renderable()?.renderable as? Sprite if (sprite != null) { sprite.colourAnimation = BlinkAnimation.obtain().set(Colour(1f, 0.5f, 0.5f, 1f), sprite.colour, 0.15f, true) } } val tile = entity.tile() if (tile != null) { val p = hitEffect.copy() p.size[0] = entity.pos().size p.size[1] = entity.pos().size val pe = Entity() pe.add(RenderableComponent(p)) val ppos = PositionComponent() ppos.size = entity.pos().size ppos.position = entity.pos().position pe.add(ppos) Global.engine.addEntity(pe) } stats.tookDamage = false } if (stats.blockBroken) { stats.blockBroken = false val p = blockBrokenEffect.copy() p.size[0] = entity.pos().size p.size[1] = entity.pos().size val pe = Entity() pe.add(RenderableComponent(p)) val ppos = PositionComponent() ppos.size = entity.pos().size ppos.position = entity.pos().position pe.add(ppos) Global.engine.addEntity(pe) entity.task().tasks.add(TaskInterrupt()) } else if (stats.blockedDamage) { stats.blockedDamage = false val p = blockEffect.copy() p.size[0] = entity.pos().size p.size[1] = entity.pos().size val pe = Entity() pe.add(RenderableComponent(p)) val ppos = PositionComponent() ppos.size = entity.pos().size ppos.position = entity.pos().position pe.add(ppos) Global.engine.addEntity(pe) } } }
0
Kotlin
3
12
e8e58ab6d24cbfa25e40751b6b8f85139afe9129
2,783
TheAbyssOfSouls
Apache License 2.0
data/remote/src/main/java/com/ku_stacks/ku_ring/remote/user/UserClient.kt
ku-ring
412,458,697
false
{"Kotlin": 653070}
package com.ku_stacks.ku_ring.remote.user import com.ku_stacks.ku_ring.remote.user.request.FeedbackRequest import com.ku_stacks.ku_ring.remote.user.request.RegisterUserRequest import com.ku_stacks.ku_ring.remote.util.DefaultResponse import javax.inject.Inject class UserClient @Inject constructor( private val userService: UserService ) { suspend fun sendFeedback( token: String, feedbackRequest: FeedbackRequest, ): DefaultResponse { return userService.sendFeedback( token = token, feedbackRequest = feedbackRequest ) } suspend fun registerUser(token: String): DefaultResponse = userService.registerUser(RegisterUserRequest(token)) suspend fun getKuringBotQueryCount(token: String): Int { return runCatching { userService.getKuringBotQueryCount(token).data.leftAskCount }.getOrElse { 0 } } }
3
Kotlin
1
23
008e6093ade7e06da0488c53ba273f461b715f4d
916
KU-Ring-Android
Apache License 2.0
app/src/main/java/com/marcossalto/peopleapp/presentation/home/components/HomeContent.kt
marcossalto
843,101,377
false
{"Kotlin": 40412}
package com.marcossalto.peopleapp.presentation.home.components import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.marcossalto.peopleapp.domain.model.User import com.marcossalto.peopleapp.domain.repository.Users @Composable fun HomeContent( modifier: Modifier = Modifier, onDeleteUser: (user: User) -> Unit, onEditUser: (id: Int?) -> Unit, users: Users = emptyList() ) { Surface( color = MaterialTheme.colorScheme.surface, modifier = modifier ) { LazyColumn { items(users) { user -> UserItem( modifier = Modifier .fillMaxSize(), user = user, onEditUser = { onEditUser(user.id) }, onDeleteUser = { onDeleteUser(user) } ) } } } } @Composable @Preview fun HomeContentPreview() { HomeContent( onDeleteUser = {}, onEditUser = {}, users = listOf( User(id = 1, name = "John", lastName = "Doe", age = 30), User(id = 2, name = "Jane", lastName = "Doe", age = 25), User(id = 3, name = "Bob", lastName = "Smith", age = 40), User(id = 4, name = "Alice", lastName = "Johnson", age = 35), User(id = 5, name = "Tom", lastName = "Williams", age = 28), User(id = 6, name = "Sara", lastName = "Lee", age = 32), User(id = 7, name = "Mike", lastName = "Brown", age = 37), User(id = 8, name = "Emily", lastName = "Davis", age = 29), User(id = 9, name = "David", lastName = "Wilson", age = 42), User(id = 10, name = "Karen", lastName = "Taylor", age = 31) ) ) }
0
Kotlin
0
0
e89dbecc4cc1cc50db48e2aa0db999f54a7a1773
2,141
people-app
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/bold/money/Banknote2.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.bold.money import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 com.chiksmedina.solar.bold.MoneyGroup val MoneyGroup.Banknote2: ImageVector get() { if (_banknote2 != null) { return _banknote2!! } _banknote2 = Builder( name = "Banknote2", 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(20.9414f, 8.1888f) curveTo(21.5215f, 8.7621f, 21.771f, 9.4839f, 21.8877f, 10.3411f) curveTo(22.0f, 11.1668f, 22.0f, 12.2166f, 22.0f, 13.5191f) verticalLineTo(13.6236f) curveTo(22.0f, 14.9261f, 22.0f, 15.9759f, 21.8877f, 16.8016f) curveTo(21.771f, 17.6589f, 21.5215f, 18.3807f, 20.9414f, 18.9539f) curveTo(20.3612f, 19.5272f, 19.6307f, 19.7738f, 18.7632f, 19.889f) curveTo(17.9276f, 20.0f, 16.8651f, 20.0f, 15.547f, 20.0f) horizontalLineTo(10.622f) curveTo(9.3039f, 20.0f, 8.2414f, 20.0f, 7.4058f, 19.889f) curveTo(6.5382f, 19.7738f, 5.8078f, 19.5272f, 5.2276f, 18.9539f) curveTo(4.8757f, 18.6062f, 4.6453f, 18.2037f, 4.4926f, 17.7495f) curveTo(5.3641f, 17.8574f, 6.4422f, 17.8573f, 7.6879f, 17.8573f) horizontalLineTo(12.6974f) curveTo(13.979f, 17.8573f, 15.0833f, 17.8574f, 15.9676f, 17.7399f) curveTo(16.9154f, 17.614f, 17.8238f, 17.3301f, 18.5607f, 16.602f) curveTo(19.2975f, 15.8739f, 19.5848f, 14.9762f, 19.7123f, 14.0398f) curveTo(19.8312f, 13.166f, 19.8311f, 12.0748f, 19.831f, 10.8084f) verticalLineTo(10.6203f) curveTo(19.8311f, 9.3891f, 19.8311f, 8.3236f, 19.7219f, 7.4623f) curveTo(20.1818f, 7.6133f, 20.5893f, 7.8409f, 20.9414f, 8.1888f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(10.1926f, 9.0477f) curveTo(9.2611f, 9.0477f, 8.5059f, 9.7938f, 8.5059f, 10.7143f) curveTo(8.5059f, 11.6348f, 9.2611f, 12.381f, 10.1926f, 12.381f) curveTo(11.1242f, 12.381f, 11.8793f, 11.6348f, 11.8793f, 10.7143f) curveTo(11.8793f, 9.7938f, 11.1242f, 9.0477f, 10.1926f, 9.0477f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(2.8469f, 5.8368f) curveTo(2.0f, 6.6737f, 2.0f, 8.0206f, 2.0f, 10.7143f) curveTo(2.0f, 13.4081f, 2.0f, 14.755f, 2.8469f, 15.5918f) curveTo(3.6938f, 16.4287f, 5.0569f, 16.4287f, 7.783f, 16.4287f) horizontalLineTo(12.6022f) curveTo(15.3284f, 16.4287f, 16.6914f, 16.4287f, 17.5384f, 15.5918f) curveTo(18.3853f, 14.755f, 18.3853f, 13.4081f, 18.3853f, 10.7143f) curveTo(18.3853f, 8.0206f, 18.3853f, 6.6737f, 17.5384f, 5.8368f) curveTo(16.6914f, 5.0f, 15.3284f, 5.0f, 12.6022f, 5.0f) horizontalLineTo(7.783f) curveTo(5.0569f, 5.0f, 3.6938f, 5.0f, 2.8469f, 5.8368f) close() moveTo(7.0602f, 10.7143f) curveTo(7.0602f, 9.0049f, 8.4626f, 7.6191f, 10.1926f, 7.6191f) curveTo(11.9226f, 7.6191f, 13.3251f, 9.0049f, 13.3251f, 10.7143f) curveTo(13.3251f, 12.4238f, 11.9226f, 13.8096f, 10.1926f, 13.8096f) curveTo(8.4626f, 13.8096f, 7.0602f, 12.4238f, 7.0602f, 10.7143f) close() moveTo(15.4937f, 13.3334f) curveTo(15.0945f, 13.3334f, 14.7709f, 13.0136f, 14.7709f, 12.6191f) verticalLineTo(8.8096f) curveTo(14.7709f, 8.4151f, 15.0945f, 8.0953f, 15.4937f, 8.0953f) curveTo(15.893f, 8.0953f, 16.2166f, 8.4151f, 16.2166f, 8.8096f) verticalLineTo(12.6191f) curveTo(16.2166f, 13.0136f, 15.893f, 13.3334f, 15.4937f, 13.3334f) close() moveTo(4.1686f, 12.6191f) curveTo(4.1686f, 13.0136f, 4.4923f, 13.3334f, 4.8915f, 13.3334f) curveTo(5.2908f, 13.3334f, 5.6144f, 13.0136f, 5.6144f, 12.6191f) lineTo(5.6144f, 8.8096f) curveTo(5.6144f, 8.4151f, 5.2908f, 8.0953f, 4.8915f, 8.0953f) curveTo(4.4923f, 8.0953f, 4.1686f, 8.4151f, 4.1686f, 8.8096f) lineTo(4.1686f, 12.6191f) close() } } .build() return _banknote2!! } private var _banknote2: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
5,863
SolarIconSetAndroid
MIT License
app/src/test/java/com/skelterlabs/events/CartEventTest.kt
SkelterLabsInc
365,889,870
false
null
package com.skelterlabs.events import org.joda.time.DateTimeUtils import org.junit.After import org.junit.Test class CartEventTest : EventTestBase() { @After override fun tearDown() { super.tearDown() DateTimeUtils.setCurrentMillisSystem() } @Test fun whenCallingToCustomFieldOfCartEvent_thenReturnCartEventMap() { DateTimeUtils.setCurrentMillisFixed(100_000L) val expected = mapOf("type" to "cart", "timestamp" to 100_000L) assertCustomFieldEquals(expected, CartEvent().toCustomField()) } }
0
Kotlin
0
1
cf4a80f69b2365f13b475232bd5434de7a2d8aaa
529
aware-android-sdk
Apache License 2.0
app/src/main/java/com/dvh/clockcompose/Clock.kt
Havriiash
629,092,308
false
null
package com.dvh.clockcompose import android.graphics.Rect import android.graphics.Typeface import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.absoluteOffset import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.rotate import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale import kotlin.math.cos import kotlin.math.sin @Composable fun CustomAnalogClock(textSize: Float, modifier: Modifier) { var boxSize by remember { mutableStateOf(IntSize(0, 0)) } var angleH by remember { mutableStateOf(0.0) } var angleM by remember { mutableStateOf(0.0) } var angleS by remember { mutableStateOf(0.0) } var isDay by remember { mutableStateOf(true) } LaunchedEffect(key1 = "tick") { withContext(Dispatchers.IO) { while (true) { val calendar = Calendar.getInstance() val h = calendar.get(Calendar.HOUR) val m = calendar.get(Calendar.MINUTE) val s = calendar.get(Calendar.SECOND) val millis = calendar.get(Calendar.MILLISECOND) val angleMillis = (360f / (60f / millis)).toDouble() angleS = (360f / (60f / s)).toDouble() + angleMillis / 1000f angleM = (360f / (60f / m)).toDouble() + angleS / 60f angleH = (360f / (12f / h)).toDouble() + angleM / 12f if (isDay != calendar.get(Calendar.HOUR_OF_DAY) in 6..18) { isDay = calendar.get(Calendar.HOUR_OF_DAY) in 6..18 } delay(100) } } } Box(modifier = modifier .fillMaxSize() .onSizeChanged { boxSize = it } .drawWithContent { drawCircle( color = Color.Black, radius = size.width / 2f, center = Offset(centerX, centerY) ) drawCircle( color = if (isDay) Color.White else Color.DarkGray, radius = size.width / 2.1f ) drawDecorations(isDay) drawClockNumbers(isDay, textSize) drawContent() drawClockHands(isDay, angleS, angleM, angleH) } ) { DrawTodayDate(isDay, textSize, boxSize, modifier) } } @Composable fun DrawTodayDate( isDay: Boolean, textSize: Float, boxSize: IntSize, modifier: Modifier = Modifier ) { val calendar = SimpleDateFormat("EEE, dd.MM.yyy", Locale.getDefault()) var calendarTextSize by remember { mutableStateOf(IntSize(0, 0)) } Text( text = calendar.format(Date()), fontSize = textSize.sp, color = if (isDay) Color.Black else Color.White, modifier = modifier .onSizeChanged { calendarTextSize = it } .absoluteOffset { IntOffset( boxSize.width / 2 - calendarTextSize.width / 2, boxSize.height / 2 + calendarTextSize.height / 2 ) } .background( color = if (isDay) Color.LightGray else Color.Black, shape = RoundedCornerShape(16f) ) .padding(12.dp) ) } val DrawScope.centerX get() = size.width / 2 val DrawScope.centerY get() = size.height / 2 fun DrawScope.drawClockNumbers(isDay: Boolean, commonTextSize: Float) { drawIntoCanvas { for (i in 0..11) { val x = size.width / 2.5f * cos(Math.toRadians(i * 30.0)) val y = size.width / 2.5f * sin(Math.toRadians(i * 30.0)) val paint = android.graphics .Paint() .apply { isAntiAlias = true textSize = commonTextSize.sp.toPx() color = if (isDay) android.graphics.Color.BLACK else android.graphics.Color.WHITE typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD) } val rect = Rect() val number = if (i > 3) "${i + 9 - 12}" else "${i + 9}" paint.getTextBounds( number, 0, 1, rect ) it.nativeCanvas.drawText( number, centerX - x.toFloat() - rect.width(), centerY - y.toFloat() + rect.height() / 2.5f, paint ) } } } fun DrawScope.drawDecorations(isDay: Boolean) { drawIntoCanvas { for (i in 0..35) { if ((i * 10) % 30 != 0) { drawRect( color = Color.Gray, topLeft = Offset(centerX - 5f, centerY - centerX + 30f), size = Size(7f, 27f) ) } it.rotate(10f, centerX, centerY) } for (i in 0..11) { drawRect( color = if (isDay) Color.Black else Color.White, topLeft = Offset(centerX - 5f, centerY - centerX + 30f), size = Size(20f, 20f) ) it.rotate(30f, centerX, centerY) } } } fun DrawScope.drawClockHands( isDay: Boolean, angleS: Double, angleM: Double, angleH: Double, ) { rotate(90f, Offset(centerX, centerY)) { drawHandHours(isDay, angleH) drawHandMinutes(isDay, angleM) drawHandSeconds(angleS) } drawCircle( radius = 15f, brush = Brush.radialGradient( colors = listOf(Color.White, Color.DarkGray), radius = 15f, center = Offset(centerX, centerY) ) ) } fun DrawScope.drawHandSeconds(angle: Double) { val xs = size.width / 2.2f * cos(Math.toRadians(angle)) val ys = size.width / 2.2f * sin(Math.toRadians(angle)) drawHand(xs.toFloat(), ys.toFloat(), 10f, Color.Red) } fun DrawScope.drawHandMinutes(isDay: Boolean, angle: Double) { val xm = size.width / 2.5f * cos(Math.toRadians(angle)) val ym = size.width / 2.5f * sin(Math.toRadians(angle)) val color = if (isDay) Color.Black else Color.White drawHand(xm.toFloat(), ym.toFloat(), 20f, color) } fun DrawScope.drawHandHours(isDay: Boolean, angle: Double) { val xh = size.width / 4f * cos(Math.toRadians(angle)) val yh = size.width / 4f * sin(Math.toRadians(angle)) val color = if (isDay) Color.Black else Color.White drawHand(xh.toFloat(), yh.toFloat(), 25f, color) } fun DrawScope.drawHand(x: Float, y: Float, strokeWidth: Float = 10f, color: Color = Color.Black) { drawLine( color = color, start = Offset(centerX, centerY), end = Offset(centerX - x, centerY - y), strokeWidth = strokeWidth ) }
0
Kotlin
0
0
2daf91d402ff2cb8c984666a41feb6120af322cc
8,089
ComposeCanvas
MIT License
src/main/kotlin/no/nav/plugins/AuthorizationPlugin.kt
navikt
644,356,194
false
{"Kotlin": 144621, "Dockerfile": 214}
package no.nav.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.response.* import no.nav.konfigurasjon.Miljø import no.nav.arbeidsgiver.altinnrettigheter.proxy.klient.AltinnrettigheterProxyKlient import no.nav.arbeidsgiver.altinnrettigheter.proxy.klient.AltinnrettigheterProxyKlientConfig import no.nav.arbeidsgiver.altinnrettigheter.proxy.klient.ProxyConfig import no.nav.arbeidsgiver.altinnrettigheter.proxy.klient.model.Subject import no.nav.arbeidsgiver.altinnrettigheter.proxy.klient.model.TokenXToken import no.nav.tokenx.TokenExchanger import no.nav.utvidelser.hentToken import no.nav.utvidelser.orgnr import no.nav.utvidelser.tokenSubject val AuthorizationPlugin = createRouteScopedPlugin( name = "AuthorizationPlugin", ) { pluginConfig.apply { on(AuthenticationChecked) { call -> val fnr = call.request.tokenSubject() ?: return@on call.respond(HttpStatusCode.Forbidden) val token = call.request.hentToken() ?: return@on call.respond(HttpStatusCode.Forbidden) val orgnr = call.orgnr ?: return@on call.respond(HttpStatusCode.BadRequest) val altinnKlient = AltinnrettigheterProxyKlient( AltinnrettigheterProxyKlientConfig( ProxyConfig("fia-arbeidsgiver", Miljø.altinnProxyUrl) ) ) val virksomheterSomBrukerHarTilgangTil = altinnKlient.hentOrganisasjoner( TokenXToken( TokenExchanger.exchangeToken( token = token, audience = Miljø.altinnRettigheterProxyClientId ) ), Subject(fnr), true ) if (virksomheterSomBrukerHarTilgangTil.none { it.organizationNumber == orgnr }) call.respond(status = HttpStatusCode.Forbidden, message = "Ikke tilgang til orgnummer") } } }
0
Kotlin
0
0
8a989c597decde90ba7375d7f8b3442724d9ac38
1,985
fia-arbeidsgiver
MIT License
authentication/authentication-core/src/commonMain/kotlin/tz/co/asoft/services/IUsersService.core.ktx.kt
aSoft-Ltd
332,933,351
false
null
@file:Suppress("PackageDirectoryMismatch") package tz.co.asoft fun IUsersService.load(loginId: String, password: String) = scope.later { if (loginId.contains("@")) { load(Email(loginId), password).await() } else { load(Phone(loginId), password).await() } } /** * Sign in the respective user * @return [Either] [User] or <JWT Token> as [String] */ fun IUsersService.signIn(loginId: String, password: String): Later<Either<User, String>?> = scope.later { val user = load( loginId = loginId, password = password ).await() ?: return@later null if (user.accounts.size == 1) { val userId = user.uid ?: return@later null val account = user.accounts.firstOrNull() val accountId = account?.uid ?: return@later null return@later authenticate(accountId, userId).await().asEither() } return@later user.asEither() } fun IUsersService.register( userAccountUID: String? = null, accountType: UserAccount.Type, accountName: String, userFullname: String, userUID: String? = null, username: String? = null, email: Email, phone: Phone, password: ByteArray ): Later<Pair<UserAccount, User>> = scope.later { val account = UserAccount( uid = userAccountUID, name = accountName, type = accountType.name, scope = null ) val newAccount: UserAccount = accountsDao.create(account).await() val user = User( uid = userUID, username = username, name = userFullname, password = SHA256.digest(password).hex, emails = listOf(email.value), phones = listOf(phone.value), accounts = listOf(newAccount) ) val newUser = create(user).await() val claim = Claim( uid = "${newAccount.uid}-user-${newUser.uid}", permits = accountType.permissionGroups.flatMap { it.permissions }.map { it.title } ) claimsDao.create(claim).await() newAccount to newUser } fun IUsersService.addUserToAccount(account: UserAccount, userId: String): Later<User> = scope.later { val user = load(userId).await() ?: throw Exception("Failed to load User(uid=$userId)") edit(user.copy(accounts = user.accounts + account)).await() }
2
Kotlin
1
1
3bb2304e1fdfa9a96ae1f693cf6c4527cd50dab5
2,253
auth
MIT License
platform/src/test/kotlin/com/samsung/healthcare/platform/application/service/project/GetInLabVisitServiceTest.kt
S-HealthStack
520,365,362
false
{"Kotlin": 894766, "Dockerfile": 1358, "ANTLR": 1066}
package com.samsung.healthcare.platform.application.service.project import com.samsung.healthcare.account.application.context.ContextHolder import com.samsung.healthcare.account.domain.AccessInLabVisitAuthority import com.samsung.healthcare.account.domain.Account import com.samsung.healthcare.account.domain.Email import com.samsung.healthcare.account.domain.Role import com.samsung.healthcare.platform.NEGATIVE_TEST import com.samsung.healthcare.platform.POSITIVE_TEST import com.samsung.healthcare.platform.application.authorize.Authorizer import com.samsung.healthcare.platform.application.exception.ForbiddenException import com.samsung.healthcare.platform.application.exception.NotFoundException import com.samsung.healthcare.platform.application.port.output.project.InLabVisitOutputPort import com.samsung.healthcare.platform.domain.Project import com.samsung.healthcare.platform.domain.project.InLabVisit import io.mockk.coEvery import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.reactor.mono import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import reactor.core.publisher.Mono import java.time.LocalDateTime @kotlinx.coroutines.ExperimentalCoroutinesApi internal class GetInLabVisitServiceTest { private val inLabVisitOutputPort = mockk<InLabVisitOutputPort>() private val getInLabVisitService = GetInLabVisitService(inLabVisitOutputPort) private val projectId = Project.ProjectId.from(1) val account = Account( "account-id", Email("[email protected]"), listOf(Role.ProjectRole.ResearchAssistant(projectId.value.toString())) ) @Test @Tag(NEGATIVE_TEST) fun `getInLabVisitById should throw forbidden when account do not have project authority`() = runTest { mockkObject(ContextHolder) val wrongProjectId = Project.ProjectId.from(2) every { ContextHolder.getAccount() } returns Mono.just(account) assertThrows<ForbiddenException>("should throw a forbidden exception") { getInLabVisitService.getInLabVisitById(wrongProjectId.toString(), 1) } } @Test @Tag(NEGATIVE_TEST) fun `getInLabVisitById should throw not found when no data found for given id`() = runTest { val inLabVisitId = 1 mockkObject(Authorizer) every { Authorizer.getAccount(AccessInLabVisitAuthority(projectId.toString())) } returns mono { account } coEvery { inLabVisitOutputPort.findById(inLabVisitId) } returns null assertThrows<NotFoundException>("should throw a not found exception") { getInLabVisitService.getInLabVisitById(projectId.value.toString(), inLabVisitId) } } @Test @Tag(POSITIVE_TEST) fun `getInLabVisitById should work properly`() = runTest { val time = LocalDateTime.now() val inLabVisitId = 1 val inLabVisit = InLabVisit(inLabVisitId, "u1", "c1", time, time, null, "") mockkObject(Authorizer) every { Authorizer.getAccount(AccessInLabVisitAuthority(projectId.toString())) } returns mono { account } coEvery { inLabVisitOutputPort.findById(inLabVisitId) } returns inLabVisit val response = getInLabVisitService.getInLabVisitById( projectId.value.toString(), inLabVisitId, ) Assertions.assertThat(response).isEqualTo(inLabVisit) } @Test @Tag(NEGATIVE_TEST) fun `getInLabVisits should throw forbidden when account do not have project authority`() = runTest { mockkObject(ContextHolder) val wrongProjectId = Project.ProjectId.from(2) every { ContextHolder.getAccount() } returns Mono.just(account) assertThrows<ForbiddenException>("should throw a forbidden exception") { getInLabVisitService.getInLabVisits(wrongProjectId.toString()) } } @Test @Tag(POSITIVE_TEST) fun `getInLabVisits should work properly`() = runTest { mockkObject(Authorizer) every { Authorizer.getAccount(AccessInLabVisitAuthority(projectId.toString())) } returns mono { account } coEvery { inLabVisitOutputPort.findAll() } returns emptyFlow() val response = getInLabVisitService.getInLabVisits( projectId.value.toString(), ) Assertions.assertThat(response).isEqualTo(emptyFlow<InLabVisit>()) } }
2
Kotlin
7
28
b7e7d0b4cc8d1f1123c9f3bd08fa5cc66fbc9920
4,597
backend-system
Apache License 2.0
src/ide/intellij-plugin/src/main/kotlin/community/flock/wirespec/ide/intellij/Annotator.kt
flock-community
506,356,849
false
{"Kotlin": 656506, "Shell": 6544, "TypeScript": 5819, "Witcher Script": 4248, "Java": 4221, "Dockerfile": 625, "Makefile": 501, "JavaScript": 140}
package community.flock.wirespec.ide.intellij import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.ExternalAnnotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import community.flock.wirespec.compiler.core.WirespecSpec import community.flock.wirespec.compiler.core.exceptions.WirespecException import community.flock.wirespec.compiler.core.parse.AST import community.flock.wirespec.compiler.core.parse.Parser import community.flock.wirespec.compiler.core.tokenize.tokenize import community.flock.wirespec.compiler.core.validate.validate import community.flock.wirespec.compiler.utils.noLogger import kotlinx.coroutines.runBlocking class Annotator : ExternalAnnotator<List<WirespecException>, List<WirespecException>>() { override fun collectInformation(file: PsiFile) = runBlocking { WirespecSpec.tokenize(file.text) .let(Parser(noLogger)::parse) .map(AST::validate) .fold({ it }, { emptyList() }) } override fun doAnnotate(collectedInfo: List<WirespecException>?) = collectedInfo override fun apply(file: PsiFile, annotationResult: List<WirespecException>?, holder: AnnotationHolder) { annotationResult?.forEach { holder .newAnnotation(HighlightSeverity.ERROR, it.message ?: "") .range( TextRange( it.coordinates.idxAndLength.idx - it.coordinates.idxAndLength.length, it.coordinates.idxAndLength.idx ) ) .create() } super.apply(file, annotationResult, holder) } }
18
Kotlin
2
17
50f8b9a1e341d6d79fdc86f6bff9fca9b32b7579
1,745
wirespec
Apache License 2.0
app/src/main/java/com/evilthreads/smsbackdoor/ui/Preferences.kt
manojvermamv
788,954,217
false
{"Kotlin": 21380}
package com.evilthreads.smsbackdoor.ui import android.content.Context import androidx.preference.PreferenceManager class Preferences(context: Context) { private val pref by lazy { PreferenceManager.getDefaultSharedPreferences(context) } fun getCity() = pref.getString("cityName", "") ?: "" fun setCity(cityName: String) { pref.edit().putString("cityName", cityName).apply() } }
0
Kotlin
0
0
933706bef22290409bc4841ece6bd4c6ab662ddd
419
Github-People-Finder
Apache License 2.0
domain/src/main/java/com/anytypeio/anytype/domain/account/AwaitAccountStartManager.kt
anyproto
647,371,233
false
{"Kotlin": 11326068, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.domain.account import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow interface AwaitAccountStartManager { fun isStarted(): Flow<Boolean> fun setIsStarted(isStarted: Boolean) object Default: AwaitAccountStartManager { private val isStarted = MutableStateFlow(false) override fun isStarted(): Flow<Boolean> = isStarted override fun setIsStarted(isStarted: Boolean) { this.isStarted.value = isStarted } } }
41
Kotlin
40
490
70d453579f4fceacf8a96683671cc9b1b01ad13e
525
anytype-kotlin
RSA Message-Digest License
core/src/main/java/me/tatocaster/core/source/local/covidstats/CovidStatDbEntity.kt
tatocaster
253,899,293
false
null
package me.tatocaster.core.source.local.covidstats import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "covid_stats") data class CovidStatDbEntity( @PrimaryKey @ColumnInfo(name = "country") val country: String, @ColumnInfo(name = "total_confirmed") val totalConfirmed: Int, @ColumnInfo(name = "total_death") val totalDeaths: Int, @ColumnInfo(name = "total_recovered") val totalRecovered: Int )
0
Kotlin
0
3
32c3eab1e0f544d75457bc5300d82a38b91e7126
494
covid19-IoT
MIT License
app/src/main/java/com/breezefieldaereo/features/stockAddCurrentStock/model/CurrentStockGetData.kt
DebashisINT
876,752,370
false
{"Kotlin": 16011993, "Java": 1030008}
package com.breezefieldaereo.features.stockAddCurrentStock.model import com.breezefieldaereo.features.stockCompetetorStock.model.CompetetorStockGetDataDtls class CurrentStockGetData { var status:String ? = null var message:String ? = null var total_stocklist_count:String ? = null var stock_list :ArrayList<CurrentStockGetDataDtls>? = null }
0
Kotlin
0
0
19b7be34bb719573e71738d1e91a26681a4a7bde
359
Aereo
Apache License 2.0
feature-ui/session-component/src/androidMain/kotlin/com/addhen/fosdem/ui/session/component/AutoSizedCircularProgressIndicatorPreview.kt
eyedol
170,208,282
false
{"Kotlin": 553796, "Shell": 3075, "Swift": 1713}
// Copyright 2023, Addhen Limited and the FOSDEM Event app project contributors // SPDX-License-Identifier: Apache-2.0 package com.addhen.fosdem.ui.session.component import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.size import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.addhen.fosdem.compose.common.ui.api.theme.AppTheme import com.addhen.fosdem.compose.common.ui.api.theme.MultiThemePreviews @MultiThemePreviews @Composable private fun AutoSizedCircularProgressIndicatorPreview() { AppTheme { Surface { Column { AutoSizedCircularProgressIndicator( modifier = Modifier.size(16.dp), ) AutoSizedCircularProgressIndicator( modifier = Modifier.size(24.dp), ) AutoSizedCircularProgressIndicator( modifier = Modifier.size(48.dp), ) AutoSizedCircularProgressIndicator( modifier = Modifier.size(64.dp), ) AutoSizedCircularProgressIndicator( modifier = Modifier.size(128.dp), ) } } } }
5
Kotlin
0
1
6d49f22e380c9d7560f617c0e4a7fb3563a34477
1,197
fosdem-event-app
Apache License 2.0
feature/notes/list/core/src/main/kotlin/ru/maksonic/beresta/feature/notes/list/core/NotesFilterUpdater.kt
maksonic
580,058,579
false
null
package ru.maksonic.beresta.feature.notes.list.core import ru.maksonic.beresta.feature.notes.list.api.ui.NoteUi import ru.maksonic.beresta.feature.notes.list.api.ui.SortedNotes import ru.maksonic.beresta.feature.notes.list.api.ui.sortByAlphabetAsc import ru.maksonic.beresta.feature.notes.list.api.ui.sortByAlphabetDesk import ru.maksonic.beresta.feature.notes.list.api.ui.sortByCreationDateAsc import ru.maksonic.beresta.feature.notes.list.api.ui.sortByCreationDateDesk import ru.maksonic.beresta.feature.notes.list.api.ui.sortUpdateDateAsc import ru.maksonic.beresta.feature.notes.list.api.ui.sortUpdateDateDesk /** * @Author maksonic on 26.05.2023 */ class NotesFilterUpdater(list: List<NoteUi>, private val currentFolderId: Long) { companion object { private const val STICKY_START_FOLDER_ID = 1L private const val STICKY_END_FOLDER_ID = 2L private const val DEFAULT_NOTE_FOLDER_ID = 2L } private val filteredList: NoteUi.Collection = NoteUi.Collection(list.filter { note -> when (currentFolderId) { // When ID == 1L - Showed all notes. STICKY_START_FOLDER_ID -> true // When ID == 2L - Showed notes without folder (category). STICKY_END_FOLDER_ID -> note.folderId == DEFAULT_NOTE_FOLDER_ID else -> note.folderId == currentFolderId } }) private fun NoteUi.Collection.applySort( current: SortedNotes, isSortPinned: Boolean ): NoteUi.Collection = this.copy( when (current) { SortedNotes.ALPHABET_ASC -> this.data.sortByAlphabetAsc(isSortPinned) SortedNotes.ALPHABET_DESC -> this.data.sortByAlphabetDesk(isSortPinned) SortedNotes.DATE_CREATION_ASC -> this.data.sortByCreationDateAsc(isSortPinned) SortedNotes.DATE_CREATION_DESC -> this.data.sortByCreationDateDesk(isSortPinned) SortedNotes.DATE_UPDATE_ASC -> this.data.sortUpdateDateAsc(isSortPinned) SortedNotes.DATE_UPDATE_DESC -> this.data.sortUpdateDateDesk(isSortPinned) } ) fun notesList(current: SortedNotes, isSortPinned: Boolean) = filteredList.applySort(current, isSortPinned) val isEmptyFilterList = filteredList.data.isEmpty() }
0
Kotlin
0
0
b1c3480b9e715f7f02302b955af64cf032e4224a
2,247
Beresta
MIT License
optional/compose/src/main/java/com/pitaya/mobile/uinspector/optional/compose/properties/DefaultComposePropertiesParserFactory.kt
YvesCheung
325,005,910
false
null
package com.pitaya.mobile.uinspector.optional.compose.properties import androidx.compose.ui.Modifier /** * @author YvesCheung * 2021/2/2 */ class DefaultComposePropertiesParserFactory : ComposePropertiesParserFactory { override val uniqueKey: String = "Default" override fun tryCreate(modifier: Modifier): ComposePropertiesParser = DefaultComposePropertiesParser(modifier) }
1
Kotlin
13
132
72c374ba5754cb4aac211cdede9af25b9c2e4b0a
398
UInspector
Apache License 2.0
app/src/main/java/ru/tinkoff/news/main/MainActivity.kt
nikitosbobin
185,379,960
false
null
package ru.tinkoff.news.main import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import ru.tinkoff.news.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tabs.setupWithViewPager(viewPager) viewPager.adapter = NewsFragmentsAdapter(this, supportFragmentManager) } }
0
Kotlin
0
0
aff0d4858776d4363a44f5fbdc1fd1b51200cf52
505
tinkoff-news
Apache License 2.0
src/main/kotlin/io/foxcapades/lib/cli/builder/arg/filter/ArgGeneralDefaultFilter.kt
Foxcapades
850,780,005
false
{"Kotlin": 251181}
package io.foxcapades.lib.cli.builder.arg.filter import io.foxcapades.kt.prop.delegation.Property import io.foxcapades.lib.cli.builder.arg.Argument import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.CharZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.DoubleZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.FloatZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.UByteZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.UIntZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.ULongZero import io.foxcapades.lib.cli.builder.arg.filter.ArgZeroFilter.UShortZero import io.foxcapades.lib.cli.builder.serial.CliSerializationConfig import io.foxcapades.lib.cli.builder.util.BUG import io.foxcapades.lib.cli.builder.util.values.ValueSource import java.math.BigDecimal import java.math.BigInteger import java.util.* import kotlin.time.Duration // null // number // boolean // string // Collection // Array // Map /** * Generalized Defaulted Argument Filter * * Attempts to filter out arguments that are set to their "default" value. * * This filter performs up to 3 types of tests on a given argument to try and * determine whether the [Argument] should be considered as having its "default" * value. * * 1. Is set: if a given argument is not set, the filter will return * `false` for that argument. * 2. Is configured default: if a given, set argument has a configured default * value, and the currently set value is equal to that default, the filter will * return `false` for that argument. * 3. Is default for type: if a given, set argument does not have a configured * default value, the filter will attempt to guess at the default for a small * set of types, primarily consisting of primitives, strings, and collections by * comparing the argument value to the 'zero' value for that type. * * ### Type Based Default Tests * * The following types will be tested for their 'zero' value: * * | Type | Default If | Includes | * |------------|------------|-------------------------------------------------------------------------| * | Number | `0` | all primitive number types, kotlin unsigned types, and `char` * | Boolean | `false` | Boolean * | String | empty | CharSequence, String * | Array | empty | All array types including primitive arrays and kotlin unsigned arrays * | Collection | empty | * | Map | empty | * | Optional | empty | All Java Optional types including primitive options * | Duration | `0` | Both Java and Kotlin durations * | Property | empty | cli-builder Property implementations and subtypes * * @since 1.0.0 */ internal object ArgGeneralDefaultFilter : ArgumentPredicate<Any?> { override fun shouldInclude(argument: Argument<Any?>, config: CliSerializationConfig, source: ValueSource) = when { !argument.isSet -> false argument.hasDefault -> argument.getDefault() != argument.get() else -> !valueIsDefault(argument.get()) } @Suppress("NAME_SHADOWING") @OptIn(ExperimentalUnsignedTypes::class) private fun valueIsDefault(value: Any?): Boolean { val value = (value ?: return true) return when (value.javaClass.packageName) { null -> BUG() "java.lang" -> when (value) { is Number -> when (value) { is Double -> value == DoubleZero is Float -> value == FloatZero else -> value.toLong() == 0L } is Boolean -> value == false is CharSequence -> value.isEmpty() is Char -> value == CharZero is Array<*> -> value.isEmpty() is IntArray -> value.isEmpty() is DoubleArray -> value.isEmpty() is ByteArray -> value.isEmpty() is CharArray -> value.isEmpty() is LongArray -> value.isEmpty() is BooleanArray -> value.isEmpty() is FloatArray -> value.isEmpty() is ShortArray -> value.isEmpty() else -> false } "java.util" -> when (value) { is Collection<*> -> value.isEmpty() is Map<*, *> -> value.isEmpty() is Optional<*> -> value.isEmpty is OptionalDouble -> value.isEmpty is OptionalInt -> value.isEmpty is OptionalLong -> value.isEmpty is Dictionary<*, *> -> value.isEmpty else -> false } "kotlin" -> when (value) { is UInt -> value == UIntZero is ULong -> value == ULongZero is UByte -> value == UByteZero is UShort -> value == UShortZero is UIntArray -> value.isEmpty() is ULongArray -> value.isEmpty() is UByteArray -> value.isEmpty() is UShortArray -> value.isEmpty() else -> false } else -> when(value) { is BigDecimal -> value == BigDecimal.ZERO is BigInteger -> value == BigInteger.ZERO is Property<*> -> false is Duration -> value == Duration.ZERO is java.time.Duration -> value.isZero else -> false } } } }
8
Kotlin
0
0
1b45c0e4ffa914ecc9c53356aa9d276a6d5aa6b7
5,265
lib-kt-cli-builder
MIT License
app/src/main/java/com/gibranlyra/cstv/domain/model/MatchData.kt
GibranLyra
728,812,322
false
{"Kotlin": 130559}
package com.gibranlyra.cstv.domain.model import android.os.Parcelable import com.gibranlyra.cstv.data.entity.MatchStatus import kotlinx.parcelize.Parcelize @Parcelize data class MatchData( val id: Int, val leagueImageUrl: String = "", val team1Id: Int = -1, val team1Name: String = "", val team1Image: PandaImage = PandaImage(), val team2Id: Int = -1, val team2Name: String = "", val team2Image: PandaImage = PandaImage(), val matchStatus: MatchStatus = MatchStatus.NOT_STARTED, val isFinished: Boolean = false, val beginAt: String = "", val leagueName: String = "", val serieName: String = "", ) : Parcelable
0
Kotlin
0
0
c93d8746b9aa25aa5324a17622f4c6ffa26e522d
664
CsTv
MIT License
app/src/main/java/github/com/st235/bitobserver/components/LineChartAdapter.kt
st235
206,961,424
false
null
package github.com.st235.bitobserver.components import android.graphics.RectF import github.com.st235.bitobserver.utils.ObservableModel import kotlin.math.max import kotlin.math.min /** * Line chart data adapter. * Helps load data into the chart view. */ abstract class LineChartAdapter: ObservableModel<Unit>() { abstract fun getSize(): Int open fun getX(index: Int): Float = index.toFloat() abstract fun getY(index: Int): Float abstract fun getData(index: Int): Any fun calculateBounds(): RectF { var minX = Float.MAX_VALUE var maxX = Float.MIN_VALUE var minY = Float.MAX_VALUE var maxY = Float.MIN_VALUE for (i in 0 until getSize()) { val x = getX(i) val y = getY(i) minX = min(x, minX) maxX = max(x, maxX) minY = min(y, minY) maxY = max(y, maxY) } return RectF(minX, minY, maxX, maxY) } }
0
Kotlin
0
0
7dfd8600be1e34257b7fb990a2598c791cf84886
958
BitObserver
MIT License
android/app/src/main/java/net/rf43/bizzyplanets/api/TempApiData.kt
rf43
641,101,112
false
null
package net.rf43.bizzyplanets.api import net.rf43.bizzyplanets.data.models.Planet object TempApiData { val planetList: List<Planet> = listOf( Planet( name = "Mercury", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/mercury_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/mercury_hero.jpg" ), Planet( name = "Venus", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/venus_thumb.png", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/venus_hero.jpg" ), Planet( name = "Earth", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/earth_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/earth_hero.jpg" ), Planet( name = "Mars", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/mars_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/mars_hero.jpg" ), Planet( name = "Jupiter", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/jupiter_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/jupiter_hero.jpg" ), Planet( name = "Saturn", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/saturn_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/saturn_hero.jpg" ), Planet( name = "Uranus", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/uranus_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/uranus_hero.jpg" ), Planet( name = "Neptune", thumbUrl = "https://rf43.github.io/bizzy-planets/assets/images/neptune_thumb.jpg", heroUrl = "https://rf43.github.io/bizzy-planets/assets/images/neptune_hero.jpg" ) ) }
0
Kotlin
0
1
274ca54992c6f582913a17a71409773f4cffa234
2,079
bizzy-planets
MIT License
app/src/main/java/dev/christopheredwards/openperiod/data/PeriodDatabase.kt
cedwards036
490,478,497
false
null
package dev.christopheredwards.openperiod.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database(entities = [PDate::class], views = [Period::class], version = 1, exportSchema = false) @TypeConverters(Converters::class) abstract class PeriodDatabase : RoomDatabase() { abstract val periodDao: PeriodDao companion object { @Volatile private var INSTANCE: PeriodDatabase? = null fun getInstance(context: Context): PeriodDatabase { synchronized(this) { var instance = INSTANCE if (instance == null) { instance = Room.databaseBuilder( context.applicationContext, PeriodDatabase::class.java, "period_database" ).fallbackToDestructiveMigration().build() INSTANCE = instance } return instance } } } }
0
Kotlin
0
2
392f5b1bb94210fd872947ee05ff748aed69115c
1,079
OpenPeriod
MIT License
test/TestHostShebang.kt
square
808,742,641
false
{"Kotlin": 124508, "C": 78423, "Shell": 21547, "C++": 15502, "Makefile": 2014}
#!/usr/bin/env stoic shebang --host -- package shebang import com.square.stoic.print.* fun main(args: List<String>): Int { println("args: $args") return 0 }
0
Kotlin
1
5
7ec84827834a1dc0e6f5f98c91a9258dbfcf0153
163
stoic
Apache License 2.0
src/main/kotlin/com/dedztbh/kuantum/jblas/matrix/type.kt
dedztbh
297,601,599
false
{"Kotlin": 67634}
package com.dedztbh.kuantum.jblas.matrix import org.jblas.ComplexDouble import org.jblas.ComplexDoubleMatrix /** * Created by DEDZTBH on 2020/09/25. * Project KuantumCircuitSim */ typealias CMatrix = ComplexDoubleMatrix typealias CNum = ComplexDouble
0
Kotlin
0
2
7d4503dad2f6218ba162360d6a9a9fad997f2263
257
KuantumCircuitSim
MIT License
app/src/test/java/com/pedrogomez/taskfollower/repository/TasksManagerTest.kt
makhnnar
382,434,932
false
null
package com.pedrogomez.taskfollower.repository import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.pedrogomez.taskfollower.domian.view.TaskVM import com.pedrogomez.taskfollower.repository.datastore.DSRepository import com.pedrogomez.taskfollower.repository.db.DBRepository import com.pedrogomez.taskfollower.utils.getOrAwaitValue import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.Assert.* import org.junit.Rule import org.junit.rules.TestRule import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.verify @RunWith(MockitoJUnitRunner::class) class TasksManagerTest { private val TASK: TaskVM = TaskVM() private val LIST = listOf( TASK ) private val LDLIST : LiveData<List<TaskVM>> = MutableLiveData( LIST ) private val ID: Long = 1 private lateinit var SUT : TasksManager @Mock lateinit var DBMock: DBRepository @Mock lateinit var DSMock: DSRepository @get:Rule var rule: TestRule = InstantTaskExecutorRule() @Before fun setUp() { SUT = TasksManager( DBMock, DSMock ) } @Test fun deleteSelected() { runBlocking { successTaskId() SUT.deleteSelected() verify(DSMock).selectedTaskId() verify(DBMock).deleteTaskById(ID) } } @Test fun setSelected() { runBlocking { SUT.setSelected(ID) verify(DSMock).setSelectedTaskId(ID) } } @Test fun selected() { runBlocking { successTaskId() SUT.selected() verify(DSMock).selectedTaskId() verify(DBMock).getTaskById(ID) } } @Test fun tasks() { runBlocking { successTaskList() val result = SUT.tasks() verify(DBMock).tasks() assertEquals( result.getOrAwaitValue(), LDLIST.getOrAwaitValue() ) } } @Test fun addTask() { runBlocking { SUT.addTask(TASK) verify(DBMock).addTask(TASK) } } @Test fun updateTask() { runBlocking { SUT.updateTask(TASK) verify(DBMock).updateTask(TASK) } } @Test fun deleteTask() { runBlocking { SUT.deleteTask(TASK) verify(DBMock).deleteTask(TASK) } } suspend fun successTaskId(){ Mockito.`when`(DSMock.selectedTaskId()).thenReturn(ID) } fun successTaskList(){ Mockito.`when`(DBMock.tasks()).thenReturn(LDLIST) } }
2
Kotlin
0
0
3dfb1d4d91496b80678c24239bbb25dfe03f28d8
2,872
taskFollower
MIT License
src/main/java/tk/bteitalia/core/feature/fixdh/FixDHListener.kt
BuildTheEarth-Italy
522,082,660
false
null
package tk.bteitalia.core.feature.fixdh import com.sk89q.worldguard.bukkit.WorldGuardPlugin import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerJoinEvent import tk.bteitalia.core.BTEItalyCorePlugin import tk.bteitalia.core.config.FixDHConfig import tk.bteitalia.core.worldguard.WGRegionEnterEvent import kotlin.math.max internal class FixDHListener( private val corePlugin: BTEItalyCorePlugin, private val worldGuardPlugin: WorldGuardPlugin, private val config: FixDHConfig ) : Listener { private fun reloadDH() { val ticksDelay = max(0, (config.delay * 20).toLong()) corePlugin.server.scheduler.scheduleSyncDelayedTask(corePlugin, { val console = corePlugin.server.consoleSender for (command in config.executeCommands) { corePlugin.server.dispatchCommand(console, command) } }, ticksDelay) } @EventHandler(ignoreCancelled = true) fun onWGRegionEnter(event: WGRegionEnterEvent) { if (!config.enabled) return val name = event.region.id for (regionName in config.regions) { if (name.equals(regionName, ignoreCase = true)) { reloadDH() return } } } @EventHandler(ignoreCancelled = true) fun onPlayerJoin(event: PlayerJoinEvent) { if (!config.enabled) return val regions = worldGuardPlugin.regionContainer.get(event.player.world) ?: return val spawnRegions = regions.regions.values.filter { it.id.equals("newspawn", ignoreCase = true) } val location = event.player.location for (region in spawnRegions) { if (!region.contains(location.blockX, location.blockY, location.blockZ)) continue for (regionName in config.regions) { reloadDH() return } } } }
2
Kotlin
0
3
5246c3ba6838eb4d49d92001a8fb7753a3aaff12
1,936
BTE-Italia-Core
MIT License
runtime/src/commonMain/kotlin/org/szkug/krpc/service/Call.kt
szkug
737,588,200
false
{"Kotlin": 15732}
package org.szkug.krpc.service interface Call { suspend operator fun invoke(serviceName: String, functionName: String, requestData: ByteArray): ByteArray }
0
Kotlin
0
2
e4a6de31369d80306c8d4d6538902f01fd934b4a
161
krpc
Apache License 2.0
app/src/main/java/com/jetbrains/handson/mpp/mobile/ShowListActivity.kt
jakepurple13
205,208,550
false
null
package com.jetbrains.handson.mpp.mobile import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.programmerbox.dragswipe.DragSwipeAdapter import kotlinx.android.synthetic.main.activity_show_list.* import kotlinx.android.synthetic.main.show_layout.view.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class ShowListActivity : AppCompatActivity() { lateinit var list: ArrayList<ShowInfo> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show_list) val source = Source.getSourceFromUrl(intent.getStringExtra("show_type")!!) val dividerItemDecoration = DividerItemDecoration( show_list.context, (show_list.layoutManager as LinearLayoutManager).orientation ) dividerItemDecoration.drawable?.setTint(Color.GRAY) show_list.addItemDecoration(dividerItemDecoration) show_list.requestFocus() searchList.findViewById<EditText>(R.id.search_src_text).isEnabled = false searchList.queryHint = "Search Shows in $source" GlobalScope.launch { val s = ShowApi(source) list = s.showInfoList as ArrayList<ShowInfo> runOnUiThread { show_list.adapter = ShowAdapter(list, this@ShowListActivity) searchList.findViewById<EditText>(R.id.search_src_text).isEnabled = true } } searchList.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String?): Boolean { show_list.adapter = ShowAdapter(list.filter { it.name.contains( newText ?: "", true ) } as ArrayList<ShowInfo>, this@ShowListActivity) return true } override fun onQueryTextSubmit(query: String?): Boolean { return true } }) } } class ShowAdapter(list: ArrayList<ShowInfo>, val context: Context) : DragSwipeAdapter<ShowInfo, ViewHolder>(list) { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.text.text = list[position].name holder.itemView.setOnClickListener { context.startActivity(Intent(context, EpisodeActivity::class.java).apply { putExtra("episode_link", list[position].url) putExtra("episode_name", list[position].name) }) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.show_layout, parent, false)) } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val text: TextView = itemView.textView!! }
0
Kotlin
0
0
37cad33a42fd7e4b30f51ba2bb2cbd38a45cb43e
3,424
iOS-Android-MPP-Modified
Apache License 2.0
domain/src/main/java/com/thisissadeghi/player/domain/model/video/Video.kt
ThisIsSadeghi
349,978,175
false
null
package com.thisissadeghi.player.domain.model.video import com.thisissadeghi.player.domain.model.base.Entity /** * Created by Ali Sadeghi * on 05,Mar,2021 */ data class Video( val id: Int, val title: String, val url: String ) : Entity
0
Kotlin
1
2
19baea79b47e18bf284b0bc24e70f3798ea46123
252
CleanVideoPlayer
MIT License
app/src/main/java/com/deonolarewaju/product_catalogue/data/remote/datasources/interfaces/IProductRDS.kt
deonwaju
729,797,385
false
{"Kotlin": 48833}
package com.deonolarewaju.product_catalogue.data.remote.datasources.interfaces import com.deonolarewaju.product_catalogue.domain.model.ProductsList interface IProductRDS { suspend fun fetchProducts(): ProductsList }
0
Kotlin
0
1
fead009cfd7e36c09d4c8965c768c6b6f12d75d8
221
Product-catalogue
MIT License
app/src/main/java/com/dimitrilc/freemediaplayer/data/source/mediastore/MediaStoreDataSourceImpl.kt
dmitrilc
443,821,454
false
null
package com.dimitrilc.freemediaplayer.data.source.mediastore import android.content.ContentUris import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.provider.MediaStore import android.util.Size import com.dimitrilc.freemediaplayer.data.entities.MediaItem import com.dimitrilc.freemediaplayer.isSameOrAfterQ import dagger.hilt.android.qualifiers.ApplicationContext import java.io.FileNotFoundException import javax.inject.Inject class MediaStoreDataSourceImpl @Inject constructor(@ApplicationContext private val appContext: Context) : MediaStoreDataSource { override fun queryAudios(): List<MediaItem> { val allAudios = mutableListOf<MediaItem>() val collection = if (isSameOrAfterQ()) { MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) } else { MediaStore.Audio.Media.EXTERNAL_CONTENT_URI } val projection = mutableListOf( MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID ) val selection = null val selectionArgs = null val sortOrder = null appContext.contentResolver.query( collection, projection.toTypedArray(), selection, selectionArgs, sortOrder )?.use { cursor -> val idColIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID) val dataColIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA) val titleColIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE) val albumColIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM) val albumIdColIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID) while (cursor.moveToNext()) { val id = cursor.getLong(idColIndex) val data = cursor.getString(dataColIndex) val uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id ) val displayName = data.substringAfterLast('/') val location = data.substringBeforeLast('/') val albumId = cursor.getInt(albumIdColIndex) val albumArtUri = if (isSameOrAfterQ()){ uri.toString() } else { getAlbumArtUriBeforeQ(albumId) } val audio = MediaItem( mediaItemId = id, uri = uri, data = data, displayName = displayName, title = cursor.getString(titleColIndex), location = location, isAudio = true, album = cursor.getString(albumColIndex), albumId = albumId, albumArtUri = albumArtUri ) allAudios.add(audio) } } return allAudios } override fun queryVideos(): List<MediaItem> { val allVideos = mutableListOf<MediaItem>() val collection = if (isSameOrAfterQ()) { MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) } else { MediaStore.Video.Media.EXTERNAL_CONTENT_URI } val projection = mutableListOf( MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE, MediaStore.Video.Media.ALBUM, MediaStore.Video.Media.DATA ) val selection = null val selectionArgs = null val sortOrder = null appContext.contentResolver.query( collection, projection.toTypedArray(), selection, selectionArgs, sortOrder )?.use { cursor -> val idColIndex = cursor.getColumnIndex(MediaStore.Video.Media._ID) val dataColIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATA) val titleColIndex = cursor.getColumnIndex(MediaStore.Video.Media.TITLE) val albumColIndex = cursor.getColumnIndex(MediaStore.Video.Media.ALBUM) while (cursor.moveToNext()) { val id = cursor.getLong(idColIndex) val data = cursor.getString(dataColIndex) val uri = ContentUris.withAppendedId( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id ) val displayName = data.substringAfterLast('/') val location = data.substringBeforeLast('/') val video = MediaItem( mediaItemId = id, uri = uri, data = data, displayName = displayName, title = cursor.getString(titleColIndex), location = location, isAudio = false, album = cursor.getString(albumColIndex), albumId = -1, albumArtUri = uri.toString() ) allVideos.add(video) } } return allVideos } override fun getThumbnail(artUri: String?, videoId: Long?): Bitmap? { fun getVideoThumbBeforeQ(videoId: Long): Bitmap? { return MediaStore.Video.Thumbnails.getThumbnail( appContext.contentResolver, videoId, MediaStore.Video.Thumbnails.MINI_KIND, null ) } var thumbnail: Bitmap? = null if (isSameOrAfterQ()) { try { thumbnail = appContext.contentResolver.loadThumbnail( Uri.parse(artUri), Size(300, 300), null ) } catch (e: FileNotFoundException) { } } else { thumbnail = if (videoId == null) { BitmapFactory.decodeFile(artUri) } else { getVideoThumbBeforeQ(videoId) } } return thumbnail } override fun getAlbumArtUriBeforeQ(albumId: Int): String? { val collection = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI val projection = arrayOf( MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART ) val selection = "${MediaStore.Audio.Albums._ID} = ?" val selectionArgs = arrayOf("$albumId") val sortOrder = null var albumArtUri: String? = null appContext.contentResolver.query( collection, projection, selection, selectionArgs, sortOrder )?.use { cursor -> val albumArtColIndex = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART) while (cursor.moveToNext()) { albumArtUri = cursor.getString(albumArtColIndex) } } return albumArtUri } }
15
Kotlin
0
1
dbdc5a2b4f3875fc71f405723ccf1a4a18116110
7,276
FreeMediaPlayer
MIT License
compiler/src/main/java/promise/database/compiler/TableSerializerMethodGenerator.kt
android-promise
243,376,957
false
null
/* * Copyright 2017, <NAME> * Licensed under the Apache License, Version 2.0, Android Promise. * 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 promise.database.compiler import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.MethodSpec import promise.database.compiler.utils.ConverterTypes import promise.database.compiler.utils.JavaUtils import promise.database.compiler.utils.capitalizeFirst import promise.database.compiler.utils.checkIfHasTypeConverter import promise.database.compiler.utils.getConverterCompatibleMethod import promise.database.compiler.utils.isElementAnnotatedAsRelation import promise.database.compiler.utils.isSameAs import promise.database.compiler.utils.toTypeName import javax.lang.model.element.Element import javax.lang.model.element.Modifier class TableSerializerMethodGenerator( private val typeDataTypePack: String, private val typeDataType: String, private val columns: List<Pair<Pair<String, Element>, String>>) : CodeGenerator<MethodSpec> { override fun generate(): MethodSpec { val codeBlock = CodeBlock.builder() codeBlock.addStatement("ContentValues values = new ContentValues()") columns.forEach { generatePutStatement(codeBlock, it.first.first, it.second, it.first.second) } codeBlock.addStatement("return values") return MethodSpec.methodBuilder("serialize") .addModifiers(Modifier.PUBLIC) .addParameter(ClassName.get(typeDataTypePack, typeDataType), "t") .addAnnotation(Override::class.java) .returns(ClassName.get("android.content", "ContentValues")) .addCode(codeBlock.build()) .build() } private fun generatePutStatement( codeBlock: CodeBlock.Builder, typeVariable: String, columnName: String, varTypeName: Element) { if (varTypeName.toTypeName().isSameAs(Boolean::class.java)) { codeBlock.addStatement("values.put(${columnName}.getName(), t.is${typeVariable.capitalizeFirst()}() ? 1 : 0)") return } if (varTypeName.checkIfHasTypeConverter()) { val executableFn = varTypeName.getConverterCompatibleMethod(ConverterTypes.SERIALIZER) if (executableFn != null) codeBlock.addStatement("values.put(${columnName}.getName(), typeConverter.${executableFn.simpleName}(t.get${typeVariable.capitalizeFirst()}()))") } else if (varTypeName.isElementAnnotatedAsRelation()) codeBlock.add(JavaUtils.generateSerializerRelationPutStatement(varTypeName, columnName)) else codeBlock.addStatement("values.put(${columnName}.getName(), t.get${typeVariable.capitalizeFirst()}())") } }
1
Kotlin
0
11
65208fab30e3ef2f1c71617e4403a2153b687084
3,073
database
Apache License 2.0
mp3recorder/src/main/java/io/j99/library/mp3recorder/Mp3Recorder.kt
hpdx
377,374,252
true
{"C": 793032, "Kotlin": 17217, "Java": 1336, "CMake": 585}
package io.j99.library.mp3recorder import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import android.os.Handler import android.os.Looper import android.os.Message import android.util.Log import io.j99.library.mp3recorder.LameEncoder.init import io.j99.library.mp3recorder.Mp3Recorder import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.OutputStream /** * @author henjue [email protected] */ class Mp3Recorder constructor( val os: OutputStream, val samplingRate: Int = DEFAULT_SAMPLING_RATE, val channelConfig: Int = AudioFormat.CHANNEL_IN_MONO, val audioFormat: PCMFormat =PCMFormat.PCM_16BIT) { var audioRecord: AudioRecord? = null private var bufferSize = 0 private var ringBuffer: RingBuffer? = null private var buffer: ByteArray?=null private var encodeThread: DataEncodeThread? = null private var isRecording = false interface OnProcessListener{ fun onRecordStart() fun onRecordCompleted(); fun onError(e:Throwable); } var listener:OnProcessListener?=null /** * Default constructor. Setup recorder with default sampling rate 1 channel, * 16 bits pcm * * @param file output file */ constructor(file: File, samplingRate: Int = DEFAULT_SAMPLING_RATE, channelConfig: Int = AudioFormat.CHANNEL_IN_MONO, audioFormat: PCMFormat = PCMFormat.PCM_16BIT) : this(FileOutputStream(file), samplingRate, channelConfig, audioFormat) { } var handler:Handler = Handler(Looper.getMainLooper()) /** * Start recording. Create an encoding thread. Start record from this * thread. * * @throws IOException IOException */ @Throws(IOException::class) fun startRecording() { if (isRecording) return Log.d(TAG, "Start recording") Log.d(TAG, "BufferSize = $bufferSize") // Initialize audioRecord if it's null. if (audioRecord == null) { initAudioRecorder() } audioRecord?.startRecording() object : Thread() { override fun run() { isRecording = true handler.post { listener?.onRecordStart() } while (isRecording) { val bytes = buffer?.let { audioRecord?.read(it, 0, bufferSize) }?:0 if (bytes > 0) { buffer?.let { ringBuffer?.write(it, bytes) } } } // release and finalize audioRecord try { audioRecord?.stop() audioRecord?.release() audioRecord = null // stop the encoding thread and try to wait // until the thread finishes its job val msg = Message.obtain(encodeThread?.getHandler(), DataEncodeThread.PROCESS_STOP) msg.sendToTarget() encodeThread?.join() handler.post { listener?.onRecordCompleted() } } catch (e: InterruptedException) { Log.d(TAG, "Faile to join encode thread") handler.post{ listener?.onError(e) } } finally { try { os.close() } catch (e: IOException) { e.printStackTrace() } } } }.start() } /** * @throws IOException IOException */ @Throws(IOException::class) fun stopRecording() { Log.d(TAG, "stop recording") isRecording = false } /** * Initialize audio recorder */ @Throws(IOException::class) private fun initAudioRecorder() { val bytesPerFrame = audioFormat.bytesPerFrame /* Get number of samples. Calculate the buffer size (round up to the factor of given frame size) */ var frameSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, audioFormat.audioFormat) / bytesPerFrame if (frameSize % FRAME_COUNT != 0) { frameSize += (FRAME_COUNT - frameSize % FRAME_COUNT) Log.d(TAG, "Frame size: $frameSize") } bufferSize = frameSize * bytesPerFrame /* Setup audio recorder */audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, channelConfig, audioFormat.audioFormat, bufferSize) // Setup RingBuffer. Currently is 10 times size of hardware buffer // Initialize buffer to hold data ringBuffer = RingBuffer(10 * bufferSize) buffer = ByteArray(bufferSize) init(samplingRate, 1, samplingRate, BIT_RATE) // Create and run thread used to encode data // The thread will encodeThread = DataEncodeThread(ringBuffer!!, os!!, bufferSize) encodeThread?.start() audioRecord?.setRecordPositionUpdateListener(encodeThread, encodeThread?.getHandler()) audioRecord?.positionNotificationPeriod = FRAME_COUNT } companion object { private val TAG = Mp3Recorder::class.java.simpleName private const val DEFAULT_SAMPLING_RATE = 22050 private const val FRAME_COUNT = 160 /* Encoded bit rate. MP3 file will be encoded with bit rate 32kbps */ private const val BIT_RATE = 32 } }
0
null
0
0
f254ffe4731ddb0fe6944ad4981b8cc16eece13e
5,658
Mp3Recorder-2
Apache License 2.0
PrimFastKotlin/KotlinAction/app/src/main/java/com/prim/gkapp/data/model/Org.kt
annocjx
248,767,646
true
{"Python": 628830, "Java": 293115, "HTML": 159403, "JavaScript": 157080, "Kotlin": 131915, "CSS": 45863, "Dart": 39473, "Objective-C": 5647, "Shell": 3784, "PHP": 2469, "CMake": 1603}
package com.prim.gkapp.data.model import android.os.Parcelable import com.prim.gkapp.anno.POKO import kotlinx.android.parcel.Parcelize @POKO @Parcelize data class Org(val avatarUrl: String = "", val id: Int = 0, val login: String = "", val gravatarId: String = "", val url: String = ""): Parcelable
0
null
0
0
b435ca4bd2d0c682c7b40f2b856d7b36af8da7c9
360
Awsome-Android-Advanced
Apache License 2.0
gradle-plugin-acceptance-test/src/main/kotlin/org/eazyportal/plugin/release/gradle/ac/project/StubProjectActionsFactory.kt
eazyportal
423,612,375
false
{"Kotlin": 242422, "Java": 43117, "HTML": 61}
package org.eazyportal.plugin.release.gradle.ac.project import org.eazyportal.plugin.release.core.project.ProjectActions import org.eazyportal.plugin.release.core.project.ProjectActionsFactory import org.eazyportal.plugin.release.core.project.model.ProjectFile import org.eazyportal.plugin.release.gradle.project.GradleProjectActions class StubProjectActionsFactory : ProjectActionsFactory { override fun create(projectFile: ProjectFile<*>): ProjectActions = if (projectFile.resolve(StubProjectActions.VERSION_JSON_FILE_NAME).exists()) { StubProjectActions(projectFile) } else { GradleProjectActions(projectFile) } }
0
Kotlin
1
0
afd3596850099df9d60155058b7b432d4640a761
681
eazyrelease-plugin
Apache License 2.0
app/src/main/java/com/example/basedeneme/ui/mainActivity/MainActivity.kt
burakselcuk1
573,400,503
false
{"Java": 126728, "Kotlin": 31435}
package com.example.basedeneme.ui.mainActivity import com.example.basedeneme.R import com.example.basedeneme.base.BaseActivity import com.example.basedeneme.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>( layoutId = R.layout.activity_main, viewModelClass = MainViewModel::class.java ) { override fun onInitDataBinding() { } }
1
null
1
1
acb1943cabf7f268e91d67be21520788c7dea429
462
Users
The Unlicense
modules/kotlog/src/main/kotlin/azadev/logging/logging.kt
Anizoptera
92,038,394
false
{"Gradle": 12, "Markdown": 2, "Ignore List": 6, "Kotlin": 13, "Java": 1}
@file:JvmName("KotLog") @file:Suppress("unused") package azadev.logging import azadev.logging.LogLevel.ASSERT import azadev.logging.LogLevel.CONFIG import azadev.logging.LogLevel.DEBUG import azadev.logging.LogLevel.ERROR import azadev.logging.LogLevel.INFO import azadev.logging.LogLevel.TRACE import azadev.logging.LogLevel.VERBOSE import azadev.logging.LogLevel.WARN import azadev.logging.impl.ConsoleLoggingAdapter import azadev.logging.impl.LOGGING_ADAPTER import java.io.* import java.util.* /** @see kotlin.jvm.internal.Intrinsics.sanitizeStackTrace */ fun sanitizeStackTrace(throwable: Throwable, classNameToDrop: String): Throwable { val stackTrace = throwable.stackTrace val size = stackTrace.size var lastIntrinsic = -1 for (i in 0..size-1) if (classNameToDrop == stackTrace[i].className) lastIntrinsic = i val list = Arrays.asList(*stackTrace).subList(lastIntrinsic + 1, size) throwable.stackTrace = list.toTypedArray() return throwable } /** @see timber.log.Timber.Tree.getStackTraceString */ fun getStackTraceString(throwable: Throwable): String { val sw = StringWriter(512) sw.appendStackTrace(throwable) val stack: String? = sw.toString() return if (stack != null && stack.isNotEmpty()) stack else (throwable.cause ?: throwable).toString() } fun Writer.appendStackTrace(throwable: Throwable) { val pw = PrintWriter(this, false) @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (throwable as java.lang.Throwable).printStackTrace(pw) pw.flush() } private var adapterInstance: LoggingAdapter? = null val ACTUAL_LOGGING_ADAPTER: LoggingAdapter get() { return adapterInstance ?: run { var isFallback = false val ad = try { LOGGING_ADAPTER } catch(e: NoClassDefFoundError) { isFallback = true ConsoleLoggingAdapter() } adapterInstance = ad if (isFallback) "KotLog".logWarning("LOGGING_ADAPTER not defined. KotLog now uses ConsoleLoggingAdapter as the fallback. Details: https://github.com/Anizoptera/Kotlin-Logging-Facade") ad } } inline fun Any.logRaw(level: Int, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, level, msgFunction) inline fun Any.logRaw(ex: Throwable, level: Int, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, level, ex, msgFunction) @JvmName("log") fun Any.logRaw(msg: CharSequence, level: Int) = ACTUAL_LOGGING_ADAPTER.log(this, level, msg) @JvmName("log") fun Any.logRaw(ex: Throwable, level: Int) = ACTUAL_LOGGING_ADAPTER.log(this, level, null, ex) @JvmName("log") fun Any.logRaw(msg: CharSequence, level: Int, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, level, msg, ex) inline fun Any.logTrace(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msgFunction) inline fun Any.logTrace(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, ex, msgFunction) @JvmName("t") fun Any.logTrace(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msg) @JvmName("t") fun Any.logTrace(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, null, ex) @JvmName("t") fun Any.logTrace(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msg, ex) inline fun Any.logVerbose(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msgFunction) inline fun Any.logVerbose(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, ex, msgFunction) @JvmName("v") fun Any.logVerbose(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msg) @JvmName("v") fun Any.logVerbose(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, null, ex) @JvmName("v") fun Any.logVerbose(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msg, ex) inline fun Any.logDebug(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msgFunction) inline fun Any.logDebug(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, ex, msgFunction) @JvmName("d") fun Any.logDebug(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msg) @JvmName("d") fun Any.logDebug(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, null, ex) @JvmName("d") fun Any.logDebug(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msg, ex) inline fun Any.logConfig(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msgFunction) inline fun Any.logConfig(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, ex, msgFunction) @JvmName("config") fun Any.logConfig(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msg) @JvmName("config") fun Any.logConfig(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, null, ex) @JvmName("config") fun Any.logConfig(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msg, ex) inline fun Any.logInfo(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msgFunction) inline fun Any.logInfo(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, ex, msgFunction) @JvmName("i") fun Any.logInfo(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msg) @JvmName("i") fun Any.logInfo(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, null, ex) @JvmName("i") fun Any.logInfo(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msg, ex) // Use exception as receiver if you don't want it to be sent to Crashlytics, but want to see it in logs // throwable.logWarning("text") inline fun Any.logWarning(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msgFunction) inline fun Any.logWarning(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, ex, msgFunction) @JvmName("w") fun Any.logWarning(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msg) @JvmName("w") fun Any.logWarning(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, null, ex) @JvmName("w") fun Any.logWarning(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msg, ex) inline fun Any.logError(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msgFunction) inline fun Any.logError(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, ex, msgFunction) @JvmName("e") fun Any.logError(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msg) @JvmName("e") fun Any.logError(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, null, ex) @JvmName("e") fun Any.logError(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msg, ex) // Don't inline, otherwise you couldn't jump from logcat to the original place the logger is called from @JvmName("errorOrThrow") fun Any.logErrorOrThrow(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, msg) @JvmName("errorOrThrow") fun Any.logErrorOrThrow(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, null, ex) @JvmName("errorOrThrow") fun Any.logErrorOrThrow(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, msg, ex) inline fun Any.logWtf(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msgFunction) inline fun Any.logWtf(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, ex, msgFunction) @JvmName("wtf") fun Any.logWtf(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, null, ex) @JvmName("wtf") fun Any.logWtf(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msg) @JvmName("wtf") fun Any.logWtf(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msg, ex) /** * Interface that duplicates all the log-methods. * Helps to preserve a proper receiver during logging: * extend your class with this interface, and all the log-calls will be * made using your class as a receiver, even if these log-calls are made * inside a lambda having its own receiver object (see README.txt for examples). */ interface Logging { fun logRaw(level: Int, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, level, msgFunction) fun logRaw(ex: Throwable, level: Int, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, level, ex, msgFunction) fun logRaw(msg: CharSequence, level: Int) = ACTUAL_LOGGING_ADAPTER.log(this, level, msg) fun logRaw(ex: Throwable, level: Int) = ACTUAL_LOGGING_ADAPTER.log(this, level, null, ex) fun logRaw(msg: CharSequence, level: Int, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, level, msg, ex) fun logTrace(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msgFunction) fun logTrace(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, ex, msgFunction) fun logTrace(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msg) fun logTrace(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, null, ex) fun logTrace(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, TRACE, msg, ex) fun logVerbose(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msgFunction) fun logVerbose(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, ex, msgFunction) fun logVerbose(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msg) fun logVerbose(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, null, ex) fun logVerbose(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, VERBOSE, msg, ex) fun logDebug(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msgFunction) fun logDebug(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, ex, msgFunction) fun logDebug(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msg) fun logDebug(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, null, ex) fun logDebug(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, DEBUG, msg, ex) fun logConfig(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msgFunction) fun logConfig(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, ex, msgFunction) fun logConfig(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msg) fun logConfig(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, null, ex) fun logConfig(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, CONFIG, msg, ex) fun logInfo(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msgFunction) fun logInfo(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, ex, msgFunction) fun logInfo(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msg) fun logInfo(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, null, ex) fun logInfo(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, INFO, msg, ex) fun logWarning(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msgFunction) fun logWarning(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, ex, msgFunction) fun logWarning(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msg) fun logWarning(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, null, ex) fun logWarning(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, WARN, msg, ex) fun logError(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msgFunction) fun logError(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, ex, msgFunction) fun logError(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msg) fun logError(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, null, ex) fun logError(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, ERROR, msg, ex) fun logErrorOrThrow(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, msg) fun logErrorOrThrow(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, null, ex) fun logErrorOrThrow(msg: CharSequence?, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.logErrorOrThrow(this, msg, ex) fun logWtf(msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msgFunction) fun logWtf(ex: Throwable, msgFunction: () -> CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, ex, msgFunction) fun logWtf(ex: Throwable) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, null, ex) fun logWtf(msg: CharSequence) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msg) fun logWtf(msg: CharSequence, ex: Throwable?) = ACTUAL_LOGGING_ADAPTER.log(this, ASSERT, msg, ex) }
0
Kotlin
0
1
40e42745d7e0905055078ea5a214fd27b7407898
12,841
Kotlin-Logging-Facade
MIT License
app/src/main/java/ru/tanexc/tree/core/utils/Theme.kt
Tanexc
659,180,976
false
null
package ru.tanexc.tree.core.utils sealed class Theme(val id: Int) { class Default: Theme(id=0) class Orange: Theme(id=1) class Purple: Theme(id=2) companion object { fun getScheme(id: Int) = when (id) { 0 -> Default() 1 -> Orange() 2 -> Purple() else -> Default() } } }
0
Kotlin
0
2
8d30280910e4feb937433e1902fa47ecbdf412b2
371
TreeTask
Apache License 2.0
presentation/src/main/kotlin/io/github/gmvalentino8/github/sample/presentation/core/components/Reducer.kt
wasabi-muffin
462,369,263
false
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
package io.github.gmvalentino8.github.sample.presentation.core.components import io.github.gmvalentino8.github.sample.presentation.core.contract.Event import io.github.gmvalentino8.github.sample.presentation.core.contract.Result import io.github.gmvalentino8.github.sample.presentation.core.contract.State import io.github.gmvalentino8.github.sample.presentation.core.contract.ViewState /** * Reducer * * [Reducer] receives [Result]s from the [Processor] and creates a new [State] */ fun interface Reducer<in R : Result, VS : ViewState, E : Event> { /** * Reduce * * A pure function that applies a [Result] to the current [State] and returns a new [State] */ suspend fun reduce(result: R, state: State<VS, E>): State<VS, E>? }
0
Kotlin
0
1
2194a2504bde08427ad461d92586497c7187fb40
761
github-sample-project
Apache License 2.0
app/src/main/java/com/malikane/mussic/Permission/ReadPermision.kt
Muratthekus
238,066,345
false
{"Kotlin": 43382}
package com.malikane.mussic.Permission import android.Manifest import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class ReadPermision{ //Get permission for reading file at device fun readFile(activity: Activity?){ if (ContextCompat.checkSelfPermission(activity!!.applicationContext, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_EXTERNAL_STORAGE)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),101) // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } } }
0
Kotlin
1
5
6dad14a84ef4dfda33b67d2e2b102bd62676b1ce
1,207
Music-Player
MIT License
rulebook-ktlint/src/test/kotlin/com/hendraanggrian/rulebook/ktlint/RenameGenericsRuleTest.kt
hendraanggrian
556,969,715
false
{"Kotlin": 96579, "Java": 4624, "Groovy": 997}
package com.hendraanggrian.rulebook.ktlint import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule import com.pinterest.ktlint.test.LintViolation import kotlin.test.Test class RenameGenericsRuleTest { private val assertThatCode = assertThatRule { RenameGenericsRule() } @Test fun `Common generic type in class-alike`() = assertThatCode( """ class MyClass<T> annotation class MyAnnotationClass<T> data class MyDataClass<T>(val i: Int) sealed class MySealedClass<T> interface MyInterface<T> """.trimIndent() ).hasNoLintViolations() @Test fun `Uncommon generic type in class-alike`() = assertThatCode( """ class MyClass<X> annotation class MyAnnotationClass<X> data class MyDataClass<X>(val i: Int) sealed class MySealedClass<X> interface MyInterface<X> """.trimIndent() ).hasLintViolationsWithoutAutoCorrect( LintViolation(1, 15, Messages[RenameGenericsRule.MSG]), LintViolation(2, 36, Messages[RenameGenericsRule.MSG]), LintViolation(3, 24, Messages[RenameGenericsRule.MSG]), LintViolation(4, 28, Messages[RenameGenericsRule.MSG]), LintViolation(5, 23, Messages[RenameGenericsRule.MSG]) ) @Test fun `Common generic type in function`() = assertThatCode( """ fun <E> execute(list: List<E>) {} """.trimIndent() ).hasNoLintViolations() @Test fun `Uncommon generic type in function`() = assertThatCode( """ fun <X> execute(list: List<X>) {} """.trimIndent() ).hasLintViolationWithoutAutoCorrect(1, 6, Messages[RenameGenericsRule.MSG]) @Test fun `Reified generic type`() = assertThatCode( """ fun <reified X> execute(list: List<X>) {} """.trimIndent() ).hasLintViolationWithoutAutoCorrect(1, 14, Messages[RenameGenericsRule.MSG]) }
0
Kotlin
0
1
060ecafac50700a5faabbc66c4ad538810f948ea
1,943
rulebook
Apache License 2.0
ui-kit/src/test/java/com/quickblox/android_ui_kit/spy/repository/EventsRepositorySpy.kt
QuickBlox
637,751,718
false
{"Kotlin": 1833847}
/* * Created by Injoit on 3.4.2023. * Copyright © 2023 Quickblox. All rights reserved. */ package com.quickblox.android_ui_kit.spy.repository import com.quickblox.android_ui_kit.domain.entity.DialogEntity import com.quickblox.android_ui_kit.domain.entity.TypingEntity import com.quickblox.android_ui_kit.domain.entity.message.MessageEntity import com.quickblox.android_ui_kit.domain.repository.EventsRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow open class EventsRepositorySpy() : EventsRepository { private val dialogsFlow = MutableSharedFlow<DialogEntity?>(0) private val messagesFlow = MutableSharedFlow<MessageEntity?>(0) private val typingFlow = MutableSharedFlow<Pair<Int?, TypingEntity.TypingTypes?>>(0) suspend fun sendDialog(dialogEntity: DialogEntity) { dialogsFlow.emit(dialogEntity) } suspend fun sendMessage(messageEntity: MessageEntity) { messagesFlow.emit(messageEntity) } suspend fun sendStartTyping(senderId: Int) { typingFlow.emit(Pair(senderId, TypingEntity.TypingTypes.STARTED)) } suspend fun sendStopTyping(senderId: Int) { typingFlow.emit(Pair(senderId, TypingEntity.TypingTypes.STOPPED)) } override fun startTypingEvent(dialogEntity: DialogEntity) { } override fun stopTypingEvent(dialogEntity: DialogEntity) { } override fun subscribeDialogEvents(): Flow<DialogEntity?> { return dialogsFlow } override fun subscribeMessageEvents(): Flow<MessageEntity?> { return messagesFlow } override fun subscribeTypingEvents(): Flow<Pair<Int?, TypingEntity.TypingTypes?>> { return typingFlow } }
1
Kotlin
0
4
0ef856d22efb1540d6e238a073badbf31c03961a
1,713
android-ui-kit
MIT License
src/main/kotlin/com/belveth/bullettime/domain/post/mapper/PostMapper.kt
belveth
482,193,761
false
null
package com.belveth.bullettime.domain.post.mapper import com.belveth.bullettime.domain.post.dto.CreatePostDto import com.belveth.bullettime.domain.post.dto.PostDto import com.belveth.bullettime.domain.post.dto.UpdatePostDto import com.belveth.bullettime.domain.post.entity.PostEntity import org.mapstruct.* @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) interface PostMapper { @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) fun dtoFromEntity(postEntity: PostEntity): PostDto @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) fun toEntityFromDto(createPostDto: CreatePostDto): PostEntity @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) fun updateEntityFromDto(updatePostDto: UpdatePostDto, @MappingTarget postEntity: PostEntity): PostEntity }
0
Kotlin
0
1
83fecf1962934d35eceeb5542c005c56f7135f54
915
bullet-time
MIT License
app/src/main/kotlin/com/gigamole/composescrollbars/sample/MainScreenDemoContent.kt
GIGAMOLE
684,139,984
false
{"Kotlin": 332829}
package com.gigamole.composescrollbars.sample import androidx.compose.animation.AnimatedContent import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.togetherWith import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.center import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.PaintingStyle import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.drawOutline import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.lerp import com.gigamole.composescrollbars.Scrollbars import com.gigamole.composescrollbars.config.ScrollbarsConfig import com.gigamole.composescrollbars.config.ScrollbarsGravity import com.gigamole.composescrollbars.config.ScrollbarsOrientation import com.gigamole.composescrollbars.config.layercontenttype.ScrollbarsLayerContentType import com.gigamole.composescrollbars.config.layercontenttype.layercontentstyletype.ScrollbarsLayerContentStyleType import com.gigamole.composescrollbars.config.layersType.ScrollbarsLayersType import com.gigamole.composescrollbars.config.layersType.layerConfig.ScrollbarsLayerConfig import com.gigamole.composescrollbars.config.layersType.layerConfig.ScrollbarsLayerGravity import com.gigamole.composescrollbars.config.layersType.thicknessType.ScrollbarsThicknessType import com.gigamole.composescrollbars.rememberScrollbarsState import com.gigamole.composescrollbars.scrolltype.ScrollbarsScrollType import com.gigamole.composescrollbars.scrolltype.knobtype.ScrollbarsStaticKnobType import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.UUID import kotlin.math.roundToInt private val sampleTitleColor = Color(0xFF007AC9) private val sampleTitleBgColor = sampleTitleColor.copy(alpha = 0.05F) private val sampleDescriptionColor = Color(0xFFE21776) private val sampleDescriptionBgColor = sampleDescriptionColor.copy(alpha = 0.05F) private val sampleStarColor = Color.White private val sampleStarBgColor = Color(0xFFFFC107) @Suppress("unused") @Composable fun MainScreenDemoContent() { val verticalScrollState = rememberScrollState() val horizontalScrollState = rememberScrollState() val coroutineScope = rememberCoroutineScope() val verticalScrollAmount = with(LocalDensity.current) { 30.dp.toPx() }.roundToInt() val horizontalScrollAmount = with(LocalDensity.current) { 128.dp.toPx() }.roundToInt() var triggerId by remember { mutableStateOf<String?>(null) } LaunchedEffect(triggerId) { if (triggerId == null) { return@LaunchedEffect } coroutineScope.launch { coroutineScope.launch { verticalScrollState.animateScrollTo( value = verticalScrollAmount, animationSpec = tween(durationMillis = 1000) ) } coroutineScope.launch { delay(600) horizontalScrollState.animateScrollTo( value = horizontalScrollAmount, animationSpec = tween(durationMillis = 1300) ) } coroutineScope.launch { delay(1300) verticalScrollState.animateScrollTo( value = -verticalScrollAmount, animationSpec = tween(durationMillis = 1000) ) } coroutineScope.launch { delay(2500) horizontalScrollState.animateScrollTo( value = -horizontalScrollAmount, animationSpec = tween(durationMillis = 600) ) } } } Box( modifier = Modifier .fillMaxSize() .background(color = Color.White) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { triggerId = UUID .randomUUID() .toString() } ), contentAlignment = Alignment.Center ) { Column( verticalArrangement = Arrangement.spacedBy( space = 16.dp, alignment = Alignment.CenterVertically, ), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier.height(height = 160.dp), horizontalArrangement = Arrangement.spacedBy(space = 32.dp) ) { Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Wrap(paddingValues = PaddingValues(all = 2.dp)), backgroundLayerContentType = ScrollbarsLayerContentType.Custom { // Set shadowed background. Box( modifier = Modifier .fillMaxSize() .shadow( elevation = 4.dp, shape = RectangleShape, clip = true, spotColor = Color.DarkGray.copy(alpha = 0.5F), ambientColor = Color.DarkGray.copy(alpha = 0.5F) ) .background( color = Color.White, shape = RectangleShape ) ) }, knobLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle( shape = RectangleShape, idleColor = Color.LightGray.copy(alpha = 0.25F) ) ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.3F) ) ) ) Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle(idleColor = Color.LightGray.copy(alpha = 0.2F)), knobLayerContentType = ScrollbarsLayerContentType.Custom { // Set shadowed knob. Box( modifier = Modifier .fillMaxSize() .shadow( elevation = 4.dp, shape = CircleShape, clip = true ) .background( color = Color.White, shape = CircleShape ) ) } ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.4F) ) ) ) Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle(idleColor = Color.LightGray.copy(alpha = 0.25F)), knobLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.4F), activeColor = Color.LightGray, outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ) ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.5F) ) ) ) Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Wrap( paddingValues = PaddingValues( horizontal = 4.dp, vertical = 6.dp ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.4F), activeColor = Color.LightGray.copy(alpha = 0.8F), shape = CutCornerShape(percent = 100), styleType = ScrollbarsLayerContentStyleType.Border(width = 2.dp), outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ), knobLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.4F), activeColor = Color.LightGray.copy(alpha = 0.8F), shape = CutCornerShape(percent = 100), outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ) ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.6F) ) ) ) Box( modifier = Modifier .height(height = 160.dp) .width(width = 250.dp) .background(color = sampleTitleBgColor) .verticalScroll(state = verticalScrollState) ) { Text( modifier = Modifier .fillMaxWidth() .padding( horizontal = 32.dp, vertical = 48.dp ), text = "Compose\nScrollbars", color = sampleTitleColor, style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.Bold, fontFamily = FontFamilySpaceGrotesk ) } Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, gravity = ScrollbarsGravity.Start, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 2.dp), layerGravity = ScrollbarsLayerGravity.Start ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 6.dp), layerGravity = ScrollbarsLayerGravity.Start, paddingValues = PaddingValues(start = 2.dp) ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.4F), activeColor = Color.LightGray.copy(alpha = 0.8F), shape = RectangleShape, outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ), knobLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.4F), activeColor = Color.LightGray.copy(alpha = 0.8F), shape = RectangleShape, outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ) ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.6F) ) ) ) Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, gravity = ScrollbarsGravity.Start, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 2.dp), layerGravity = ScrollbarsLayerGravity.Center ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 10.dp), layerGravity = ScrollbarsLayerGravity.Center ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.IdleActive( idleColor = Color.LightGray.copy(alpha = 0.3F), activeColor = Color.LightGray.copy(alpha = 0.6F), shape = RectangleShape, outAnimationSpec = tween( durationMillis = 200, delayMillis = 300 ) ), knobLayerContentType = ScrollbarsLayerContentType.Custom { state -> // Take the idle active color from the background to match it on knob. val idleActiveColor = (state.config.backgroundLayerContentType as? ScrollbarsLayerContentType.Default.Colored.IdleActive)?.idleActiveColor ?: Color.LightGray.copy(alpha = 0.3F) Box( modifier = Modifier .fillMaxSize() .background( color = Color.White, shape = RectangleShape ) .border( color = idleActiveColor, width = 2.dp ) ) } ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.5F) ) ) ) Scrollbars( modifier = Modifier .width(width = 16.dp) .alpha(alpha = 0.3F), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 4.dp), layerGravity = ScrollbarsLayerGravity.Center ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 16.dp), layerGravity = ScrollbarsLayerGravity.Center ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Custom { // Custom line with bulbs background. Box( modifier = Modifier .fillMaxHeight() .align(alignment = Alignment.Center) ) { Box( modifier = Modifier .fillMaxHeight() .width(width = 2.dp) .padding(vertical = 8.dp) .align(alignment = Alignment.Center) .background(color = Color.LightGray) ) Box( modifier = Modifier .padding(top = 6.dp) .size(size = 4.dp) .background( color = Color.LightGray, shape = CircleShape ) ) Box( modifier = Modifier .padding(bottom = 6.dp) .size(size = 4.dp) .align(alignment = Alignment.BottomCenter) .background( color = Color.LightGray, shape = CircleShape ) ) } }, knobLayerContentType = ScrollbarsLayerContentType.Custom { // Custom dot with increasing size custom knob. val knobFraction = 1.0F - if (it.scrollFraction <= 0.5F) { 1.0F - (it.scrollFraction * 2.0F) } else { (it.scrollFraction - 0.5F) * 2.0F } val knobSize = lerp( start = 6.dp, stop = 16.dp, fraction = knobFraction ) val knobColor = androidx.compose.ui.graphics.lerp( start = Color.LightGray, stop = Color.DarkGray, fraction = knobFraction ) Box( modifier = Modifier .fillMaxSize() .align(alignment = Alignment.Center), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .size(size = knobSize) .background( color = knobColor, shape = CircleShape ) ) } } ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Exact(size = 16.dp) ) ) ) Scrollbars( modifier = Modifier.width(width = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Vertical, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 2.dp), layerGravity = ScrollbarsLayerGravity.Center, paddingValues = PaddingValues(vertical = 6.dp) ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 12.dp), layerGravity = ScrollbarsLayerGravity.Center ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle( idleColor = Color.LightGray.copy(alpha = 0.2F), shape = CircleShape ), knobLayerContentType = ScrollbarsLayerContentType.Custom { // Custom circle shadow knob. Box( modifier = Modifier .fillMaxSize() .shadow( elevation = 4.dp, shape = CircleShape, clip = true ) .background( color = Color.White, shape = CircleShape ) ) } ), scrollType = ScrollbarsScrollType.Scroll( state = verticalScrollState, knobType = ScrollbarsStaticKnobType.Exact(size = 12.dp) ) ) ) } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy( space = 32.dp, alignment = Alignment.CenterHorizontally ), verticalAlignment = Alignment.CenterVertically ) { Column( modifier = Modifier.width(width = 160.dp), verticalArrangement = Arrangement.spacedBy(space = 16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Scrollbars( modifier = Modifier.height(height = 10.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Horizontal, gravity = ScrollbarsGravity.Start, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 5.dp), layerGravity = ScrollbarsLayerGravity.Center ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 10.dp), layerGravity = ScrollbarsLayerGravity.Center ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle( idleColor = Color.LightGray.copy(alpha = 0.45F), shape = CircleShape ), knobLayerContentType = ScrollbarsLayerContentType.Custom { // Custom circle long knob. Box( modifier = Modifier .fillMaxSize() .background( color = Color.White, shape = CircleShape ) .border( color = Color.LightGray.copy(alpha = 0.45F), width = 2.dp, shape = CircleShape ) ) } ), scrollType = ScrollbarsScrollType.Scroll( state = horizontalScrollState, knobType = ScrollbarsStaticKnobType.Fraction(fraction = 0.5F) ) ) ) Scrollbars( modifier = Modifier.height(height = 16.dp), state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Horizontal, gravity = ScrollbarsGravity.End, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 2.dp), layerGravity = ScrollbarsLayerGravity.End ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Exact(thickness = 10.dp), layerGravity = ScrollbarsLayerGravity.End, paddingValues = PaddingValues(bottom = 6.dp) ) ), backgroundLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle( idleColor = Color.LightGray.copy(alpha = 0.55F), shape = RectangleShape ), knobLayerContentType = ScrollbarsLayerContentType.Default.Colored.Idle( idleColor = Color.LightGray.copy(alpha = 0.55F), shape = RectangleShape ), ), scrollType = ScrollbarsScrollType.Scroll( state = horizontalScrollState, knobType = ScrollbarsStaticKnobType.Exact(size = 10.dp) ) ) ) } Box( modifier = Modifier .width(width = 250.dp) .height(height = 48.dp) .background(color = sampleDescriptionBgColor) .horizontalScroll(state = horizontalScrollState), contentAlignment = Alignment.CenterStart ) { Text( modifier = Modifier.padding(horizontal = 16.dp), text = "Polish Android Compose UI with advanced scrollbars", color = sampleDescriptionColor, style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Normal, fontFamily = FontFamilyOpenSans ) } Column( modifier = Modifier .width(width = 160.dp) .height(height = 48.dp), verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally ) { Scrollbars( state = rememberScrollbarsState( config = ScrollbarsConfig( orientation = ScrollbarsOrientation.Horizontal, gravity = ScrollbarsGravity.End, paddingValues = PaddingValues(), layersType = ScrollbarsLayersType.Split( backgroundLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Wrap, layerGravity = ScrollbarsLayerGravity.End, paddingValues = PaddingValues(horizontal = 12.dp) ), knobLayerConfig = ScrollbarsLayerConfig( thicknessType = ScrollbarsThicknessType.Wrap, layerGravity = ScrollbarsLayerGravity.End ), ), backgroundLayerContentType = ScrollbarsLayerContentType.Custom { state -> // Custom increasing triangle background. val bgColor = androidx.compose.ui.graphics.lerp( start = Color.LightGray.copy(alpha = 0.25F), stop = Color.LightGray.copy(alpha = 0.55F), fraction = state.scrollFraction ) Canvas( modifier = Modifier .fillMaxWidth() .height(height = 6.dp) ) { drawPath( path = Path().apply { moveTo( x = 0.0F, y = size.height ) lineTo( x = size.width, y = 0.0F ) lineTo( x = size.width, y = size.height ) close() }, color = bgColor ) } }, knobLayerContentType = ScrollbarsLayerContentType.Custom { state -> // Custom sliding popup with a 100% special star knob. val maxReached by remember(state.scrollFraction) { derivedStateOf { state.scrollFraction >= 0.99F } } var prevScrollFraction by remember { mutableFloatStateOf(state.scrollFraction) } val isForward = when { prevScrollFraction < state.scrollFraction -> { true } prevScrollFraction > state.scrollFraction -> { false } else -> { null } } prevScrollFraction = state.scrollFraction val progressKnobColor = androidx.compose.ui.graphics.lerp( start = Color.LightGray.copy(alpha = 0.25F), stop = Color.LightGray.copy(alpha = 0.55F), fraction = state.scrollFraction ) val knobColor by animateColorAsState( targetValue = if (maxReached) { sampleStarBgColor } else { progressKnobColor }, label = "KnobColor" ) val progressTextColor = androidx.compose.ui.graphics.lerp( start = Color.DarkGray.copy(alpha = 0.5F), stop = Color.DarkGray.copy(alpha = 0.8F), fraction = state.scrollFraction ) val textColor by animateColorAsState( targetValue = if (maxReached) { sampleStarColor } else { progressTextColor }, label = "TextColor" ) val progressKnobScale = androidx.compose.ui.util.lerp( start = 0.85F, stop = 1.25F, fraction = state.scrollFraction ) val knobScale by animateFloatAsState( targetValue = if (maxReached) { 1.85F } else { progressKnobScale }, animationSpec = spring( dampingRatio = Spring.DampingRatioLowBouncy, stiffness = 7_000.0F ), label = "KnobScale" ) val knobOffset = lerp( start = 0.dp, stop = (-6).dp, fraction = state.scrollFraction ) val knobOffsetPx = with(LocalDensity.current) { knobOffset.toPx() } val knobRotation by animateFloatAsState( targetValue = if (maxReached) { 0.0F } else { if (state.scrollType.isScrollInProgress && isForward != null) { if (isForward) { -12.0F } else { 12.0F } } else { 0.0F } }, animationSpec = if (maxReached) { spring( dampingRatio = 0.18F, stiffness = Spring.StiffnessMedium ) } else { spring( dampingRatio = 0.35F, stiffness = Spring.StiffnessMediumLow ) }, label = "KnobRotation" ) val knobText = (state.scrollFraction * 100.0F).roundToInt().toString() Column( modifier = Modifier .fillMaxWidth() .padding(bottom = 4.dp) .graphicsLayer( scaleX = knobScale, scaleY = knobScale, translationY = knobOffsetPx, rotationZ = knobRotation, transformOrigin = TransformOrigin( pivotFractionX = 0.5F, pivotFractionY = 1.0F ) ), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = Modifier .fillMaxWidth() .height(height = 22.dp) .background( color = knobColor, shape = RoundedCornerShape(size = 6.dp) ), contentAlignment = Alignment.Center ) { AnimatedContent( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center, targetState = maxReached, transitionSpec = { (fadeIn(animationSpec = spring()) + scaleIn(animationSpec = spring())).togetherWith( fadeOut(animationSpec = spring()) + scaleOut(animationSpec = spring()) ) }, label = "KnobTextIconContent" ) { maxReachedState -> Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { if (maxReachedState) { Image( modifier = Modifier.size(size = 14.dp), painter = painterResource(id = R.drawable.ic_star), contentScale = ContentScale.FillBounds, colorFilter = ColorFilter.tint(color = sampleStarColor), contentDescription = "" ) } else { Text( text = knobText, color = textColor, fontWeight = FontWeight.Bold, fontSize = TextUnit( value = 10.0F, type = TextUnitType.Sp ) ) } } } } Canvas( modifier = Modifier .height(height = 6.dp) .width(width = 12.dp) ) { val path = Path().apply { moveTo( x = 0.0F, y = 0.0F ) lineTo( x = size.width * 0.25F, y = 0.0F ) lineTo( x = size.center.x, y = size.height ) lineTo( x = size.width * 0.75F, y = 0.0F ) lineTo( x = size.width, y = 0.0F ) lineTo( x = size.width, y = 0.0F ) lineTo( x = 0.0F, y = 0.0F ) close() } drawIntoCanvas { canvas -> canvas.drawOutline( outline = Outline.Generic(path = path), paint = Paint().apply { color = knobColor style = PaintingStyle.Fill pathEffect = PathEffect.cornerPathEffect(radius = 8.dp.toPx()) } ) } } } } ), scrollType = ScrollbarsScrollType.Scroll( state = horizontalScrollState, knobType = ScrollbarsStaticKnobType.Exact(size = 24.dp) ) ) ) } } } } }
0
Kotlin
3
95
2d72e0bb7d674c6316c2e1a709dda1242dbeefc0
52,829
ComposeScrollbars
MIT License
library/src/main/java/com/andreacioccarelli/billingprotector/crypt/HashGeneratior.kt
cioccarellia
141,766,102
false
null
package com.andreacioccarelli.billingprotector.crypt import java.security.MessageDigest import kotlin.experimental.and /** * Designed and Developed by Andrea Cioccarelli */ object HashGeneratior { private const val HASH_METHOD = "MD5" fun hash(input: String): String { val md = MessageDigest.getInstance(HASH_METHOD) md.update(input.toByteArray()) val digest = md.digest() val buffer = StringBuffer() val magicByte = 0xff.toByte() for (b in digest) { buffer.append(String.format("%02x", b and magicByte)) } return buffer.toString() } }
1
Kotlin
6
35
478e93464fac69f3b1fef72f6e53d6c41f24d146
633
billing-protector
Apache License 2.0
privacy_plugin/plugins/src/main/kotlin/TempTest.kt
ZakAnun
759,869,114
false
{"Kotlin": 10351}
import com.android.build.api.artifact.SingleArtifact import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.gradle.AppPlugin import org.gradle.api.Plugin import org.gradle.api.tasks.TaskProvider import org.gradle.api.initialization.Settings import org.gradle.kotlin.dsl.register class TempTest : Plugin<Settings> { override fun apply(settings: Settings) { var taskProvider: TaskProvider<AllProjectsApkTask>? = null settings.gradle.beforeProject { project -> // since we want a single task that will consume all APKs produced by a // sub-project's RELEASE variant, let's create it in the rootProject only. if (project == project.rootProject) { taskProvider = project.tasks.register<AllProjectsApkTask>( "allProjectsAction" ) { // set the Task output file inside the build's output folder outputFile.set( project.layout.buildDirectory.file("list_of_apks.txt") ) } } // Registers a callback on the application of the Android Application plugin. // This allows the CustomPlugin to work whether it's applied before or after // the Android Application plugin. project.plugins.withType(AppPlugin::class.java) { _ -> // so we now know that the application plugin has been applied so // let's look up its extension so we can invoke the AGP Variant API. val androidComponents = project.extensions.getByType(ApplicationAndroidComponentsExtension::class.java) // Registers a callback to be called, when a RELEASE variant is configured androidComponents.onVariants( androidComponents.selector().withBuildType("release") ) { variant -> // for each RELEASE variant, let's configure the unique task we created // in the root project and add the APK artifact to its input file. taskProvider?.configure { task -> println("Adding variant ${variant.name} APKs from ${project.path}") // look up the APK directory artifact as a Provider<Directory> and // add it to the task's inputDirectories FileCollection. task.inputDirectories.add( variant.artifacts.get(SingleArtifact.APK) ) } } } } } }
0
Kotlin
0
0
153680bc486adf22930c43a205814c77135e8250
2,693
PrivacyPlugin
Apache License 2.0
android/src/main/java/dev/igorcferreira/rsstodon/android/db/entity/StatusEntity.kt
igorcferreira
569,381,753
false
{"Kotlin": 103347}
package dev.igorcferreira.rsstodon.android.db.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.* @Entity(tableName = "status") data class StatusEntity( @PrimaryKey val id: String, @ColumnInfo(name = "content") val content: String, @ColumnInfo(name = "created_at") val createdAt: Date, @ColumnInfo(name = "display_name") val displayName: String, @ColumnInfo(name = "uri") val uri: String )
0
Kotlin
0
0
00c454f4506048adb983c308445ee6926348d1a6
477
RSSTodon-Kotlin
Apache License 2.0
aTalk/src/main/java/org/atalk/impl/neomedia/jmfext/media/protocol/rtpdumpfile/RawPacketScheduler.kt
cmeng-git
704,328,019
false
{"Kotlin": 14364024, "Java": 2718723, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375}
/* * Copyright @ 2015 Atlassian Pty 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 org.atalk.impl.neomedia.jmfext.media.protocol.rtpdumpfile import org.atalk.impl.neomedia.RTPPacketPredicate import org.atalk.service.neomedia.RawPacket import org.atalk.util.ByteArrayBuffer import org.atalk.util.RTPUtils.rtpTimestampDiff /** * Suggests a schedule method that puts the current thread to sleep for X milis, where X is such * that RTP timestamps and a given clock are respected. * * @author <NAME> */ class RawPacketScheduler /** * Ctor. * * @param clockRate */( /** * The RTP clock rate, used to interpret the RTP timestamps read from the file. */ private val clockRate: Long) { /** * The timestamp of the last rtp packet (the timestamp change only when a marked packet has been sent). */ private var lastRtpTimestamp = -1L /** * puts the current thread to sleep for X milis, where X is such that RTP timestamps and a given * clock are respected. * * @param rtpPacket * the `RTPPacket` to schedule. */ @Throws(InterruptedException::class) fun schedule(rtpPacket: RawPacket) { if (!RTPPacketPredicate.INSTANCE.test(rtpPacket as ByteArrayBuffer)) { return } if (lastRtpTimestamp == -1L) { lastRtpTimestamp = rtpPacket.timestamp return } val previous = lastRtpTimestamp lastRtpTimestamp = rtpPacket.timestamp val rtpDiff = rtpTimestampDiff(lastRtpTimestamp, previous) val nanos = rtpDiff * 1000 * 1000 * 1000 / clockRate if (nanos > 0) { Thread.sleep(nanos / 1000000, (nanos % 1000000).toInt()) } } }
0
Kotlin
0
0
90e83dd8c054a5f480d03e8b0b1912b41bd79b0c
2,256
atalk-hmos_kotlin
Apache License 2.0
app/src/test/java/com/example/quotableapp/fakes/FakeObjectsCreators.kt
slowikj
428,242,218
false
{"Kotlin": 295506}
package com.example.quotableapp.fakes import androidx.paging.PagingConfig import com.example.quotableapp.common.DispatchersProvider import com.example.quotableapp.data.remote.common.ApiResponseInterpreter import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.TestScope import retrofit2.Response fun getFakeApiResponseInterpreter(): ApiResponseInterpreter { return object : ApiResponseInterpreter { override suspend fun <DTO> invoke(apiCall: suspend () -> Response<DTO>): Result<DTO> { val res = apiCall() return if (res.isSuccessful) { Result.success(res.body()!!) } else Result.failure(Exception()) } } } @ExperimentalStdlibApi @ExperimentalCoroutinesApi fun TestScope.getTestDispatchersProvider(): DispatchersProvider { return getTestDispatchersProvider(getTestDispatcher()) } @ExperimentalStdlibApi @ExperimentalCoroutinesApi fun TestScope.getTestDispatcher(): TestDispatcher { return this.coroutineContext[CoroutineDispatcher] as TestDispatcher } @ExperimentalCoroutinesApi fun getTestDispatchersProvider(testDispatcher: TestDispatcher): DispatchersProvider { return object : DispatchersProvider { override val Main: CoroutineDispatcher get() = testDispatcher override val Unconfined: CoroutineDispatcher get() = testDispatcher override val Default: CoroutineDispatcher get() = testDispatcher override val IO: CoroutineDispatcher get() = testDispatcher } } fun getTestPagingConfig(): PagingConfig = PagingConfig( pageSize = 30, enablePlaceholders = true, initialLoadSize = 30, prefetchDistance = 10 )
12
Kotlin
0
1
1011bd6fd1793fdc8d20a3fa7116ab1bd7639187
1,819
quotable-android-app
Apache License 2.0
pix/src/main/kotlin/br/com/zup/pix/exception/handlers/InternalExceptionHandler.kt
danielgutknecht
349,216,101
true
{"Kotlin": 45022}
package br.com.zup.pix.exception.handlers import br.com.zup.pix.exception.ExceptionHandler import br.com.zup.pix.exception.ExceptionHandler.StatusWithDetails import br.com.zup.pix.exception.types.InternalException import io.grpc.Status import java.lang.Exception class InternalExceptionHandler: ExceptionHandler<InternalException> { override fun handle(e: InternalException): StatusWithDetails = StatusWithDetails( Status.INTERNAL .withDescription(e.message) .withCause(e) ) override fun supports(e: Exception): Boolean = e is InternalException }
0
Kotlin
0
0
3c85cd8a2b62a5b15f0c065bb95dd320e7fb05d1
618
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/org/fossasia/susi/ai/skills/skilllisting/contract/ISkillListingView.kt
Maimoi
163,274,923
true
{"Kotlin": 467372, "Java": 42275, "Shell": 2946}
package org.fossasia.susi.ai.skills.skilllisting.contract import org.fossasia.susi.ai.dataclasses.SkillsBasedOnMetrics /** * * Created by chiragw15 on 15/8/17. */ interface ISkillListingView { fun visibilityProgressBar(boolean: Boolean) fun updateAdapter(metrics: SkillsBasedOnMetrics) fun displayError() }
0
Kotlin
0
0
545385e725793162e31d1a42fd1c771ea43a668e
323
susi_android
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/mui/base/Dropdown.kt
karakum-team
387,062,541
false
{"Kotlin": 1406331, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/base/Dropdown") package mui.base /** * * Demos: * * - [Menu](https://mui.com/base-ui/react-menu/) * * API: * * - [Dropdown API](https://mui.com/base-ui/react-menu/components-api/#dropdown) */ external val Dropdown: react.FC<DropdownProps>
0
Kotlin
5
36
f16625a1a7ecd16eae808761497618faceae8f6d
316
mui-kotlin
Apache License 2.0
app/src/main/java/com/alvayonara/openweatherapps/core/di/NetworkModule.kt
alvayonara
341,443,640
false
{"Kotlin": 41580}
package com.alvayonara.openweatherapps.core.di import com.alvayonara.openweatherapps.BuildConfig import com.alvayonara.openweatherapps.core.data.source.remote.network.ApiService import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit @Module @InstallIn(ApplicationComponent::class) class NetworkModule { @Provides fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .build() } @Provides fun provideMoshi(): Moshi = Moshi.Builder() .addLast(KotlinJsonAdapterFactory()) .build() @Provides fun provideApiService(moshi: Moshi): ApiService { val retrofit = Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL) .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(provideOkHttpClient()) .build() return retrofit.create(ApiService::class.java) } }
0
Kotlin
0
0
6e0deb68cad5cba72ac188fe116e61d8cc8fbdd8
1,470
openweather-android
Apache License 2.0
app/src/main/java/com/romnan/kamusbatak/presentation/preferences/PreferencesScreenState.kt
deddyrumapea
458,088,031
false
{"Kotlin": 204411, "CMake": 1603}
package com.romnan.kamusbatak.presentation.preferences import com.romnan.kamusbatak.BuildConfig import com.romnan.kamusbatak.domain.model.ThemeMode data class PreferencesScreenState( val isUpdatingLocalDb: Boolean, val localDbLastUpdatedAt: Long?, val currentThemeMode: ThemeMode, val isThemeModeDialogVisible: Boolean, val visiblePermissionDialogQueue: List<String>, ) { val appVersion: String get() = BuildConfig.VERSION_NAME companion object { val defaultValue = PreferencesScreenState( isUpdatingLocalDb = false, localDbLastUpdatedAt = null, currentThemeMode = ThemeMode.System, isThemeModeDialogVisible = false, visiblePermissionDialogQueue = emptyList(), ) } }
0
Kotlin
0
1
9be3a715e89974009cf1707455d907c72f63b6f7
787
KamusBatak
Apache License 2.0
src/main/kotlin/com/mygame/data/GameFrame.kt
theapache64
400,972,673
false
null
package com.mygame.data import androidx.compose.ui.graphics.Color data class Circle( val color: Color, val radius: Float, val x: Float, val y: Float ) data class GameFrame( val score: Int, val circles: List<Circle> )
0
Kotlin
0
5
d7efabb53be77e7d5406629d98abdb463c769255
243
compose-desktop-game-template
Apache License 2.0
src/main/kotlin/com/github/rafaelldi/tyeplugin/runtimes/TyeReplicaRuntime.kt
rafaelldi
342,595,811
false
null
package com.github.rafaelldi.tyeplugin.runtimes import com.github.rafaelldi.tyeplugin.model.TyeServiceReplica import com.intellij.openapi.vfs.VirtualFile class TyeReplicaRuntime<T>(val replica: T, parentRuntime: TyeServiceRuntime<*>) : TyeBaseRuntime(replica.getName()) where T : TyeServiceReplica { init { parent = parentRuntime } fun update(updatedReplica: T) { updateProperties(updatedReplica.properties) updateEnvironmentVariables(updatedReplica.environmentVariables) } private fun updateProperties(updatedProperties: MutableMap<String, String?>) { val removedProperties = replica.properties.keys.subtract(updatedProperties.keys) for (property in updatedProperties) { val currentValue = replica.properties[property.key] if (currentValue == property.value) { continue } replica.properties[property.key] = property.value } for (removedProperty in removedProperties) { replica.properties.remove(removedProperty) } } private fun updateEnvironmentVariables(updatedVariables: MutableMap<String, String?>?) { if (updatedVariables == null || replica.environmentVariables == null) { return } val removedVariables = replica.environmentVariables.keys.subtract(updatedVariables.keys) for (variable in updatedVariables) { val currentValue = replica.environmentVariables[variable.key] if (currentValue == variable.value) { continue } replica.environmentVariables[variable.key] = variable.value } for (removedVariable in removedVariables) { replica.environmentVariables.remove(removedVariable) } } override fun getSourceFile(): VirtualFile? { return parent?.getSourceFile() } }
0
Kotlin
1
8
5824f812f483745b40c1a2ce24297b96b16d2d71
1,915
tye-plugin
MIT License
app/src/main/java/com/nykaa/nykaacat/network/NetworkExtention.kt
AntimKhel
750,518,139
false
{"Kotlin": 26168}
package com.nykaa.nykaacat.network import androidx.annotation.Keep import retrofit2.HttpException import retrofit2.Response suspend fun <T : Any> safeApiCall( execute: suspend () -> Response<T> ): ApiResponse<T> { return try { val response = execute() val body = response.body() if (response.isSuccessful && body != null) { ApiResponse.Success(body) } else { ApiResponse.Error.ResponseError(Pair(response.code().toString(), response.message())) } } catch (e: HttpException) { ApiResponse.Error.ApiError(Pair(e.code().toString(), e.message())) } catch (e: Exception) { ApiResponse.Exception(e) } } @Keep sealed class ApiResponse<T> { class NOOP<T> : ApiResponse<T>() class Loading<T>() : ApiResponse<T>() class Success<T>(val data: T?) : ApiResponse<T>() sealed class Error<T>(val message: Pair<String?, String?>?, val data: T? = null) : ApiResponse<T>() { class ApiError<T>(message: Pair<String?, String?>?, data: T? = null) : Error<T>(message, data) class ResponseError<T>(message: Pair<String?, String?>?, data: T? = null) : Error<T>(message, data) } class Exception<T>(val exception: kotlin.Exception?) : ApiResponse<T>() }
0
Kotlin
0
0
37c6266c16869897f0d019ac9cb1808c37b42cf3
1,270
NykaaNyan
Apache License 2.0
HappyBirthday/marsphotos/src/test/java/com/example/happybirthday/marsphotos/MarsApiServiceTest.kt
ETSEmpiricalStudyKotlinAndroidApps
496,360,419
false
{"Kotlin": 718685, "Java": 174794}
package com.example.happybirthday.marsphotos import com.example.happybirthday.network.MarsApiService import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import junit.framework.Assert.* import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class MarsApiServiceTest : BaseTest() { private lateinit var service: MarsApiService @Before fun setup() { val url = mockWebServer.url("/") service = Retrofit.Builder() .baseUrl(url) .addConverterFactory( MoshiConverterFactory.create( Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() ) ) .build() .create(MarsApiService::class.java) } @Test fun apiService() { enqueue("mars_photos.json") runBlocking { val apiResponse = service.getPhotos() assertNotNull(apiResponse) assertTrue("The list was empty", apiResponse.isNotEmpty()) assertEquals("The IDs did mot match", "424905", apiResponse[0].id) } } }
0
null
0
0
147caab2622d15c52cd5b8cf21779c73481c9020
1,286
android-dev
MIT License
app/src/main/java/com/example/goalstracker/MainActivity.kt
Mohanmanuhs
795,360,347
false
{"Kotlin": 79018}
package com.example.goalstracker import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.navigation.compose.rememberNavController import com.example.goalstracker.navigation.NavigationHost import com.example.goalstracker.ui.theme.GoalsTrackerTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GoalsTrackerTheme { Surface(modifier=Modifier.fillMaxSize(),color= Color.Transparent) { val navController = rememberNavController() NavigationHost(navController = navController) } } } } }
0
Kotlin
0
0
76a9efc0a96b479629dbee6296d32f23556bb84e
1,128
Daily-Drive
MIT License
src/main/kotlin/tools/aqua/turnkey/plugin/util/Collections.kt
tudo-aqua
860,027,153
false
{"Kotlin": 105116}
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2019-2024 The TurnKey Authors * * 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 tools.aqua.turnkey.plugin.util /** Apply [transform] to all elements in this iterable, gathering the results in a [Set]. */ internal inline fun <T, R> Iterable<T>.mapToSet(transform: (T) -> R): Set<R> = mapTo(LinkedHashSet(), transform) /** Apply [transform] to all elements in this collection, gathering the results in a [Set]. */ internal inline fun <T, R> Collection<T>.mapToSet(transform: (T) -> R): Set<R> = mapTo(LinkedHashSet(size), transform)
0
Kotlin
0
0
aa1e199db82737d171925ee72508b89b58662f81
1,120
turnkey-gradle-plugin
Creative Commons Attribution 4.0 International
app/src/main/java/com/github/dimitarstoyanoff/outdoorsy/data/remote/RemoteApi.kt
DimitarStoyanoff
716,590,174
false
{"Kotlin": 35961}
/* * Copyright 2023 dimitarstoyanoff. * * 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. * * Created by dstoyanov on 09/11/2023. */ package com.github.dimitarstoyanoff.outdoorsy.data.remote import com.github.dimitarstoyanoff.outdoorsy.data.model.RentalsResponse import retrofit2.http.GET import retrofit2.http.Query /** * An interface which defines all remote Retrofit calls with their request/responses. */ interface RemoteApi { /** * Get a list of rentals depending on a criteria. * * @param query search criteria, space-separated. * @param page get a specific page for pagination. * @param limit number of results requested. * @return a [RentalsResponse]. */ @GET("rentals") suspend fun getRentals( @Query("filter[keywords]") query: String? = null, @Query("page[offset]") page: Int? = null, @Query("page[limit]") limit: Int? = null ): RentalsResponse }
0
Kotlin
0
0
fa9ab3ccc4080a83c996eb7351ae8c7f30808ebd
1,478
outdoorsy
Apache License 2.0
langsmith-java-core/src/main/kotlin/com/langsmith/api/services/async/RunManifestServiceAsync.kt
langchain-ai
774,515,765
false
{"Kotlin": 2288977, "Shell": 1314, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.langsmith.api.services.async import com.langsmith.api.core.RequestOptions import com.langsmith.api.models.RunManifestRetrieveParams import com.langsmith.api.models.RunManifestSchema import java.util.concurrent.CompletableFuture interface RunManifestServiceAsync { /** Get a specific run manifest. */ @JvmOverloads fun retrieve( params: RunManifestRetrieveParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<RunManifestSchema> }
1
Kotlin
0
2
922058acd6e168f6e1db8d9e67a24850ab7e93a0
654
langsmith-java
Apache License 2.0