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
ktlint-rules/tst/software/aws/toolkits/ktlint/rules/CopyrightHeaderRuleTest.kt
zaerald
298,881,314
false
null
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.ktlint.rules import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.test.lint import org.assertj.core.api.Assertions.assertThat import org.junit.Test class CopyrightHeaderRuleTest { private val rule = CopyrightHeaderRule() @Test fun noHeaderPresent() { assertThat( rule.lint( """ import a.b.c """.trimIndent() ) ).containsExactly( LintError(1, 1, "copyright-header", "Missing or incorrect file header") ) } @Test fun headerPresent() { assertThat( rule.lint( """ // Copyright 1970 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import a.b.c """.trimIndent() ) ).isEmpty() } }
0
null
0
1
25bb745e59eda0e6304b51f1bd1d8b740915ff07
998
aws-toolkit-jetbrains
Apache License 2.0
module_common/src/main/kotlin/life/chenshi/keepaccounts/module/common/utils/BindingAdapters.kt
SMAXLYB
340,857,932
false
null
package life.chenshi.keepaccounts.module.common.utils import android.graphics.Color import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.DrawableRes import androidx.databinding.BindingAdapter import coil.load import life.chenshi.keepaccounts.module.common.R import java.text.DateFormat import java.util.* /** * 给textView设置文字, 如果为空则隐藏textView */ @BindingAdapter("textWithVisibility") fun bindTextWithVisibility(view: TextView, text: CharSequence?) { view.visibility = if (text.isNullOrEmpty()) { View.GONE } else { view.text = text View.VISIBLE } } @BindingAdapter("nullableText", "defaultText", requireAll = true) fun bindDefaultTextIfNullOrEmpty(view: TextView, nullableText: CharSequence?, defaultText: CharSequence) { view.text = nullableText.takeUnless { it.isNullOrBlank() } ?: defaultText } /** * 按照给定的格式来格式化时间戳, 然后展示在textView上 */ @BindingAdapter("timestamp", "format", requireAll = true) fun bindTimeStampToText(view: TextView, timestamp: Long, format: DateFormat) { view.text = DateUtil.date2String(Date(timestamp), format) } @BindingAdapter("drawableInt") fun bindDrawableRes(imageView: ImageView, @DrawableRes drawableInt: Int) { imageView.load(drawableInt) } @BindingAdapter("gradientColorStr") fun bindGradientColorStr(view: View, colorStr: String?) { if (colorStr == null) { view.setBackgroundResource(R.drawable.common_corner_all_large_primary_gradient) return } view.setShapeWithRippleBackground( view.context.resources.getDimension(R.dimen.common_large_corner_size), Color.parseColor(colorStr), Color.parseColor("#27707070"), true ) }
0
Kotlin
0
2
389632d87e90588555c10682a5804f6fddba5278
1,734
KeepAccount
Apache License 2.0
src/main/kotlin/com/eve/engine/esi4k/model/EffectModifier.kt
EveEngine
254,506,280
false
null
package com.eve.engine.esi4k.model import com.fasterxml.jackson.annotation.JsonProperty open class EffectModifier ( @JsonProperty("domain") val domain: String? = null, @JsonProperty("effect_id") val effectId: Int? = null, @JsonProperty("func") val func: String, @JsonProperty("modified_attribute_id") val modifiedAttributeId: Int? = null, @JsonProperty("modifying_attribute_id") val modifyingAttributeId: Int? = null, @JsonProperty("operator") val operator: Int? = null )
0
Kotlin
0
0
6aba2e43a8dc11b2c435d08b91dc9ed4baf9ea9b
497
esi4k
Apache License 2.0
src/main/java/me/bytebeats/mns/listener/WindowSwitchListener.kt
bytebeats
282,830,790
false
{"Gradle Kotlin DSL": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 30, "Kotlin": 10, "XML": 9, "SVG": 1}
package me.bytebeats.mns.listener import java.awt.event.WindowEvent import java.awt.event.WindowListener /** * @Author bytebeats * @Email <<EMAIL>> * @Github https://github.com/bytebeats * @Created at 2021/9/19 15:58 * @Version 1.0 * @Description To detect whether window is opened or closed */ abstract class WindowSwitchListener : WindowListener { override fun windowClosing(e: WindowEvent?) {} override fun windowIconified(e: WindowEvent?) {} override fun windowDeiconified(e: WindowEvent?) {} override fun windowActivated(e: WindowEvent?) {} override fun windowDeactivated(e: WindowEvent?) {} }
25
Java
52
219
105fe49791ed35d5b9877c9c7d8ec2497147e3e1
632
mns
MIT License
app/src/test/java/_demo/Fast.kt
teamtuna
355,517,555
true
{"Kotlin": 69325, "Batchfile": 117}
package _demo import org.junit.jupiter.api.Tag @Target(AnnotationTarget.FUNCTION, AnnotationTarget.TYPE) @Retention(AnnotationRetention.RUNTIME) @Tag("fast") annotation class Fast
0
Kotlin
2
1
d35524312179bb9b8c85be7c63ba84e31a8fbb6e
181
NumberQuiz
Apache License 2.0
app/src/main/java/com/tfm/musiccommunityapp/ui/dialogs/profile/EditProfileDialog.kt
luiscruzr8
613,985,223
false
null
package com.tfm.musiccommunityapp.ui.dialogs.profile import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.RelativeLayout import androidx.fragment.app.DialogFragment import com.tfm.musiccommunityapp.R import com.tfm.musiccommunityapp.databinding.EditProfileDialogBinding import com.tfm.musiccommunityapp.domain.model.UserDomain import com.tfm.musiccommunityapp.ui.dialogs.common.alertDialogTwoOptions import java.util.regex.Pattern class EditProfileDialog( private val userProfile: UserDomain, private val onSaveClicked: (UserDomain) -> Unit ) : DialogFragment() { private var _binding: EditProfileDialogBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout to use as dialog or embedded fragment val dialogLayout = inflater.inflate(R.layout.edit_profile_dialog, container, false) _binding = EditProfileDialogBinding.bind(dialogLayout) setLayout(userProfile) return dialogLayout } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // the content val root = RelativeLayout(activity) root.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) // creating the fullscreen dialog val dialog = Dialog(root.context) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(root) dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.window!!.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) return dialog } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun extractUpdatedValues(): UserDomain { return userProfile.copy( phone = binding.phoneNumberEditText.text.toString().trim(), bio = binding.bioEditText.text.toString().trim(), interests = emptyList() ) } private fun setLayout(userProfile: UserDomain) { userProfile.apply { binding.usernameEditText.setText(login) binding.usernameTextInputLayout.isEnabled = false binding.emailEditText.setText(email) binding.emailTextInputLayout.isEnabled = false binding.phoneNumberEditText.setText(phone) binding.bioEditText.setText(bio) } binding.dismissButton.setOnClickListener { dismiss() } binding.saveButton.setOnClickListener { if(!validateUpdatedValues()) { return@setOnClickListener } alertDialogTwoOptions(requireContext(), getString(R.string.edit_screen_save_dialog_title), null, getString(R.string.edit_screen_save_dialog_message), getString(R.string.accept), { onSaveClicked(extractUpdatedValues()).run { dismiss() } }, getString(R.string.cancel), { dismiss() } ) } } private fun validateUpdatedValues(): Boolean { var isValid = true //Phone number validation if (binding.phoneNumberEditText.text.isNullOrBlank()) { binding.phoneNumberTextInputLayout.error = getString(R.string.edit_screen_phone_number_required) isValid = false } else if (!isValidPhoneNumber(binding.phoneNumberEditText.text.toString())) { binding.phoneNumberTextInputLayout.error = getString(R.string.edit_screen_phone_number_incorrect_format) isValid = false } else { binding.phoneNumberTextInputLayout.error = null } return isValid } private fun isValidPhoneNumber(text: String): Boolean { val phonePattern: Pattern = Pattern.compile(PHONE_NUMBER_REGEX) return phonePattern.matcher(text).matches() } companion object { const val PHONE_NUMBER_REGEX = "^[0-9]{6,9}\$" } }
28
Kotlin
0
1
e852d00c4b26e54a3f232e1d19b46446dbba4811
4,531
android-musiccommunity
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/DeviceTabletQuestion.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.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.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.DeviceTabletQuestion: ImageVector get() { if (_deviceTabletQuestion != null) { return _deviceTabletQuestion!! } _deviceTabletQuestion = Builder(name = "DeviceTabletQuestion", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 21.0f) horizontalLineToRelative(-9.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f) verticalLineToRelative(-16.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(12.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) verticalLineToRelative(7.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 22.0f) verticalLineToRelative(0.01f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 19.0f) arcToRelative(2.003f, 2.003f, 0.0f, false, false, 0.914f, -3.782f) arcToRelative(1.98f, 1.98f, 0.0f, false, false, -2.414f, 0.483f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.0f, 17.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -2.0f, 0.0f) } } .build() return _deviceTabletQuestion!! } private var _deviceTabletQuestion: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
3,216
compose-icon-collections
MIT License
src/org/jetbrains/kannotator/annotationsInference/mutability/mutabilityAnnotations.kt
JetBrains
5,904,223
false
null
package org.jetbrains.kannotator.controlFlow.builder.analysis.mutability import org.jetbrains.kannotator.controlFlow.builder.analysis.Annotation import org.jetbrains.kannotator.annotationsInference.propagation.TwoElementLattice import org.jetbrains.kannotator.controlFlow.builder.analysis.mutability.MutabilityAnnotation.* enum class MutabilityAnnotation : Annotation { MUTABLE READ_ONLY } private val JB_MUTABLE = "org.jetbrains.kannotator.runtime.annotations.Mutable" private val JB_READ_ONLY = "org.jetbrains.kannotator.runtime.annotations.ReadOnly" fun classNamesToMutabilityAnnotation(canonicalClassNames: Set<String>) : MutabilityAnnotation? { val containsMutable = canonicalClassNames.contains(JB_MUTABLE) val containsImmutable = canonicalClassNames.contains(JB_READ_ONLY) if (containsMutable == containsImmutable) return null return if (containsMutable) MutabilityAnnotation.MUTABLE else MutabilityAnnotation.READ_ONLY } object MutabiltyLattice : TwoElementLattice<MutabilityAnnotation>( small = READ_ONLY, big = MUTABLE )
1
Kotlin
15
34
ef10885ba0a7c84a04dc33aa24dc2eb50abd622f
1,097
kannotator
Apache License 2.0
src/main/kotlin/com/aahzbrut/theater/dto/PerformanceAddRequest.kt
AahzBrut
278,851,524
false
null
package com.aahzbrut.theater.dto class PerformanceAddRequest { var id: Long? = null var title: String? = null }
0
Kotlin
0
0
03698909d908c6ac38bdeaaca658c46a567db765
120
theater
MIT License
data/media/src/main/java/com/afterroot/watchdone/media/MovieStore.kt
thesandipv
255,834,235
false
{"Kotlin": 565099, "Shell": 1180}
/* * Copyright (C) 2020-2023 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.afterroot.watchdone.media import app.tivi.data.db.DatabaseTransactionRunner import app.tivi.data.util.storeBuilder import app.tivi.util.Logger import com.afterroot.watchdone.data.daos.MediaDao import com.afterroot.watchdone.data.daos.getMediaByIdOrThrow import com.afterroot.watchdone.data.model.Media import com.afterroot.watchdone.data.util.mergeMedia import javax.inject.Inject import org.mobilenativefoundation.store.store5.Fetcher import org.mobilenativefoundation.store.store5.SourceOfTruth import org.mobilenativefoundation.store.store5.Store class MovieStore @Inject constructor( mediaDao: MediaDao, tmdbMovieDataSource: TmdbMovieDataSource, transactionRunner: DatabaseTransactionRunner, logger: Logger, ) : Store<Long, Media> by storeBuilder( fetcher = Fetcher.of { id: Long -> val savedMedia = mediaDao.getMediaByIdOrThrow(id) return@of run { tmdbMovieDataSource.getMovie(savedMedia) } }, sourceOfTruth = SourceOfTruth.of( reader = { movieId -> mediaDao.getMediaByIdFlow(movieId) }, writer = { id, response -> logger.d { "Writing in database:media $response" } transactionRunner { mediaDao.upsert( mergeMedia(local = mediaDao.getMediaByIdOrThrow(id), tmdb = response), ) } }, delete = mediaDao::delete, deleteAll = mediaDao::deleteAll, ), ).build()
9
Kotlin
1
5
b52a8c406045372408f45575f281e1920f57a87f
2,099
watchdone
Apache License 2.0
business/src/main/kotlin/com/isystk/sample/common/exception/NoDataFoundException.kt
isystk
328,037,305
false
{"Kotlin": 462354, "TypeScript": 88591, "HTML": 77276, "SCSS": 24557, "FreeMarker": 21801, "JavaScript": 5293, "Shell": 3607, "Dockerfile": 1581, "CSS": 942}
package com.isystk.sample.common.exception /** * ファイル不存在エラー */ class FileNotFoundException : RuntimeException { /** * コンストラクタ */ constructor(message: String?) : super(message) {} /** * コンストラクタ */ constructor(e: Exception?) : super(e) {} companion object { private const val serialVersionUID = -6212475941372852475L } }
0
Kotlin
0
2
2e4e0c62af22c05403e5d3452ba08eb09c05a7f1
375
kotlin-springboot-boilerplate
MIT License
app/src/main/java/com/example/labratour/presentation/model/dao/PlaceDao.kt
Arye182
363,609,024
false
null
package com.example.labratour.presentation.model.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.labratour.presentation.model.data.PlaceGoogleModel @Dao interface PlaceDao { @Query("SELECT * FROM places WHERE id = :id_place") fun getPlace(id_place: String): PlaceGoogleModel @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertPlaces(places: List<PlaceGoogleModel>) @Query("DELETE FROM places") suspend fun deleteAllPlaces() }
0
Kotlin
0
1
29339a2c4da4db799ab87006794695e11ea36c9b
566
LabraTour
MIT License
kaverit/src/jvmMain/kotlin/org/kodein/type/JVMUtils.kt
kosi-libs
236,804,204
false
null
package org.kodein.type import java.lang.reflect.* /** * The JVM type that is wrapped by a TypeToken. */ public val TypeToken<*>.jvmType: Type get() = when (this) { is JVMAbstractTypeToken -> jvmType else -> throw IllegalStateException("${javaClass.simpleName} is not a JVM Type Token") } internal val ParameterizedType.rawClass get() = rawType as Class<*> @OptIn(ExperimentalStdlibApi::class) internal fun ParameterizedType.reify(parent: Type, originType: ParameterizedType? = null, realTypeArguments: Array<Type>? = null): Type { if (parent !is ParameterizedType) return parent /* Keep the reference to the encapsulating type e.g. for Set<Map<Int, String>> _originType -> Set<? extends T> _originRawClass -> java.util.Set _realTypeArguments -> [Int, String] */ val _originType = originType ?: this val _originRawClass = originType?.rawClass ?: rawClass val _realTypeArguments = realTypeArguments ?: actualTypeArguments return ParameterizedTypeImpl( parent.rawClass, buildList { parent.actualTypeArguments.forEach { arg -> when (arg) { /* In case the type argument is TypeVariable e.g. T, E, V, K... */ is TypeVariable<*> -> { _originRawClass.typeParameters.indexOf(arg).takeIf { it >= 0 }?.let { add((_realTypeArguments)[it].kodein()) } } /* In case the type argument is WildcardType and first upperBounds extends a ParameterizedType or TypeVariable e.g. ? extends Set, ? extends Map, ? extends T, ? extends V... */ is WildcardType -> { arg.upperBounds[0]?.also { upperBound -> when (upperBound) { is ParameterizedType -> { add(upperBound.reify(upperBound, _originType, _realTypeArguments)) } is TypeVariable<*> -> { _originRawClass.typeParameters.indexOf(upperBound) .takeIf { it >= 0 }?.let { add((_realTypeArguments)[it].kodein()) } } } } } /* In case the type argument is ParameterizedType e.g. Set<? extends E> */ is ParameterizedType -> add(arg.reify(arg, _originType, _realTypeArguments)) else -> add(arg.kodein()) } } } .toTypedArray(), parent.ownerType.kodein() ) } internal fun Type.removeVariables(): Type { if (this !is ParameterizedType) return this return ParameterizedTypeImpl( rawClass, actualTypeArguments.map { arg -> if (arg is TypeVariable<*>) Any::class.java else arg.kodein() } .toTypedArray(), ownerType.kodein() ) } internal val TypeVariable<*>.firstBound: Type get() = (bounds[0] as? TypeVariable<*>)?.firstBound ?: bounds[0] internal val Class<*>.boundedGenericSuperClass: Type? get() { val parent = genericSuperclass ?: return superclass if (parent !is ParameterizedType) return parent return ParameterizedTypeImpl( parent.rawClass, parent.actualTypeArguments.map { (it as? TypeVariable<*>)?.firstBound ?: it } .toTypedArray(), parent.ownerType ) } internal fun Type.typeHashCode(): Int = when(this) { is Class<*> -> this.hashCode() is ParameterizedType -> actualTypeArguments.fold(rawClass.typeHashCode()) { hash, arg -> hash * 31 + arg.typeHashCode() } is WildcardType -> (this.upperBounds + this.lowerBounds).fold(17) { hash, arg -> hash * 19 + arg.typeHashCode() } is GenericArrayType -> 53 + this.genericComponentType.typeHashCode() is TypeVariable<*> -> bounds.fold(23) { hash, arg -> hash * 29 + arg.typeHashCode() } else -> this.hashCode() } internal fun Type.typeEquals(other: Type): Boolean { return when (this) { is Class<*> -> this == other is ParameterizedType -> { if (other !is ParameterizedType) return false rawClass.typeEquals(other.rawClass) && ( actualTypeArguments.allTypeEquals(other.actualTypeArguments) || boundedTypeArguments().allTypeEquals(other.boundedTypeArguments()) ) } is WildcardType -> { if (other !is WildcardType) return false lowerBounds.allTypeEquals(other.lowerBounds) && upperBounds.allTypeEquals(other.upperBounds) } is GenericArrayType -> { if (other !is GenericArrayType) return false genericComponentType.typeEquals(other.genericComponentType) } is TypeVariable<*> -> { if (other !is TypeVariable<*>) return false bounds.allTypeEquals(other.bounds) } else -> this == other } } private fun ParameterizedType.boundedTypeArguments() = actualTypeArguments.map { if (it is WildcardType) it.upperBounds.firstOrNull() ?: Any::class.java else it } .toTypedArray() private fun Array<Type>.allTypeEquals(other: Array<Type>): Boolean { if (size != other.size) return false return indices.all { this[it].typeEquals(other[it]) } } @Suppress("UNCHECKED_CAST") @PublishedApi internal fun <T : Type?> T.kodein(): T = when (this) { is ParameterizedType -> ParameterizedTypeImpl(this) is GenericArrayType -> GenericArrayTypeImpl(this) else -> this } as T internal fun Class<*>.jvmArrayType(): Class<*> { val descriptor = if (isPrimitive) { when (this) { Boolean::class.javaPrimitiveType -> "[Z" Byte::class.javaPrimitiveType -> "[B" Char::class.javaPrimitiveType -> "[C" Short::class.javaPrimitiveType -> "[S" Int::class.javaPrimitiveType -> "[I" Long::class.javaPrimitiveType -> "[J" Float::class.javaPrimitiveType -> "[F" Double::class.javaPrimitiveType -> "[D" else -> error("Unknown primitive type $this") } } else { "[L$name;" } return Class.forName(descriptor) } public fun TypeToken<*>.primitiveType(): TypeToken<*> { if (jvmType !is Class<*>) error("$this does not represent a boxed primitive type") return typeToken( (jvmType as Class<*>).kotlin.javaPrimitiveType ?: error("$this does not represent a boxed primitive type") ) }
0
Kotlin
1
9
53a88e677a16e4ccd095a4db1108f22e76546fe2
7,112
Kaverit
MIT License
example/src/main/kotlin/com/expedia/graphql/sample/model/ContextualResponse.kt
d4rken
157,257,082
false
null
package com.expedia.graphql.sample.model import com.expedia.graphql.annotations.GraphQLDescription @GraphQLDescription("simple response that contains value read from context") data class ContextualResponse(val passedInValue: Int, val contextValue: String)
0
null
0
2
1d78a129b7f8e7b01c4bed063076a215ca4b29be
258
graphql-kotlin
Apache License 2.0
feature/employee_absent/src/main/kotlin/com/niyaj/employeeAbsent/AbsentScreen.kt
skniyajali
644,752,474
false
{"Kotlin": 4945599, "Shell": 8001, "Java": 232}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.niyaj.employeeAbsent import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.FabPosition import androidx.compose.material3.SnackbarHostState 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.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.niyaj.common.tags.AbsentScreenTags.ABSENT_LIST import com.niyaj.common.tags.AbsentScreenTags.ABSENT_NOT_AVAILABLE import com.niyaj.common.tags.AbsentScreenTags.ABSENT_SCREEN_TITLE import com.niyaj.common.tags.AbsentScreenTags.ABSENT_SEARCH_PLACEHOLDER import com.niyaj.common.tags.AbsentScreenTags.CREATE_NEW_ABSENT import com.niyaj.common.tags.AbsentScreenTags.DELETE_ABSENT_MESSAGE import com.niyaj.common.tags.AbsentScreenTags.DELETE_ABSENT_TITLE import com.niyaj.common.utils.Constants.SEARCH_ITEM_NOT_FOUND import com.niyaj.designsystem.theme.PoposRoomTheme import com.niyaj.employeeAbsent.components.AbsentEmployeeList import com.niyaj.employeeAbsent.destinations.AbsentExportScreenDestination import com.niyaj.employeeAbsent.destinations.AbsentImportScreenDestination import com.niyaj.employeeAbsent.destinations.AbsentSettingsScreenDestination import com.niyaj.employeeAbsent.destinations.AddEditAbsentScreenDestination import com.niyaj.model.EmployeeWithAbsents import com.niyaj.ui.components.ItemNotAvailable import com.niyaj.ui.components.LoadingIndicator import com.niyaj.ui.components.PoposPrimaryScaffold import com.niyaj.ui.components.ScaffoldNavActions import com.niyaj.ui.components.StandardDialog import com.niyaj.ui.components.StandardFAB import com.niyaj.ui.event.UiState import com.niyaj.ui.parameterProvider.AbsentPreviewParameter import com.niyaj.ui.utils.DevicePreviews import com.niyaj.ui.utils.Screens import com.niyaj.ui.utils.TrackScreenViewEvent import com.niyaj.ui.utils.UiEvent import com.niyaj.ui.utils.isScrolled import com.ramcosta.composedestinations.annotation.Destination import com.ramcosta.composedestinations.annotation.RootNavGraph import com.ramcosta.composedestinations.navigation.DestinationsNavigator import com.ramcosta.composedestinations.result.NavResult import com.ramcosta.composedestinations.result.ResultRecipient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @RootNavGraph(start = true) @Destination(route = Screens.ABSENT_SCREEN) @Composable fun AbsentScreen( navigator: DestinationsNavigator, viewModel: AbsentViewModel = hiltViewModel(), resultRecipient: ResultRecipient<AddEditAbsentScreenDestination, String>, exportRecipient: ResultRecipient<AbsentExportScreenDestination, String>, importRecipient: ResultRecipient<AbsentImportScreenDestination, String>, ) { val scope = rememberCoroutineScope() val snackbarState = remember { SnackbarHostState() } val uiState by viewModel.absents.collectAsStateWithLifecycle() val showSearchBar by viewModel.showSearchBar.collectAsStateWithLifecycle() val event by viewModel.eventFlow.collectAsStateWithLifecycle(initialValue = null) AbsentScreenContent( uiState = uiState, selectedItems = viewModel.selectedItems.toList(), selectedEmployees = viewModel.selectedEmployee.toList(), showSearchBar = showSearchBar, searchText = viewModel.searchText.value, onClickSearchIcon = viewModel::openSearchBar, onSearchTextChanged = viewModel::searchTextChanged, onClickClear = viewModel::clearSearchText, onCloseSearchBar = viewModel::closeSearchBar, onClickSelectItem = viewModel::selectItem, onClickSelectAll = viewModel::selectAllItems, onClickDeselect = viewModel::deselectItems, onClickDelete = viewModel::deleteItems, onClickBack = navigator::popBackStack, onNavigateToScreen = navigator::navigate, onClickCreateNew = { navigator.navigate(AddEditAbsentScreenDestination()) }, onClickEdit = { navigator.navigate(AddEditAbsentScreenDestination(it)) }, onClickSettings = { navigator.navigate(AbsentSettingsScreenDestination()) }, onSelectEmployee = viewModel::selectEmployee, onAbsentAddClick = { navigator.navigate(AddEditAbsentScreenDestination(employeeId = it)) }, modifier = Modifier, snackbarState = snackbarState, ) HandleResultRecipients( resultRecipient = resultRecipient, exportRecipient = exportRecipient, importRecipient = importRecipient, event = event, onDeselectItems = viewModel::deselectItems, coroutineScope = scope, snackbarHostState = snackbarState, ) } @androidx.annotation.VisibleForTesting @Composable internal fun AbsentScreenContent( uiState: UiState<List<EmployeeWithAbsents>>, selectedItems: List<Int>, selectedEmployees: List<Int>, showSearchBar: Boolean, searchText: String, onClickSearchIcon: () -> Unit, onSearchTextChanged: (String) -> Unit, onClickClear: () -> Unit, onCloseSearchBar: () -> Unit, onClickSelectItem: (Int) -> Unit, onClickSelectAll: () -> Unit, onClickDeselect: () -> Unit, onClickDelete: () -> Unit, onClickBack: () -> Unit, onNavigateToScreen: (String) -> Unit, onClickCreateNew: () -> Unit, onClickEdit: (Int) -> Unit, onClickSettings: () -> Unit, onSelectEmployee: (Int) -> Unit, onAbsentAddClick: (Int) -> Unit, modifier: Modifier = Modifier, snackbarState: SnackbarHostState = remember { SnackbarHostState() }, scope: CoroutineScope = rememberCoroutineScope(), lazyListState: LazyListState = rememberLazyListState(), ) { TrackScreenViewEvent(screenName = Screens.ABSENT_SCREEN) BackHandler { if (selectedItems.isNotEmpty()) { onClickDeselect() } else if (showSearchBar) { onCloseSearchBar() } else { onClickBack() } } val showFab = uiState is UiState.Success val openDialog = remember { mutableStateOf(false) } PoposPrimaryScaffold( modifier = modifier, currentRoute = Screens.ABSENT_SCREEN, title = if (selectedItems.isEmpty()) ABSENT_SCREEN_TITLE else "${selectedItems.size} Selected", floatingActionButton = { StandardFAB( fabVisible = (showFab && selectedItems.isEmpty() && !showSearchBar), onFabClick = onClickCreateNew, onClickScroll = { scope.launch { lazyListState.animateScrollToItem(0) } }, showScrollToTop = lazyListState.isScrolled, fabText = CREATE_NEW_ABSENT, ) }, navActions = { ScaffoldNavActions( placeholderText = ABSENT_SEARCH_PLACEHOLDER, showSettingsIcon = true, selectionCount = selectedItems.size, showSearchBar = showSearchBar, showSearchIcon = showFab, searchText = searchText, onEditClick = { onClickEdit(selectedItems.first()) }, onDeleteClick = { openDialog.value = true }, onSettingsClick = onClickSettings, onSelectAllClick = onClickSelectAll, onClearClick = onClickClear, onSearchIconClick = onClickSearchIcon, onSearchTextChanged = onSearchTextChanged, ) }, fabPosition = if (lazyListState.isScrolled) FabPosition.End else FabPosition.Center, selectionCount = selectedItems.size, showBackButton = showSearchBar, onDeselect = onClickDeselect, onBackClick = if (showSearchBar) onCloseSearchBar else onClickBack, snackbarHostState = snackbarState, onNavigateToScreen = onNavigateToScreen, ) { Crossfade( targetState = uiState, label = "AbsentList::UiState", ) { state -> when (state) { is UiState.Loading -> LoadingIndicator() is UiState.Empty -> { ItemNotAvailable( text = if (searchText.isEmpty()) ABSENT_NOT_AVAILABLE else SEARCH_ITEM_NOT_FOUND, buttonText = CREATE_NEW_ABSENT, onClick = onClickCreateNew, ) } is UiState.Success -> { AbsentEmployeeList( items = state.data, expanded = selectedEmployees::contains, onExpandChanged = onSelectEmployee, doesSelected = selectedItems::contains, onClick = { if (selectedItems.isNotEmpty()) { onClickSelectItem(it) } }, onLongClick = onClickSelectItem, modifier = Modifier.testTag(ABSENT_LIST), showTrailingIcon = true, onChipClick = onAbsentAddClick, lazyListState = lazyListState, ) } } } } AnimatedVisibility( visible = openDialog.value, ) { StandardDialog( title = DELETE_ABSENT_TITLE, message = DELETE_ABSENT_MESSAGE, onConfirm = { openDialog.value = false onClickDelete() }, onDismiss = { openDialog.value = false onClickDeselect() }, ) } } @Composable private fun HandleResultRecipients( resultRecipient: ResultRecipient<AddEditAbsentScreenDestination, String>, exportRecipient: ResultRecipient<AbsentExportScreenDestination, String>, importRecipient: ResultRecipient<AbsentImportScreenDestination, String>, event: UiEvent?, onDeselectItems: () -> Unit, coroutineScope: CoroutineScope = rememberCoroutineScope(), snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, ) { resultRecipient.onNavResult { result -> when (result) { is NavResult.Canceled -> { onDeselectItems() } is NavResult.Value -> { onDeselectItems() coroutineScope.launch { snackbarHostState.showSnackbar(result.value) } } } } exportRecipient.onNavResult { result -> when (result) { is NavResult.Canceled -> {} is NavResult.Value -> { coroutineScope.launch { snackbarHostState.showSnackbar(result.value) } } } } importRecipient.onNavResult { result -> when (result) { is NavResult.Canceled -> {} is NavResult.Value -> { coroutineScope.launch { snackbarHostState.showSnackbar(result.value) } } } } LaunchedEffect(key1 = event) { event?.let { data -> when (data) { is UiEvent.OnError -> { coroutineScope.launch { snackbarHostState.showSnackbar(data.errorMessage) } } is UiEvent.OnSuccess -> { coroutineScope.launch { snackbarHostState.showSnackbar(data.successMessage) } } } } } } @DevicePreviews @Composable private fun AbsentScreenPreview( @PreviewParameter(AbsentPreviewParameter::class) uiState: UiState<List<EmployeeWithAbsents>>, modifier: Modifier = Modifier, ) { PoposRoomTheme { AbsentScreenContent( uiState = uiState, selectedItems = listOf(), selectedEmployees = listOf(1, 2, 3), showSearchBar = false, searchText = "", onClickSearchIcon = {}, onSearchTextChanged = {}, onClickClear = {}, onCloseSearchBar = {}, onClickSelectItem = {}, onClickSelectAll = {}, onClickDeselect = {}, onClickDelete = {}, onClickBack = {}, onNavigateToScreen = {}, onClickCreateNew = {}, onClickEdit = {}, onClickSettings = {}, onSelectEmployee = {}, onAbsentAddClick = {}, modifier = modifier, ) } }
42
Kotlin
0
1
a64f2043b4de365f05edc06344393083e0fed4d3
13,996
PoposRoom
Apache License 2.0
app/src/main/java/com/github/pwcong/jpstart/mvp/model/BaseModel.kt
pwcong
69,102,440
false
{"Kotlin": 123508}
package com.github.pwcong.jpstart.mvp.model import com.github.pwcong.jpstart.mvp.bean.BannerItem import com.github.pwcong.jpstart.mvp.bean.JPItem import com.github.pwcong.jpstart.mvp.bean.JPTab import rx.Subscriber interface BaseModel<T> { val data: List<T> interface MainActivityModel : BaseModel<BannerItem> interface JPStartTabFragmentModel : BaseModel<JPTab> interface JPStartFragmentModel { fun getData(category: Int, subscriber: Subscriber<List<JPItem>>) } interface MemoryFragmentModel { val qingYinWithoutHeader: List<JPItem> val zhuoYinWithoutHeader: List<JPItem> val aoYinWithoutHeader: List<JPItem> } interface PuzzleActivityModel { val options: Array<String> val items: List<JPItem> } }
0
Kotlin
3
10
6045b02fb36257d9c7fb009f2ba8c385b3a5eb1f
794
JPStart
Apache License 2.0
uicomponents/src/main/java/com/example/uicomponents/models/FloatingAlert.kt
perrystreetsoftware
538,729,133
false
{"Kotlin": 78968}
package com.example.uicomponents.models sealed class FloatingAlert { data class Dialog(val state: DialogUiState): FloatingAlert() data class Toast(val state: ToastUiState): FloatingAlert() }
1
Kotlin
2
4
35fc57c12af88a1046f690d983b1b4275adf1ac1
200
DemoAppAndroid
MIT License
app/src/main/java/com/anthony/foodmap/model/Category.kt
anthony0982
238,707,081
false
null
package com.anthony.foodmap.model data class Category (val id:String, val name:String, val icon: Icon)
0
Kotlin
0
0
ccebae3a5e784e69c352c1e93add91a500cd0529
103
Food-Map
Apache License 2.0
app/src/main/java/app/tivi/showdetails/details/ShowDetailsFragment.kt
jdtremblay
175,612,450
true
{"Kotlin": 646033, "Dockerfile": 1796, "Shell": 1630, "Java": 737}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.showdetails.details import android.annotation.SuppressLint import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.constraintlayout.motion.widget.MotionLayout import androidx.core.os.bundleOf import androidx.core.view.isGone import androidx.core.view.isVisible import app.tivi.R import app.tivi.SharedElementHelper import app.tivi.data.entities.ActionDate import app.tivi.data.entities.Episode import app.tivi.data.entities.Season import app.tivi.data.entities.TiviShow import app.tivi.databinding.FragmentShowDetailsBinding import app.tivi.extensions.forEachConstraintSet import app.tivi.showdetails.ShowDetailsNavigator import app.tivi.util.TiviMvRxFragment import com.airbnb.mvrx.MvRx import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState import kotlinx.android.parcel.Parcelize import javax.inject.Inject class ShowDetailsFragment : TiviMvRxFragment() { companion object { @JvmStatic fun create(id: Long): ShowDetailsFragment { return ShowDetailsFragment().apply { arguments = bundleOf(MvRx.KEY_ARG to Arguments(id)) } } } @Parcelize data class Arguments(val showId: Long) : Parcelable private val viewModel: ShowDetailsFragmentViewModel by fragmentViewModel() @Inject lateinit var showDetailsViewModelFactory: ShowDetailsFragmentViewModel.Factory @Inject lateinit var controller: ShowDetailsEpoxyController @Inject lateinit var showDetailsNavigator: ShowDetailsNavigator @Inject lateinit var textCreator: ShowDetailsTextCreator private lateinit var binding: FragmentShowDetailsBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentShowDetailsBinding.inflate(inflater, container, false) binding.setLifecycleOwner(viewLifecycleOwner) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.textCreator = textCreator binding.detailsMotion.setOnApplyWindowInsetsListener { _, insets -> binding.detailsMotion.forEachConstraintSet { it.constrainHeight(R.id.details_status_bar_anchor, insets.systemWindowInsetTop) } binding.detailsMotion.rebuildMotion() // Just return insets insets } // Finally, request some insets view.requestApplyInsets() // Make the MotionLayout draw behind the status bar binding.detailsMotion.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE binding.detailsMotion.setTransitionListener(object : MotionLayout.TransitionListener { override fun onTransitionStarted(motionLayout: MotionLayout, startId: Int, endId: Int) { } override fun onTransitionChange(motionLayout: MotionLayout, startId: Int, endId: Int, progress: Float) { binding.detailsAppbarBackground.cutProgress = 1f - progress binding.detailsPoster.visibility = View.VISIBLE } override fun onTransitionTrigger(motionLayout: MotionLayout?, p1: Int, p2: Boolean, p3: Float) { } @SuppressLint("RestrictedApi") override fun onTransitionCompleted(motionLayout: MotionLayout, currentId: Int) { when (currentId) { R.id.end -> { binding.detailsAppbarBackground.cutProgress = 0f binding.detailsPoster.isGone = true binding.detailsFollowFab.isGone = true } R.id.start -> { binding.detailsAppbarBackground.cutProgress = 1f binding.detailsPoster.isVisible = true binding.detailsFollowFab.isVisible = true } } } }) binding.detailsFollowFab.setOnClickListener { viewModel.onToggleMyShowsButtonClicked() } binding.detailsToolbar.setNavigationOnClickListener { viewModel.onUpClicked(showDetailsNavigator) } controller.callbacks = object : ShowDetailsEpoxyController.Callbacks { override fun onRelatedShowClicked(show: TiviShow, view: View) { viewModel.onRelatedShowClicked( showDetailsNavigator, show, SharedElementHelper().apply { addSharedElement(view, "poster") } ) } override fun onEpisodeClicked(episode: Episode, view: View) { viewModel.onRelatedShowClicked(showDetailsNavigator, episode) } override fun onMarkSeasonUnwatched(season: Season) = viewModel.onMarkSeasonUnwatched(season) override fun onMarkSeasonWatched(season: Season, onlyAired: Boolean, date: ActionDate) { viewModel.onMarkSeasonWatched(season, onlyAired, date) } override fun toggleSeasonExpanded(season: Season) { viewModel.toggleSeasonExpanded(season) } } binding.detailsRv.setController(controller) } override fun invalidate() { withState(viewModel) { if (binding.state == null) { // First time we've had state, start any postponed transitions scheduleStartPostponedTransitions() } binding.state = it controller.setData(it) } } }
0
Kotlin
0
0
8082baae65c5dec574b109f0d8b45e8670775ee9
6,461
tivi
Apache License 2.0
app/src/main/java/com/example/todolist_app/domain/usecase/TodoListUseCase.kt
dev-baik
806,409,435
false
{"Kotlin": 45840}
package com.example.todolist_app.domain.usecase import com.example.todolist_app.domain.model.TodoList import com.example.todolist_app.domain.repository.TodoListRepository import javax.inject.Inject class TodoListUseCase @Inject constructor( private val todoListRepository: TodoListRepository ) { fun loadList() = todoListRepository.loadList() suspend fun save(item: TodoList) = todoListRepository.save(item) suspend fun delete(item: TodoList) = todoListRepository.delete(item) }
0
Kotlin
0
0
ecec41e90984e3d35d97fd9245c13187b56332fa
500
TodoList-App
Apache License 2.0
src/commonMain/kotlin/node/variable/NodeNumber.kt
waterstopper
452,776,841
false
{"Kotlin": 301038, "JavaScript": 239}
package node.variable import node.Node import properties.primitive.PDouble import properties.primitive.PInt import table.SymbolTable class NodeNumber(value: String, position: Pair<Int, Int>, val number: Number, val isDouble: Boolean = false) : Node("(NUMBER)", value, position) { override fun evaluate(symbolTable: SymbolTable) = if (isDouble) PDouble(number.toDouble()) else PInt(number.toInt()) }
8
Kotlin
1
3
6ad6ea19c3a79b19c3f747a40a12d64c159997f1
418
Regina
MIT License
lib/src/main/java/de/sipgate/federmappe/FirebaseTimestampDecoder.kt
sipgate
729,069,301
false
{"Kotlin": 67816}
package de.sipgate.federmappe.firestore import com.google.firebase.Timestamp import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerializationException import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.AbstractDecoder import kotlinx.serialization.encoding.CompositeDecoder import kotlinx.serialization.modules.EmptySerializersModule import kotlinx.serialization.modules.SerializersModule @ExperimentalSerializationApi class FirebaseTimestampDecoder( private val timestamp: Timestamp, override val serializersModule: SerializersModule = EmptySerializersModule(), ) : AbstractDecoder() { internal enum class DecodeState { DECODE_SECONDS, DECODE_NANOS, END_OF_STRUCTURE, ; fun advance() = when (this) { DECODE_SECONDS -> DECODE_NANOS DECODE_NANOS -> END_OF_STRUCTURE else -> END_OF_STRUCTURE } } private var decodeState = DecodeState.DECODE_SECONDS override fun decodeSequentially(): Boolean = true override fun decodeCollectionSize(descriptor: SerialDescriptor): Int = 2 override fun decodeValue(): Any = when (decodeState) { DecodeState.DECODE_SECONDS -> timestamp.seconds DecodeState.DECODE_NANOS -> timestamp.nanoseconds else -> throw SerializationException("Serializer read after end of structure!") }.also { decodeState = decodeState.advance() } // This method will most likely never be called because decodeSequentially returns true override fun decodeElementIndex(descriptor: SerialDescriptor): Int = when (decodeState) { DecodeState.DECODE_SECONDS -> 0 DecodeState.DECODE_NANOS -> 1 DecodeState.END_OF_STRUCTURE -> CompositeDecoder.DECODE_DONE } }
2
Kotlin
0
0
b751f83af504bc43cd0b6787a5f12d2240b5f058
1,899
federmappe
Apache License 2.0
headlesswifimanager/src/main/java/com/wideverse/headlesswifimanager/interfaces/AdvertisingCallback.kt
wideverse
177,209,814
false
null
/* * Copyright 2019 Wideverse * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wideverse.headlesswifimanager.interfaces import java.lang.Exception interface AdvertisingCallback{ /** * The procedure has been interrupted by an error */ fun onError(e: Exception) /** * Successfully connected to WiFi */ fun onSuccess() // TODO: consider passing wifi info here for user /** * Successfully started advertising on Nearby */ fun onAdvertisingStarted() }
0
Kotlin
12
117
ab469a59faf234c428fc2c07e9ea5ca88e752081
1,031
headless-wifi-manager
Apache License 2.0
one.lfa.updater.inventory.api/src/main/java/one/lfa/updater/inventory/api/InventoryExternalStorageServiceType.kt
AULFA
189,855,520
false
{"Git Config": 1, "Gradle": 28, "INI": 28, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 213, "Java": 17, "XML": 98, "Java Properties": 4, "Text": 1, "YAML": 3}
package one.lfa.updater.inventory.api import java.io.File import java.net.URI /** * A service that interfaces with Android's "external storage" directories. */ interface InventoryExternalStorageServiceType { companion object { /** * The URI scheme used to denote external storage files. */ val uriScheme: String = "lfaUpdaterExternal" } /** * Find all of the external storage directories. */ fun allDirectories(): List<File> /** * Find the external storage directory, if any, that starts with `mount`. */ fun findDirectoryFor( mount: File ): File? /** * Find the given file for an `lfaUpdaterExternal` URI. */ fun findFile( uri: URI ): File? }
2
null
1
1
5cde488e4e9f9e60f5737d9e1a8fc8817f6b22a8
722
updater
Apache License 2.0
tracker/tracker_domain/src/main/java/com/example/tracker_domain/use_case/TrackFood.kt
Mzazi25
607,523,553
false
null
package com.example.tracker_domain.use_case import com.example.tracker_domain.model.MealType import com.example.tracker_domain.model.TrackableFood import com.example.tracker_domain.model.TrackedFood import com.example.tracker_domain.repository.TrackerRepository import java.time.LocalDate import java.time.temporal.TemporalAmount import kotlin.math.roundToInt class TrackFood( private val repository: TrackerRepository ){ suspend operator fun invoke( food: TrackableFood, amount: Int, mealType: MealType, date: LocalDate ){ repository.insertTrackedFood( TrackedFood( name = food.name, carbs = ((food.carbsPer100g /100f) * amount).roundToInt(), proteins = ((food.proteinPer100g /100f) * amount).roundToInt(), fats = ((food.fatPer100g /100f) * amount).roundToInt(), calories = ((food.caloriesPer100g /100f) * amount).roundToInt(), imageUrl = food.imageUrl, mealType = mealType, amount = amount, date = date) ) } }
0
Kotlin
0
1
2ed698bdbadaae5b2e4edb81ade0ab6930ee84fe
1,121
CalorieTracker
The Unlicense
src/main/kotlin/io/github/kezhenxu94/cache/lite/GenericCache.kt
kezhenxu94
135,662,994
false
null
package com.superwall.sdk.storage.memory /** * Copyright 2020 kezhenxu94 * * 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. */ /** * A Generic K,V [GenericCache] defines the basic operations to a cache. */ interface GenericCache<K, V> { /** * The number of the items that are currently cached. */ val size: Int /** * Cache a [value] with a given [key] */ operator fun set(key: K, value: V) /** * Get the cached value of a given [key], or null if it's not cached or evicted. */ operator fun get(key: K): V? /** * Remove the value of the [key] from the cache, and return the removed value, or null if it's not cached at all. */ fun remove(key: K): V? /** * Remove all the items in the cache. */ fun clear() }
6
null
3
97
99d04f862285f8a079d2283ef0d090047d40189e
1,309
cache-lite
Apache License 2.0
router-compiler/src/main/java/me/reezy/router/processor/RouteProcessor.kt
czy1121
348,677,507
false
null
package me.reezy.router.processor import com.google.auto.service.AutoService import com.squareup.kotlinpoet.* import me.reezy.router.annotation.Route import java.io.File import javax.annotation.processing.* import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import javax.lang.model.util.Elements import javax.lang.model.util.Types private const val WARNINGS = """ *************************************************** * THIS CODE IS GENERATED BY Router, DO NOT EDIT. * *************************************************** """ private const val PKG = "me.reezy.router" private const val PKG_GEN = "$PKG.generated" private const val PKG_ANN = "$PKG.annotation" @AutoService(Processor::class) @SupportedOptions("moduleName") @SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedAnnotationTypes(value = ["$PKG_ANN.Route"]) class RouteProcessor : AbstractProcessor() { private val routes = mutableSetOf<String>() protected lateinit var mElements: Elements protected lateinit var mTypes: Types protected lateinit var mLogger: Logger protected lateinit var mFormattedModuleName: String protected lateinit var mOriginalModuleName: String override fun init(env: ProcessingEnvironment) { super.init(env) mElements = env.elementUtils mTypes = env.typeUtils mLogger = Logger(env.messager, PKG) val options = env.options if (options.isNotEmpty()) { mOriginalModuleName = options["moduleName"] ?: "" mFormattedModuleName = mOriginalModuleName.replace("[^0-9a-zA-Z_]+".toRegex(), "") } mLogger.info("[$mOriginalModuleName] ${this::class.java.simpleName} init") } override fun process(set: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { if (set.isEmpty()) { return false } if (mOriginalModuleName.isBlank()) { mLogger.warning("this module name is null!!! skip this module!!") return false } try { mLogger.info("[$mOriginalModuleName] ${this::class.java.simpleName} process!!!") generate(roundEnv) } catch (e: Exception) { mLogger.error(e) } return true } private fun FileSpec.writeFile() { val outputFile = File(processingEnv.options["kapt.kotlin.generated"]) outputFile.mkdirs() writeTo(outputFile.toPath()) } private fun generate(roundEnv: RoundEnvironment) { routes.clear() val elements = roundEnv.getElementsAnnotatedWith(Route::class.java) if (elements.isEmpty()) { return } mLogger.info("Found ${elements.size} routes in [$mOriginalModuleName]") val tmActivity = mElements.getTypeElement("android.app.Activity").asType() val tmHandler = mElements.getTypeElement("$PKG.RouteCall").asType() // val tmRouter = mElements.getTypeElement("$PKG.Router").asType() val tmRouteTable = mElements.getTypeElement("$PKG.internal.RouteTable").asType() val funcSpec = FunSpec.builder("load").addParameter("rt", tmRouteTable.asTypeName()) elements.forEach { val annotation = it.getAnnotation(Route::class.java) // val paths = arrayOf(annotation.value) + annotation.routes val paths = (arrayOf(annotation.value) + annotation.routes).filter { path -> if (path.isEmpty()) { // mLogger.info("The route path is empty, so skip ${it.asType()}") return@filter false } if (routes.contains(path)) { mLogger.warning("The route path $path already exists, so skip ${it.asType()}") return@filter false } return@filter true }.toTypedArray() if (paths.isEmpty()) { mLogger.info("The route paths is empty, so skip ${it.asType()}") return@forEach } if (mTypes.isSubtype(it.asType(), tmActivity) || mTypes.isSubtype(it.asType(), tmHandler)) { mLogger.info("Found ${it.asType()}") routes.addAll(paths) funcSpec.addStatement("rt.add(%T::class.java, %L, %L, %L)", it.asType(), paths.format(), annotation.interceptors.format(), annotation.flags) } else { mLogger.info("Unknown route type, so skip ${it.asType()}") } } val typeSpec = TypeSpec.classBuilder("RouteLoader_$mFormattedModuleName") .addKdoc(WARNINGS) .addFunction(funcSpec.build()) .build() val kotlinFile = FileSpec.builder(PKG_GEN, "RouteLoader_$mFormattedModuleName") .addType(typeSpec) .build() kotlinFile.writeFile() } private fun Array<String>.format(): String { if (isEmpty()) { return "null" } return joinToString("\", \"", "arrayOf(\"", "\")") } }
0
Kotlin
0
3
da94bec47c641aff3099da3ad0e943f18120f6ba
5,089
router
Apache License 1.1
ui/ui-test/src/main/java/androidx/ui/test/android/AndroidSemanticsTreeInteraction.kt
FYI-Google
258,765,297
false
null
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.ui.test.android import android.R import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Handler import android.os.Looper import android.os.SystemClock import android.view.Choreographer import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.compose.Recomposer import androidx.test.espresso.Espresso import androidx.test.espresso.NoMatchingViewException import androidx.test.espresso.ViewAssertion import androidx.test.espresso.matcher.ViewMatchers import androidx.ui.core.SemanticsTreeNode import androidx.ui.core.SemanticsTreeProvider import androidx.ui.test.SemanticsTreeInteraction import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit /** * Android specific implementation of [SemanticsTreeInteraction]. * * Important highlight is that this implementation is using Espresso underneath to find the current * [Activity] that is visible on screen. So it does not rely on any references on activities being * held by your tests. * * @param throwOnRecomposeTimeout Will throw exception if waiting for recomposition timeouts. */ internal class AndroidSemanticsTreeInteraction internal constructor( private val throwOnRecomposeTimeOut: Boolean ) : SemanticsTreeInteraction() { /** * Whether after the latest performed action we waited for any pending changes in composition. * This is used in internal tests to verify that actions that are supposed to mutate the * hierarchy as really observed like that. */ internal var hadPendingChangesAfterLastAction = false // we should not wait more than two frames, but two frames can be much more // than 32ms when we skip a few, so "better" 10x number should work here private val defaultRecomposeWaitTimeMs = 1000L private val selectors = mutableListOf<(SemanticsTreeNode) -> Boolean>() private val handler = Handler(Looper.getMainLooper()) override fun findAllMatching(): List<SemanticsTreeNode> { waitForIdleCompose() val collectedInfo = findActivityAndTreeProvider() return collectedInfo.treeProvider.getAllSemanticNodes() .filter { node -> selectors.all { selector -> selector(node) } } .toList() } override fun addSelector(selector: (SemanticsTreeNode) -> Boolean): SemanticsTreeInteraction { selectors.add(selector) return this } private fun performAction(action: (SemanticsTreeProvider) -> Unit) { val collectedInfo = findActivityAndTreeProvider() handler.post(object : Runnable { override fun run() { action.invoke(collectedInfo.treeProvider) } }) // It might seem we don't need to wait for idle here as every query and action we make // already waits for idle before being executed. However since Espresso could be mixed in // these tests we rather wait to be recomposed before we leave this method to avoid // potential flakes. hadPendingChangesAfterLastAction = waitForIdleCompose() } /** * Waits for Compose runtime to be idle - meaning it has no pending changes. * * @return Whether the method had to wait for pending changes or not. */ private fun waitForIdleCompose(): Boolean { if (Looper.getMainLooper() == Looper.myLooper()) { throw Exception("Cannot be run on UI thread.") } var hadPendingChanges = false val latch = CountDownLatch(1) handler.post(object : Runnable { override fun run() { hadPendingChanges = Recomposer.hasPendingChanges() if (hadPendingChanges) { scheduleIdleCheck(latch) } else { latch.countDown() } } }) val succeeded = latch.await(defaultRecomposeWaitTimeMs, TimeUnit.MILLISECONDS) if (throwOnRecomposeTimeOut && !succeeded) { throw RecomposeTimeOutException() } return hadPendingChanges } private fun scheduleIdleCheck(latch: CountDownLatch) { Choreographer.getInstance().postFrameCallback(object : Choreographer.FrameCallback { @SuppressLint("SyntheticAccessor") override fun doFrame(frameTimeNanos: Long) { if (Recomposer.hasPendingChanges()) { scheduleIdleCheck(latch) } else { latch.countDown() } } }) } override fun sendClick(x: Float, y: Float) { performAction { treeProvider -> val eventDown = MotionEvent.obtain( SystemClock.uptimeMillis(), 10, MotionEvent.ACTION_DOWN, x, y, 0 ) treeProvider.sendEvent(eventDown) eventDown.recycle() val eventUp = MotionEvent.obtain( SystemClock.uptimeMillis(), 10, MotionEvent.ACTION_UP, x, y, 0 ) treeProvider.sendEvent(eventUp) eventUp.recycle() } } private fun findActivityAndTreeProvider(): CollectedInfo { val viewForwarder = ViewForwarder() // Use Espresso to find the content view for us. // We can't use onView(instanceOf(SemanticsTreeProvider::class.java)) as Espresso throws // on multiple instances in the tree. Espresso.onView( ViewMatchers.withId( R.id.content ) ).check(viewForwarder) if (viewForwarder.viewFound == null) { throw IllegalArgumentException("Couldn't find a Compose root in the view hierarchy. " + "Are you using Compose in your Activity?") } val view = viewForwarder.viewFound!! as ViewGroup return CollectedInfo(view.context, collectSemanticTreeProviders(view)) } private fun collectSemanticTreeProviders( contentViewGroup: ViewGroup ): AggregatedSemanticTreeProvider { val collectedRoots = mutableSetOf<SemanticsTreeProvider>() fun collectSemanticTreeProvidersInternal(parent: ViewGroup) { for (index in 0 until parent.childCount) { when (val child = parent.getChildAt(index)) { is SemanticsTreeProvider -> collectedRoots.add(child) is ViewGroup -> collectSemanticTreeProvidersInternal(child) else -> { } } } } collectSemanticTreeProvidersInternal(contentViewGroup) return AggregatedSemanticTreeProvider( collectedRoots ) } /** * There can be multiple Compose views in Android hierarchy and we want to interact with all of * them. This class merges all the semantics trees into one, hiding the fact that the API might * be interacting with several Compose roots. */ private class AggregatedSemanticTreeProvider( private val collectedRoots: Set<SemanticsTreeProvider> ) : SemanticsTreeProvider { override fun getAllSemanticNodes(): List<SemanticsTreeNode> { // TODO(pavlis): Once we have a tree support we will just add a fake root parent here return collectedRoots.flatMap { it.getAllSemanticNodes() } } override fun sendEvent(event: MotionEvent) { // TODO(pavlis): This is not good. collectedRoots.first().sendEvent(event) } } /** A hacky way to retrieve views from Espresso matchers. */ private class ViewForwarder : ViewAssertion { var viewFound: View? = null override fun check(view: View?, noViewFoundException: NoMatchingViewException?) { viewFound = view } } internal class RecomposeTimeOutException : Throwable("Waiting for recompose has exceeded the timeout!") private data class CollectedInfo( val context: Context, val treeProvider: SemanticsTreeProvider ) }
8
null
1
6
b9cd83371e928380610719dfbf97c87c58e80916
8,799
platform_frameworks_support
Apache License 2.0
communication/src/com/google/android/libraries/car/communication/messagingsync/MessagingNotificationHandler.kt
google
415,118,653
false
null
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.communication.messagingsync import android.app.Notification import android.content.Context import android.content.Intent import android.os.Bundle import android.provider.Telephony import android.service.notification.StatusBarNotification import androidx.annotation.VisibleForTesting import androidx.core.app.NotificationCompat.MessagingStyle.Message import androidx.core.app.RemoteInput import com.google.android.libraries.car.communication.messagingsync.DebugLogs.CarToPhoneMessageError.INVALID_PROTOBUF_EXCEPTION import com.google.android.libraries.car.communication.messagingsync.DebugLogs.CarToPhoneMessageError.UNKNOWN_ACTION import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.DUPLICATE_MESSAGE import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.MESSAGING_SYNC_FEATURE_DISABLED import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.NON_CAR_COMPATIBLE_MESSAGE_NO_MESSAGING_STYLE import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.NON_CAR_COMPATIBLE_MESSAGE_NO_REPLY import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.NON_CAR_COMPATIBLE_MESSAGE_SHOWS_UI import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.OLD_MESSAGES_IN_NOTIFICATION import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.REPLY_REPOST import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.SMS_MESSAGE import com.google.android.libraries.car.communication.messagingsync.DebugLogs.PhoneToCarMessageError.UNKNOWN import com.google.android.libraries.car.notifications.NotificationHandler import com.google.android.libraries.car.notifications.NotificationSyncManager import com.google.android.libraries.car.notifications.lastMessage import com.google.android.libraries.car.notifications.markAsReadAction import com.google.android.libraries.car.notifications.messagingStyle import com.google.android.libraries.car.notifications.passesRelaxedCarMsgRequirements import com.google.android.libraries.car.notifications.passesStrictCarMsgRequirements import com.google.android.libraries.car.notifications.replyAction import com.google.android.libraries.car.notifications.showsUI import com.google.android.libraries.car.trustagent.Car import com.google.protobuf.InvalidProtocolBufferException import com.google.protos.aae.messenger.NotificationMsg.Action.ActionName.MARK_AS_READ import com.google.protos.aae.messenger.NotificationMsg.Action.ActionName.REPLY import com.google.protos.aae.messenger.NotificationMsg.CarToPhoneMessage import java.time.Duration import java.time.Instant import java.util.UUID import kotlin.math.abs /** * Synchronizes car-compatible text messages with the connected [Car]. It also relays Mark-as-Read * and Reply actions user does on the car to the appropriate messaging app on the device. */ internal class MessagingNotificationHandler( private val context: Context, private val carId: UUID, private val sendMessage: (data: ByteArray, carId: UUID) -> Int, private val messagingUtils: MessagingUtils, private val timeSource: TimeProvider, sharedState: NotificationHandlerSharedState ) : NotificationHandler { /** * The notification map where the key is [StatusBarNotification.getKey] and the Notification * represents [StatusBarNotification.getNotification] */ private val notificationMap = mutableMapOf<String, Notification>() private val replyMessages = sharedState.replyMessages private var connectionTime: Instant? = null var isCarConnected = false private set fun onMessageReceived(data: ByteArray) = try { val carToPhoneMsg = CarToPhoneMessage.parseFrom(data) when (val actionName = carToPhoneMsg.actionRequest.actionName) { REPLY -> sendReply(carToPhoneMsg) MARK_AS_READ -> markAsRead(carToPhoneMsg) else -> DebugLogs.logCarToPhoneMessageError(UNKNOWN_ACTION, actionName.toString()) } } catch (e: InvalidProtocolBufferException) { DebugLogs.logCarToPhoneMessageError(INVALID_PROTOBUF_EXCEPTION, e.javaClass.name, e) } /** * Enables handler to listen for notifications and post to car. * Clears car-level caching. * * Example use: * ``` * MessagingNotificationHandler().also { it.onCarConnected } * ``` */ fun onCarConnected() { notificationMap.clear() if (isCarConnected) return NotificationSyncManager.addNotificationHandler(this) connectionTime = timeSource.now() isCarConnected = true DebugLogs.logOnCarConnected() } /** * Clears all car-level caching on disconnect. Also stops listening for notifications, rendering * this handler as inoperable. To reuse handler re-call [onCarConnected], */ fun onCarDisconnected() { NotificationSyncManager.removeNotificationHandler(this) notificationMap.clear() connectionTime = null isCarConnected = false DebugLogs.logOnCarDisconnected() } override fun onNotificationReceived(sbn: StatusBarNotification) { if (!canHandleNotification(sbn)) { val reasons = cannotHandleNotificationReasons(sbn) DebugLogs.logPhoneToCarMessageErrors(reasons, "${sbn.packageName}") return } DebugLogs.logMessageNotificationReceived(sbn.packageName) val message = sbn.toMessageDAO()?.toMessage() ?: return sendMessage(message.toByteArray(), carId) notificationMap[sbn.key] = sbn.notification DebugLogs.logMessageToCarSent(message.message.textMessage) } @VisibleForTesting fun canHandleNotification(sbn: StatusBarNotification) = isFeatureEnabled() && isCarCompatibleNotification(sbn) && isUnique(sbn) && isRecentTextMessage(sbn) && !isReplyRepost(sbn) && !isSMSMessage(sbn.packageName) /** * Returns a string concatenation with the error code name and details of the * [StatusBarNotification] */ @VisibleForTesting fun cannotHandleNotificationReasons(sbn: StatusBarNotification): List<String> { val reasons = buildList { if (!isFeatureEnabled()) { add("${MESSAGING_SYNC_FEATURE_DISABLED.name}") } if (sbn.notification.messagingStyle == null) { add("${NON_CAR_COMPATIBLE_MESSAGE_NO_MESSAGING_STYLE.name}") } if (sbn.notification.replyAction == null ) { add("${NON_CAR_COMPATIBLE_MESSAGE_NO_REPLY.name}") } if (sbn.notification.showsUI ) { add("${NON_CAR_COMPATIBLE_MESSAGE_SHOWS_UI.name}") } if (!isUnique(sbn)) { add("${DUPLICATE_MESSAGE.name}") } if (!isRecentTextMessage(sbn)) { add("${OLD_MESSAGES_IN_NOTIFICATION.name}") } if (isReplyRepost(sbn)) { add("${REPLY_REPOST.name}") } if (isSMSMessage(sbn.packageName)) { add("${SMS_MESSAGE.name}") } if (isEmpty()) { add("${UNKNOWN.name}") } } return reasons } private fun isFeatureEnabled() = messagingUtils.isMessagingSyncEnabled(carId.toString()) private fun StatusBarNotification.toMessageDAO(): PhoneToCarMessageDAO? { val isNewConversation = notificationMap[key] == null val style = notification.messagingStyle val lastMessage = style?.lastMessage ?: return null val appIcon = notification.smallIcon ?: return null val appIconColor = notification.color val connectionInstant = connectionTime ?: return null return PhoneToCarMessageDAO( key = key, context = context, packageName = packageName, style = style, appIcon = appIcon, appIconColor = appIconColor, isNewConversation = isNewConversation, lastMessage = lastMessage, connectionTime = connectionInstant ) } private fun sendReply(carToPhoneMsg: CarToPhoneMessage) { val action = notificationMap[carToPhoneMsg.notificationKey]?.replyAction val remoteInput = action?.remoteInputs?.first() ?: return val actionDataList = carToPhoneMsg.actionRequest.mapEntryList val response = actionDataList.firstOrNull { it.key == REPLY_KEY } ?: return val bundle = Bundle().apply { putCharSequence(remoteInput.resultKey, response.value) } val intent = Intent() val remoteInputs = action.remoteInputs ?: emptyArray<RemoteInput>() RemoteInput.addResultsToIntent(remoteInputs, intent, bundle) action.actionIntent?.send(context, 0, intent) DebugLogs.logSendReplyToPhone() replyMessages.put( carToPhoneMsg.notificationKey, Message( response.value, timeSource.now().toEpochMilli(), notificationMap[carToPhoneMsg.notificationKey]?.messagingStyle?.user ) ) } private fun markAsRead(carToPhoneMsg: CarToPhoneMessage) { val notification = notificationMap[carToPhoneMsg.notificationKey] ?: return val action = notification.markAsReadAction action?.actionIntent?.send(context, 0, Intent()) DebugLogs.logSendMarkAsReadToPhone() } /** * Allowlisted applications do not require mark as read intent to be present in the notification. */ private fun isCarCompatibleNotification(sbn: StatusBarNotification) = if (isAllowlistedForRelaxedReqs(sbn.packageName)) sbn.notification.passesRelaxedCarMsgRequirements else sbn.notification.passesStrictCarMsgRequirements private fun isAllowlistedForRelaxedReqs(packageName: String): Boolean { val allowList = context.getString(R.string.relaxedAllowlist).split(",") return packageName in allowList } /** * SMS is already supported through Bluetooth Message Profile. For v1, the handler ignores any sms * message from the default sms package Future work includes also checking 3p messaging apps that * posts sms notifications. */ private fun isSMSMessage(packageName: String) = Telephony.Sms.getDefaultSmsPackage(context) == packageName /** * * Previous, unread messages are occasionally reposted in new notifications. * * When a new notification is received, we check to see if the phone is connected to a car before * handling the notification. * * We also need to verify that the text message is recent and was received after the phone was * connected to the car. * * Returns true if text message was received after the phone connected with the car. */ private fun isRecentTextMessage(sbn: StatusBarNotification): Boolean { val connectionInstant = connectionTime ?: return false val lastMessageTime = Instant.ofEpochMilli(sbn.notification.messagingStyle?.lastMessage?.timestamp ?: 0) return lastMessageTime >= connectionInstant } /** * Returns true if this is a non-duplicate/unique notification It is a known issue that WhatsApp * sends out the same message multiple times. To handle this, we check the timestamp to make sure * this is not a duplicate message */ private fun isUnique(sbn: StatusBarNotification): Boolean { val newStyle = sbn.notification.messagingStyle val newLastMessage = newStyle?.lastMessage ?: return true val previousNotification = notificationMap[sbn.key] val previousStyle = previousNotification?.messagingStyle val previousLastMessage = previousStyle?.lastMessage ?: return true return !(previousLastMessage.timestamp == newLastMessage.timestamp && previousLastMessage.text == newLastMessage.text && previousLastMessage.person?.name == newLastMessage.person?.name) } /** * Returns true if this is a notification update representing the user's reply to a message. * * We compare the last known reply message from our internal cache to the latest message in the * Status Bar Notification to verify this notification is not a reply repost. * * It is important to note that user can trigger a response outside of IHU interactions. The reply * cache will not know of these responses, so we also check to see if there are other indications * that this message is clearly from the user with a call to [isMessageClearlyFromUser] which * checks to see if unique identifiers such as user key or user uri are present. * * These identifiers are optional and not always present in message notifications, so the reply * cache is still necessary as a fallback to check for replies by the user triggered by the IHU. * * The reply timestamp is an approximation of the expected reply timestamp, created when we send a * reply intent to the 3p messaging app. The 3p messaging app sets the true timestamp for the * reply message. In this case the true timestamp is unknown but we anticipate it would be within * 2 seconds, plus or minus of our approximation. */ private fun isReplyRepost(sbn: StatusBarNotification): Boolean { if (isMessageClearlyFromUser(sbn)) return true val replyMessage = replyMessages[sbn.key] ?: return false val lastMessage = sbn.notification.messagingStyle?.lastMessage ?: return false val isWithinTimeInterval = abs(lastMessage.timestamp - replyMessage.timestamp) <= REPLY_REPOST_INTERVAL_MS return isWithinTimeInterval && lastMessage.person?.name == replyMessage.person?.name && lastMessage.text == replyMessage.text } /** * Returns true if the message notification is clearly from current user, using unique identifiers * such as key or uri. Sender name is not a sufficient unique identifier as there can be multiple * users with the same name. The unique identifiers (uri and key) are optional and may not be set * by the messaging app. If method returns false, it means more checks need to be made to * determine if the message is from the current user, such as checking the last reply cache sent * directly from the IHU. */ private fun isMessageClearlyFromUser(sbn: StatusBarNotification): Boolean { val messagingStyle = sbn.notification.messagingStyle ?: return false val lastMessage = messagingStyle.lastMessage ?: return false lastMessage.person?.key?.let { return it == messagingStyle.user.key } lastMessage.person?.uri?.let { return it == messagingStyle.user.uri } return false } companion object { private const val REPLY_KEY = "REPLY" /** * The expected time interval between the SDK sending out the reply pending intent to the * application, and the application posting a notification with this reply. */ private val REPLY_REPOST_INTERVAL_MS = Duration.ofSeconds(2).toMillis() } }
0
null
4
18
2efd734e7db42ef9e2d40ff4d2144eded9a65c91
15,256
android-auto-companion-android
Apache License 2.0
src/main/kotlin/core/usecase/HandleBuildFailedUseCase.kt
kingargyle
232,397,685
true
{"Kotlin": 57396}
package core.usecase open class HandleBuildFailedUseCase( val postStatusUseCase: PostStatusUseCase, val summaries: List<GetSummaryUseCase> ) { open fun invoke() { summaries.postAll(postStatusUseCase) } }
0
null
0
0
a7f04b4753e6594107f405cc123b55aaff95158c
237
BuildChecks
Apache License 2.0
library/echo-core/src/commonTest/kotlin/io/github/alexandrepiveteau/echo/core/causality/EventIdentifierTest.kt
markdown-party
341,117,604
false
{"Kotlin": 603967, "Dockerfile": 723, "JavaScript": 715, "Shell": 646, "HTML": 237, "CSS": 133}
package io.github.alexandrepiveteau.echo.core.causality import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class EventIdentifierTest { @Test fun singleSite_respectsOrdering() { val site = SiteIdentifier(1U) val a = EventIdentifier(SequenceNumber(1U), site) val b = EventIdentifier(SequenceNumber(2U), site) assertTrue(a < b) assertEquals(a, a) assertEquals(b, b) } @Test fun multipleSites_respectSequenceNumberOrdering() { val alice = SiteIdentifier(1U) val bob = SiteIdentifier(2U) val a = EventIdentifier(SequenceNumber(0U), alice) val b = EventIdentifier(SequenceNumber(0U), bob) val c = EventIdentifier(SequenceNumber(1U), alice) val d = EventIdentifier(SequenceNumber(1U), bob) assertTrue(a < d) assertTrue(b < c) } @Test fun concurrentUpdates_makeTotalOrdering() { val alice = SiteIdentifier(1U) val bob = SiteIdentifier(2U) val charlie = SiteIdentifier(3U) val a = EventIdentifier(SequenceNumber.Min, alice) val b = EventIdentifier(SequenceNumber.Min, bob) val c = EventIdentifier(SequenceNumber.Min, charlie) assertTrue(a < b) assertTrue(b < c) assertTrue(b < c) } }
0
Kotlin
3
54
d7d50e59522fdccc1d8ca70f0e495ca959847684
1,231
mono
MIT License
app/src/main/java/br/com/william/fernandes/srp/MainActivity.kt
williamjosefernandes
608,693,253
false
null
package br.com.william.fernandes.srp import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import br.com.william.fernandes.srp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val cozinheiro = Cozinheiro() private val garcom = Garcom() private val lavaLoucas = LavaLoucas() private val chef = Chef(cozinheiro, garcom, lavaLoucas) private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnPrepararJantar.setOnClickListener { chef.prepararJantar() } } }
0
Kotlin
0
0
59e490b1b75f00869bab5d4b8dc28ec975e4abb5
766
Single-Responsibility-Principle
Apache License 2.0
integration-test/app/src/commonMain/kotlin/com/moriatsushi/koject/integrationtest/app/component/MultipleComponent.kt
mori-atsushi
605,139,896
false
null
@file:OptIn(ExperimentalKojectApi::class) package com.moriatsushi.koject.integrationtest.app.component import com.moriatsushi.koject.ExperimentalKojectApi import com.moriatsushi.koject.Provides import com.moriatsushi.koject.component.Component import com.moriatsushi.koject.component.ComponentExtras @Component @Retention(AnnotationRetention.BINARY) annotation class CustomComponent1 class CustomComponent1Extras : ComponentExtras<CustomComponent1> @Component @Retention(AnnotationRetention.BINARY) annotation class CustomComponent2 class CustomComponent2Extras : ComponentExtras<CustomComponent2> class MultipleCustomComponentClass( val value: String, ) @Provides @CustomComponent1 fun provideCustomComponent1(): MultipleCustomComponentClass { return MultipleCustomComponentClass("custom-component-1") } @Provides @CustomComponent2 fun provideCustomComponent2(): MultipleCustomComponentClass { return MultipleCustomComponentClass("custom-component-2") } @Provides @CustomComponent1 class CustomComponent1Holder( val value: MultipleCustomComponentClass, ) @Provides @CustomComponent2 class CustomComponent2Holder( val value: MultipleCustomComponentClass, )
13
Kotlin
2
96
c22286b39a3e6249842d148ff0a22f1fb7d37d47
1,188
koject
Apache License 2.0
shared/domain/src/main/kotlin/land/sungbin/androidprojecttemplate/shared/domain/dsl/Dsl.kt
GibsonRuitiari
519,628,609
false
{"Kotlin": 39307}
package land.sungbin.androidprojecttemplate.shared.domain.dsl // TODO: set your dsl name @DslMarker annotation class Dsl
0
null
1
0
37d2437f03507b687ae9112e635d48eb2850e34f
122
duckie
MIT License
app/src/main/java/ru/axcheb/spotifyapi/di/NetworkModule.kt
axcheb
402,218,865
false
null
package ru.axcheb.spotifyapi.di import android.app.Application import android.content.Context import android.content.Context.MODE_PRIVATE import coil.ImageLoader import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import dagger.Module import dagger.Provides import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import retrofit2.Retrofit import ru.axcheb.spotifyapi.data.AccessTokenProvider import ru.axcheb.spotifyapi.data.AccessTokenProviderImpl import ru.axcheb.spotifyapi.data.network.interceptor.AuthInterceptor import ru.axcheb.spotifyapi.data.network.interceptor.SpotifyTokenAuthenticator import ru.axcheb.spotifyapi.data.network.service.SpotifyService import ru.axcheb.spotifyapi.data.network.service.TokenService import javax.inject.Singleton @Module object NetworkModule { @Provides @Singleton fun provideJson(): Json { return Json(Json.Default) { ignoreUnknownKeys = true } } /** * Spotify authorization service. */ @Singleton @Provides fun provideTokenService(json: Json): TokenService { val httpClient = OkHttpClient.Builder().build() val retrofit = Retrofit.Builder() .baseUrl("https://accounts.spotify.com/") .client(httpClient) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() return retrofit.create(TokenService::class.java) } @Singleton @Provides fun provideAccessTokenProvider( context: Context, tokenService: TokenService ): AccessTokenProvider { val prefs = context.getSharedPreferences("app_pref", MODE_PRIVATE) return AccessTokenProviderImpl(prefs, tokenService) } /** * Spotify API Rest service. */ @Singleton @Provides fun provideSpotifyService( json: Json, accessTokenProvider: AccessTokenProvider ): SpotifyService { val httpClient = OkHttpClient.Builder() .addInterceptor(AuthInterceptor(accessTokenProvider)) .authenticator(SpotifyTokenAuthenticator(accessTokenProvider)) .build() val retrofit = Retrofit.Builder() .baseUrl("https://api.spotify.com") .client(httpClient) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() return retrofit.create(SpotifyService::class.java) } @Singleton @Provides fun provideImageLoader(application: Application): ImageLoader { return ImageLoader(application) } }
0
Kotlin
0
0
a40c53cfe39d9e9b2ee58c09236e9b0d57e4462d
2,684
SpotifyBrowser
MIT License
src/main/kotlin/de/matthiasfisch/planningpoker/controller/GameController.kt
fischmat
637,992,688
false
{"Kotlin": 106249, "Dockerfile": 516, "Shell": 505}
package de.matthiasfisch.planningpoker.controller import de.matthiasfisch.planningpoker.model.* import de.matthiasfisch.planningpoker.service.GameService import de.matthiasfisch.planningpoker.service.PlayerService import de.matthiasfisch.planningpoker.service.RoundService import org.springframework.data.domain.Pageable import org.springframework.web.bind.annotation.* @RestController @RequestMapping("api/v1/games") class GameController( private val gameService: GameService, private val playerService: PlayerService, private val roundService: RoundService ) { @GetMapping fun getAllGames(@RequestParam("page") page: Int?, @RequestParam("limit") pageSize: Int?): PagedResult<Game> { return gameService.getPagedGames( Pageable.ofSize(pageSize ?: 10) .withPage(page ?: 0) ).let { PagedResult(it) } } @GetMapping("/{gameId}") fun getGame(@PathVariable("gameId") gameId: String): Game { return gameService.getGame(gameId) } @GetMapping("/{gameId}/players") fun getPlayers(@PathVariable("gameId") gameId: String): List<Player> { return gameService.getPlayersInGame(gameId) } @PostMapping fun createGame(@RequestBody stub: GameStub): Game { return gameService.createGame(stub) } @GetMapping("/{gameId}/rounds") fun getRounds(@PathVariable("gameId") gameId: String): List<Round> { return roundService.getRounds(gameId) } @GetMapping("/{gameId}/rounds/current") fun getCurrentRound(@PathVariable("gameId") gameId: String): Round { return roundService.getCurrentRound(gameId) } @PostMapping("/{gameId}/rounds") fun startRound(@PathVariable("gameId") gameId: String, @RequestBody stub: RoundStub): Round { return roundService.startRound(gameId, stub) } @DeleteMapping("/{gameId}/rounds/{roundId}") fun endRound(@PathVariable("gameId") gameId: String, @PathVariable("roundId") roundId: String): Round { return roundService.endRound(gameId, roundId) } @PostMapping("/{gameId}/players") fun joinGame(@PathVariable("gameId") gameId: String): Player { return playerService.joinGame(gameId) } @DeleteMapping("/{gameId}/players") fun leaveGame(@PathVariable("gameId") gameId: String): Player { return playerService.leaveGame(gameId) } @GetMapping("/{gameId}/rounds/{roundId}/votes") fun getVotes(@PathVariable("gameId") gameId: String, @PathVariable("roundId") roundId: String): List<Vote> { require(roundService.getRound(roundId).gameId == gameId) { "Round $roundId does not belong to game $gameId." } return roundService.getVotes(roundId) } @PostMapping("/{gameId}/rounds/{roundId}/votes") fun submitVote(@PathVariable("roundId") roundId: String, @RequestBody card: Card): Vote { return roundService.putVote(roundId, card) } @DeleteMapping("/{gameId}/rounds/{roundId}/votes/mine") fun revokeVote(@PathVariable("roundId") roundId: String) { roundService.revokeVote(roundId) } @GetMapping("/{gameId}/rounds/{roundId}/results") fun getRoundResults(@PathVariable("gameId") gameId: String, @PathVariable("roundId") roundId: String): RoundResults { require(roundService.getRound(roundId).gameId == gameId) { "Round $roundId does not belong to game $gameId." } return roundService.getRoundResults(roundId) } }
0
Kotlin
0
0
2d4b89de99e63fc82ad953b44a8092d1fc2bfb55
3,469
planningpoker
MIT License
translation/src/main/kotlin/catmoe/fallencrystal/translation/event/events/translation/TranslationLoadEvent.kt
CatMoe
638,486,044
false
{"Kotlin": 764903}
/* * Copyright 2023. CatMoe / FallenCrystal * * 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 catmoe.fallencrystal.translation.event.events.translation import catmoe.fallencrystal.translation.event.TranslationEvent class TranslationLoadEvent : TranslationEvent()
2
Kotlin
0
21
5a0f321eafffd1247a84e4a7e12d4efb50226368
789
MoeFilter
Apache License 2.0
app/src/main/java/com/rob729/newsfeed/utils/NotificationHelper.kt
rob729
680,605,109
false
null
package com.rob729.newsfeed.utils import android.Manifest import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.workDataOf import com.rob729.newsfeed.R import com.rob729.newsfeed.ui.NewsActivity import com.rob729.newsfeed.workManager.NewsReminder import java.util.Calendar import java.util.concurrent.TimeUnit class NotificationHelper(private val context: Context) { fun createNotification(title: String, message: String) { createNotificationChannel() val intent = Intent(context, NewsActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val notification = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher_foreground) .setContentTitle(title) .setContentText(message) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true) .build() if (ActivityCompat.checkSelfPermission( context, Manifest.permission.POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED ) { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) } } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT ).apply { description = NOTIFICATION_CHANNEL_DESCRIPTION } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } fun scheduleNotification() { val currentDate = Calendar.getInstance() val dueDate = Calendar.getInstance() dueDate.set(Calendar.HOUR_OF_DAY, 8) dueDate.set(Calendar.MINUTE, 30) dueDate.set(Calendar.SECOND, 0) if (dueDate.before(currentDate)) { dueDate.add(Calendar.HOUR_OF_DAY, 24) } val timeDiff = dueDate.timeInMillis - currentDate.timeInMillis val newsReminderWorkRequest = OneTimeWorkRequestBuilder<NewsReminder>() .setInitialDelay(timeDiff, TimeUnit.MILLISECONDS) .setInputData( workDataOf( Constants.NOTIFICATION_TITLE to context.getString(R.string.notification_title), Constants.NOTIFICATION_MESSAGE to context.getString(R.string.notification_sub_title), ) ) .build() WorkManager.getInstance(context).enqueueUniqueWork( WORK_NAME, ExistingWorkPolicy.REPLACE, newsReminderWorkRequest ) } companion object { private const val NOTIFICATION_ID = 1 private const val CHANNEL_ID = "Daily News Reminder" private const val WORK_NAME = "DAILY_NEWS_REMINDER" private const val NOTIFICATION_CHANNEL_DESCRIPTION = "News Reminder Channel Description" } }
5
null
0
1
cc7678e60af479efad8d1d4d2bbc825c4ba4e10b
3,775
News-Feed
Apache License 2.0
basick/src/main/java/com/mozhimen/basick/utilk/android/database/UtilKCursor.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.utilk.android.database import android.annotation.SuppressLint import android.database.Cursor /** * @ClassName UtilKCursor * @Description TODO * @Author Mozhimen & <NAME> * @Date 2023/5/25 10:31 * @Version 1.0 */ fun Cursor.getString(key: String): String = UtilKCursor.getString(this, key) object UtilKCursor { @JvmStatic fun getColumnIndex(cursor: Cursor, columnName: String): Int = cursor.getColumnIndex(columnName) @SuppressLint("Range") @JvmStatic fun getString(cursor: Cursor, key: String): String = cursor.getString(getColumnIndex(cursor, key)) }
0
Kotlin
7
114
24ed5b2eab8739929c708697d7b59c0e7e7f9523
629
SwiftKit
Apache License 2.0
lib/navigationsetup/src/main/java/se/gustavkarlsson/skylight/android/lib/navigationsetup/LibNavigationSetupModule.kt
wowselim
288,922,417
true
{"Kotlin": 316543}
package se.gustavkarlsson.skylight.android.lib.navigationsetup import dagger.Module import dagger.Provides import dagger.Reusable @Module object LibNavigationSetupModule { @Provides @Reusable internal fun provideNavigationInstaller(): NavigationInstaller = SimpleStackNavigationInstaller( DefaultDirectionsCalculator ) }
0
null
0
0
4da1731aca92d4e6d4b0e8128ca504fc0b3820b9
364
skylight-android
MIT License
app/src/main/java/au/com/dw/paging3contentprovider/rx/MessageRxPageSource.kt
davidwong
275,048,893
false
null
package au.com.dw.paging3contentprovider.rx import androidx.paging.rxjava2.RxPagingSource import au.com.dw.paging3contentprovider.Message import au.com.dw.paging3contentprovider.MessageRepository import io.reactivex.Single import io.reactivex.schedulers.Schedulers /** * PagingSource that loads data from a content provider. */ class MessageRxPageSource(val repo: MessageRepository) : RxPagingSource<Int, Message>() { // the initial load size for the first page may be different from the requested size var initialLoadSize: Int = 0 override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, Message>> { // Start refresh at page 1 if undefined. val nextPageNumber = params.key ?: 1 if (params.key == null) { initialLoadSize = params.loadSize } // work out the offset into the database to retrieve records from the page number, // allow for a different load size for the first page val offsetCalc = { if (nextPageNumber == 2) initialLoadSize else ((nextPageNumber - 1) * params.loadSize) + (initialLoadSize - params.loadSize) } val offset = offsetCalc.invoke() return repo.getMessagesRx(params.loadSize, offset) .subscribeOn(Schedulers.io()) .toList() .map<LoadResult<Int, Message>> { list -> LoadResult.Page( data = list, prevKey = null, // assume that if a full page is not loaded, that means the end of the data nextKey = if (list.size < params.loadSize) null else nextPageNumber + 1 ) } .onErrorReturn { e -> LoadResult.Error(e) } } }
1
Kotlin
0
8
2bbd2ab9ec07e21261179e32a2203224ca6ddc71
1,904
Paging3-ContentProvider
Apache License 2.0
aws-lambda-function-resolvers/src/main/java/jetbrains/buildServer/runner/lambda/function/LambdaFunctionInvoker.kt
JetBrains
465,689,992
false
null
package jetbrains.buildServer.runner.lambda.function import jetbrains.buildServer.runner.lambda.model.RunDetails import kotlin.jvm.Throws interface LambdaFunctionInvoker { @Throws(Exception::class) fun invokeLambdaFunction(runDetails: List<RunDetails>): Boolean }
1
Kotlin
2
1
087fe2c33de95107249fdf704485d3e10a52e4b9
273
teamcity-aws-lambda-plugin
Apache License 2.0
stocks/src/main/java/com/pyamsoft/tickertape/stocks/api/EquityType.kt
pyamsoft
371,196,339
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.tickertape.stocks.api import androidx.annotation.CheckResult enum class EquityType(val display: String) { STOCK("Stock"), OPTION("Option"), CRYPTOCURRENCY("Cryptocurrency"); companion object { private val valueSet by lazy(LazyThreadSafetyMode.NONE) { values().toSet() } /** * Parse the EquityType string, fall back to STOCK if it is nothing else we can support * * Looping over the values is faster than using a try catch on the valueOf() static function. */ @JvmStatic @CheckResult fun from(name: String): EquityType { for (value in valueSet) { if (value.name == name) { return value } } return STOCK } } }
5
null
0
7
fb25840700ec9ae096ef8bfb0dced762b8dd2f61
1,324
tickertape
Apache License 2.0
string-annotations/common/internal/src/main/java/com/mmolosay/stringannotations/internal/AnnotationSpanProcessor.kt
mmolosay
519,758,730
false
{"Kotlin": 148805}
package com.mmolosay.stringannotations.internal import android.text.Annotation import android.text.Spanned /* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Processes [Annotation]s. */ public object AnnotationSpanProcessor { /** * Parses specified [annotations] of [spanned] into list of [StringAnnotation]. */ internal fun parseStringAnnotations( spanned: Spanned, annotations: Array<out Annotation> ): List<StringAnnotation> = annotations.mapIndexed { index, annotation -> val range = parseAnnotationRange(spanned, annotation) if (range.first == -1 || range.last == -1) { throw IllegalArgumentException("annotation doesn\'t belong to this string") } StringAnnotation(annotation, range.first, range.last, index) } /** * Retrieves [annotation]'s start and end positions in terms of specified [spanned]. * If [annotation] is `null`, then we assume that is a top-most root, and return full [spanned] * range. */ internal fun parseAnnotationRange( spanned: Spanned, annotation: Annotation? ): IntRange { annotation ?: return 0..spanned.length val start = spanned.getSpanStart(annotation) val end = spanned.getSpanEnd(annotation) return start..end } /** * Variant of [parseAnnotationRange] that works with [annotations] array. */ public fun parseAnnotationRanges( spanned: Spanned, annotations: Array<out Annotation> ): List<IntRange> = annotations.map { parseAnnotationRange(spanned, it) } }
0
Kotlin
0
1
43323fdf7689548ff80f27073b98e11ce77d070d
2,193
StringAnnotations
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsciagcareersinductionapi/TestData.kt
ministryofjustice
620,258,376
false
{"Kotlin": 140849, "Dockerfile": 1191}
package uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.AbilityToWorkImpactedBy import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.EducationLevels import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.HopingToGetWork import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.OtherQualification import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.PersonalInterests import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.PrisonTraining import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.PrisonWork import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.QualificationLevel import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.ReasonToNotGetWork import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.Skills import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.WorkType import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.jsonprofile.CIAGProfileRequestDTO import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.AchievedQualification import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.CIAGProfile import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.EducationAndQualification import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.PreviousWork import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.PrisonWorkAndEducation import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.SkillsAndInterests import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.WorkExperience import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.WorkInterestDetail import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity.WorkInterests import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.service.CIAGProfileService import java.lang.Boolean.FALSE import java.time.LocalDateTime class TestData { companion object { private lateinit var profileService: CIAGProfileService val createdByString = "createdBy" val offenderIdString = "offenderId" val modifiedByString = "modifiedBy" var hopingToGetWork = HopingToGetWork.NOT_SURE var abilityToWorkImpactDetailList = mutableSetOf(AbilityToWorkImpactedBy.HEALTH_ISSUES) var reasonToNotGetWork = mutableSetOf(ReasonToNotGetWork.FULL_TIME_CARER) var previousWorkDetail = WorkExperience(WorkType.BEAUTY, null, "jobtitle", "Respon") var previousWorkDetailSet = mutableSetOf(previousWorkDetail) var workInterests = WorkInterests( "Sacintha", LocalDateTime.now(), null, mutableSetOf(WorkType.BEAUTY), null, mutableSetOf( WorkInterestDetail(WorkType.BEAUTY, "tired"), ), null, ) var previousWork = PreviousWork(FALSE, "Sacintha", LocalDateTime.now(), null, mutableSetOf(WorkType.BEAUTY), null, previousWorkDetailSet, workInterests, null) var skillsAndInterests = SkillsAndInterests( "Sacintha", LocalDateTime.now(), null, mutableSetOf(Skills.COMMUNICATION), null, mutableSetOf(PersonalInterests.COMMUNITY), null, null, ) var acchievedQualification = AchievedQualification("Subject", "grade 2", QualificationLevel.LEVEL_1) var acchievedQualificationSet = mutableSetOf(acchievedQualification) var educationAndQualification = EducationAndQualification( "Sacintha", LocalDateTime.now(), null, EducationLevels.FURTHER_EDUCATION_COLLEGE, acchievedQualificationSet, mutableSetOf(OtherQualification.CSCS_CARD), null, null, ) var prisonWorkAndEducation = PrisonWorkAndEducation( "Sacintha", LocalDateTime.now(), null, mutableSetOf(PrisonWork.PRISON_LAUNDRY), null, mutableSetOf(PrisonTraining.BARBERING_AND_HAIRDRESSING), null, null, ) val ciagDTO = CIAGProfileRequestDTO( "A1234AB", "sacintha", LocalDateTime.now(), "sacintha", true, LocalDateTime.now(), HopingToGetWork.NOT_SURE, null, null, abilityToWorkImpactDetailList, reasonToNotGetWork, previousWork, skillsAndInterests, educationAndQualification, prisonWorkAndEducation, "1.1", ) val ciag = CIAGProfile( "A1234AB", "sacintha", LocalDateTime.now(), "sacintha", true, LocalDateTime.now(), HopingToGetWork.NOT_SURE, null, null, abilityToWorkImpactDetailList, reasonToNotGetWork, previousWork, skillsAndInterests, educationAndQualification, prisonWorkAndEducation, "1.1", ) val ciagEducation = CIAGProfile( "A1234AB", "sacintha", LocalDateTime.now(), "sacintha", true, LocalDateTime.now(), HopingToGetWork.NOT_SURE, null, null, abilityToWorkImpactDetailList, reasonToNotGetWork, null, null, educationAndQualification, null, "1.1", ) val ciagPreviousWork = CIAGProfile( "A1234AB", "sacintha", LocalDateTime.now(), "sacintha", true, LocalDateTime.now(), HopingToGetWork.NOT_SURE, null, null, abilityToWorkImpactDetailList, reasonToNotGetWork, previousWork, null, null, null, "1.1", ) val ciagPrisonWork = CIAGProfile( "A1234AB", "sacintha", LocalDateTime.now(), "sacintha", true, LocalDateTime.now(), HopingToGetWork.NOT_SURE, null, null, abilityToWorkImpactDetailList, reasonToNotGetWork, null, null, null, prisonWorkAndEducation, "1.1", ) } }
2
Kotlin
0
0
5060375a3bd3c062a5d304802653064cd0a2b762
5,718
hmpps-ciag-careers-induction-api
MIT License
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/CorporateDesignDemoDescriptor.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meistercharts.demo.descriptors import com.meistercharts.algorithms.layers.AbstractLayer import com.meistercharts.algorithms.layers.LayerPaintingContext import com.meistercharts.algorithms.layers.LayerType import com.meistercharts.algorithms.layers.addClearBackground import com.meistercharts.algorithms.layers.text.TextLayer import com.meistercharts.algorithms.painter.Color import com.meistercharts.canvas.FontDescriptorFragment import com.meistercharts.canvas.LayerSupport import com.meistercharts.demo.ChartingDemo import com.meistercharts.demo.ChartingDemoDescriptor import com.meistercharts.demo.DemoCategory import com.meistercharts.demo.PredefinedConfiguration import com.meistercharts.design.CorporateDesign import com.meistercharts.design.DebugDesign import com.meistercharts.design.NeckarITDesign import com.meistercharts.design.SegoeUiDesign import com.meistercharts.design.corporateDesign import com.meistercharts.model.Direction import com.meistercharts.model.DirectionBasedBasePointProvider import com.meistercharts.charts.lizergy.solar.LizergyDesign import it.neckar.open.kotlin.lang.fastFor import it.neckar.open.provider.MultiProvider /** * */ class CorporateDesignDemoDescriptor : ChartingDemoDescriptor<CorporateDesign?> { override val name: String = "Corporate Design" override val category: DemoCategory = DemoCategory.ShowCase override val predefinedConfigurations: List<PredefinedConfiguration<CorporateDesign?>> = listOf( PredefinedConfiguration(null, "null"), PredefinedConfiguration(NeckarITDesign, "Neckar IT"), PredefinedConfiguration(SegoeUiDesign, "Segoe UI"), PredefinedConfiguration(DebugDesign, "Debug"), PredefinedConfiguration(LizergyDesign, "Lizergy"), ) override fun createDemo(configuration: PredefinedConfiguration<CorporateDesign?>?): ChartingDemo { return ChartingDemo { val selectedCorporateDesign = configuration?.payload ?: corporateDesign meistercharts { configure { layers.addClearBackground() addLayer(selectedCorporateDesign, selectedCorporateDesign.h1, selectedCorporateDesign.h1Color, 0.0, "H1") addLayer(selectedCorporateDesign, selectedCorporateDesign.h2, selectedCorporateDesign.h2Color, 60.0, "H2") addLayer(selectedCorporateDesign, selectedCorporateDesign.h3, selectedCorporateDesign.h3Color, 115.0, "H3") addLayer(selectedCorporateDesign, selectedCorporateDesign.h4, selectedCorporateDesign.h4Color, 160.0, "H4") addLayer(selectedCorporateDesign, selectedCorporateDesign.h5, selectedCorporateDesign.h5Color, 190.0, "H5") addLayer(selectedCorporateDesign, selectedCorporateDesign.textFont, selectedCorporateDesign.textColor, 220.0, "Text") addLayer(selectedCorporateDesign, selectedCorporateDesign.textFont, selectedCorporateDesign.chartColors, 250.0, "Chart colors") } } } } private fun LayerSupport.addLayer(selectedCorporateDesign: CorporateDesign, fontDescriptorFragment: FontDescriptorFragment, color: Color, gapTop: Double, description: String) { val text = "$description: ${selectedCorporateDesign.id} - $fontDescriptorFragment" layers.addLayer(TextLayer({ _, _ -> listOf( text ) }) { font = fontDescriptorFragment textColor = color anchorDirection = Direction.TopCenter anchorPointProvider = DirectionBasedBasePointProvider(Direction.TopCenter) anchorGapVertical = gapTop } ) } private fun LayerSupport.addLayer(selectedCorporateDesign: CorporateDesign, fontDescriptorFragment: FontDescriptorFragment, colors: MultiProvider<CorporateDesignDemoDescriptor, Color>, gapTop: Double, description: String) { val text = "$description: ${selectedCorporateDesign.id}" layers.addLayer(object : AbstractLayer() { override val type: LayerType get() = LayerType.Content override fun paint(paintingContext: LayerPaintingContext) { val gc = paintingContext.gc val centerX = gc.width * 0.5 gc.font(fontDescriptorFragment) gc.fillText(text, centerX, gapTop, Direction.TopRight) 10.fastFor { gc.fill(colors.valueAt(it)) gc.fillRect(centerX + it * 24.0 + 10.0, gapTop, 20.0, 20.0) } } }) } }
0
Kotlin
0
4
af73f0e09e3e7ac9437240e19974d0b1ebc2f93c
4,915
meistercharts
Apache License 2.0
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/CorporateDesignDemoDescriptor.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meistercharts.demo.descriptors import com.meistercharts.algorithms.layers.AbstractLayer import com.meistercharts.algorithms.layers.LayerPaintingContext import com.meistercharts.algorithms.layers.LayerType import com.meistercharts.algorithms.layers.addClearBackground import com.meistercharts.algorithms.layers.text.TextLayer import com.meistercharts.algorithms.painter.Color import com.meistercharts.canvas.FontDescriptorFragment import com.meistercharts.canvas.LayerSupport import com.meistercharts.demo.ChartingDemo import com.meistercharts.demo.ChartingDemoDescriptor import com.meistercharts.demo.DemoCategory import com.meistercharts.demo.PredefinedConfiguration import com.meistercharts.design.CorporateDesign import com.meistercharts.design.DebugDesign import com.meistercharts.design.NeckarITDesign import com.meistercharts.design.SegoeUiDesign import com.meistercharts.design.corporateDesign import com.meistercharts.model.Direction import com.meistercharts.model.DirectionBasedBasePointProvider import com.meistercharts.charts.lizergy.solar.LizergyDesign import it.neckar.open.kotlin.lang.fastFor import it.neckar.open.provider.MultiProvider /** * */ class CorporateDesignDemoDescriptor : ChartingDemoDescriptor<CorporateDesign?> { override val name: String = "Corporate Design" override val category: DemoCategory = DemoCategory.ShowCase override val predefinedConfigurations: List<PredefinedConfiguration<CorporateDesign?>> = listOf( PredefinedConfiguration(null, "null"), PredefinedConfiguration(NeckarITDesign, "Neckar IT"), PredefinedConfiguration(SegoeUiDesign, "Segoe UI"), PredefinedConfiguration(DebugDesign, "Debug"), PredefinedConfiguration(LizergyDesign, "Lizergy"), ) override fun createDemo(configuration: PredefinedConfiguration<CorporateDesign?>?): ChartingDemo { return ChartingDemo { val selectedCorporateDesign = configuration?.payload ?: corporateDesign meistercharts { configure { layers.addClearBackground() addLayer(selectedCorporateDesign, selectedCorporateDesign.h1, selectedCorporateDesign.h1Color, 0.0, "H1") addLayer(selectedCorporateDesign, selectedCorporateDesign.h2, selectedCorporateDesign.h2Color, 60.0, "H2") addLayer(selectedCorporateDesign, selectedCorporateDesign.h3, selectedCorporateDesign.h3Color, 115.0, "H3") addLayer(selectedCorporateDesign, selectedCorporateDesign.h4, selectedCorporateDesign.h4Color, 160.0, "H4") addLayer(selectedCorporateDesign, selectedCorporateDesign.h5, selectedCorporateDesign.h5Color, 190.0, "H5") addLayer(selectedCorporateDesign, selectedCorporateDesign.textFont, selectedCorporateDesign.textColor, 220.0, "Text") addLayer(selectedCorporateDesign, selectedCorporateDesign.textFont, selectedCorporateDesign.chartColors, 250.0, "Chart colors") } } } } private fun LayerSupport.addLayer(selectedCorporateDesign: CorporateDesign, fontDescriptorFragment: FontDescriptorFragment, color: Color, gapTop: Double, description: String) { val text = "$description: ${selectedCorporateDesign.id} - $fontDescriptorFragment" layers.addLayer(TextLayer({ _, _ -> listOf( text ) }) { font = fontDescriptorFragment textColor = color anchorDirection = Direction.TopCenter anchorPointProvider = DirectionBasedBasePointProvider(Direction.TopCenter) anchorGapVertical = gapTop } ) } private fun LayerSupport.addLayer(selectedCorporateDesign: CorporateDesign, fontDescriptorFragment: FontDescriptorFragment, colors: MultiProvider<CorporateDesignDemoDescriptor, Color>, gapTop: Double, description: String) { val text = "$description: ${selectedCorporateDesign.id}" layers.addLayer(object : AbstractLayer() { override val type: LayerType get() = LayerType.Content override fun paint(paintingContext: LayerPaintingContext) { val gc = paintingContext.gc val centerX = gc.width * 0.5 gc.font(fontDescriptorFragment) gc.fillText(text, centerX, gapTop, Direction.TopRight) 10.fastFor { gc.fill(colors.valueAt(it)) gc.fillRect(centerX + it * 24.0 + 10.0, gapTop, 20.0, 20.0) } } }) } }
0
Kotlin
0
4
af73f0e09e3e7ac9437240e19974d0b1ebc2f93c
4,915
meistercharts
Apache License 2.0
app/src/main/java/dev/danascape/stormci/utils/DeviceUtils.kt
danascape
564,441,039
false
null
package dev.danascape.stormci.utils import java.io.BufferedReader import java.io.InputStream import java.io.InputStreamReader object DeviceUtils { fun getDeviceProperty(command: String): String { try { val p = Runtime.getRuntime().exec(command) val `is`: InputStream? = if (p.waitFor() == 0) { p.inputStream } else { p.errorStream } val br = BufferedReader( InputStreamReader(`is`), 32 ) val line = br.readLine() br.close() return line } catch (ex: Exception) { return "ERROR: " + ex.message } } }
5
Kotlin
5
1
b4c3d16687c89ce801477ef15d017819fe0bf685
715
StormCIApp
Apache License 2.0
app/src/main/java/io/robothouse/androidboilerplate/manager/AuthManager.kt
likppi10
357,961,866
false
null
package io.robothouse.androidboilerplate.manager import com.google.firebase.auth.AuthResult import io.reactivex.Maybe interface AuthManager { fun login(email: String, password: String): Maybe<AuthResult> fun register(username: String, email: String, password: String): Maybe<AuthResult> fun isLoggedIn(): Boolean fun signOut() }
0
Kotlin
0
0
e5b636342b4bee0813e05424e9372d489196fbac
342
MVP_FireStore_Login
MIT License
games-mpp/games-server/src/main/kotlin/net/zomis/games/standalone/Wordle.kt
Zomis
125,767,793
false
{"Kotlin": 1346310, "Vue": 212095, "JavaScript": 43020, "CSS": 4513, "HTML": 1459, "Shell": 801, "Dockerfile": 348}
package net.zomis.games.standalone import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import net.zomis.bestOf import net.zomis.games.dsl.GamesImpl import net.zomis.games.impl.words.Wordle import net.zomis.games.impl.words.wordlists.WordleWords import net.zomis.games.dsl.listeners.BlockingGameListener suspend fun main() { val coroutineScope = CoroutineScope(Dispatchers.Default) val blocking = BlockingGameListener() val count = 1 val games = (1..count).map { GamesImpl.game(Wordle.game) }.map { it.setup().startGame(coroutineScope, 1) { listOf(blocking) } } fun add(index: Int, results: Pair<String, IntArray>) { games[index].model.players.first().guesses.add(Wordle.guessResult(results.first, *results.second)) } fun add(guess: String, results: List<IntArray?>) { results.forEachIndexed { index, intArray -> if (intArray != null) games[index].model.players.first().guesses.add(Wordle.guessResult(guess, *intArray)) } } add(0, "raise" to intArrayOf(2, 0, 0, 1, 0)) // add(0, "_____" to intArrayOf(0,2,0,2,2)) // add("_____", listOf(intArrayOf(0,0,0,1,0), intArrayOf(0,0,0,1,0), intArrayOf(0,0,0,1,0), intArrayOf(1,0,0,0,0))) games.forEach { g -> g.model.players.first().also { it.guesses.forEach { guess -> it.reducePossibleWords(guess) } } } // val words = if (true) games else WordleWords.choosable val guess = WordleWords.choosable.bestOf { guess -> games.map { it.model.players.first() }.filter { !it.completed() }.sumOf { val possibleBonus = if (guess in it.possibleWords) 1 else 0 val score = Wordle.Bot.score(it, guess) println("$guess: ${score.second}") // println("$guess: ${score.second} - ${score.first}") -score.second + possibleBonus } } games.forEach { val possible = it.model.players.first().possibleWords println("${possible.size} Possible: $possible") } println(guess) coroutineScope.cancel() }
89
Kotlin
5
17
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
2,161
Games
MIT License
tools/plugin/gradle-plugin/plugin-build/plugin/src/main/java/dev/elide/buildtools/gradle/plugin/tasks/InflateRuntimeTask.kt
elide-dev
506,113,888
false
null
package dev.elide.buildtools.gradle.plugin.tasks import dev.elide.buildtools.gradle.plugin.ElideExtension import dev.elide.buildtools.gradle.plugin.util.UntarUtil import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option import java.io.File import java.io.FileNotFoundException import java.io.InputStream import java.nio.file.StandardCopyOption /** Task which inflates the packaged JS runtime into a build path where it can be referenced. */ public abstract class InflateRuntimeTask : DefaultTask() { public companion object { /** Name of the inflate-runtime task. */ public const val TASK_NAME: String = "inflateJsRuntime" /** Where we should be able to find the packaged JS runtime. */ private const val RUNTIME_PKG: String = "/dev/elide/buildtools/js/runtime/js-runtime.tar.gz" /** Install the [InflateRuntimeTask] on the provided [extension] and [project]. */ @JvmStatic public fun install(extension: ElideExtension, project: Project): InflateRuntimeTask { return project.tasks.create(TASK_NAME, InflateRuntimeTask::class.java) { it.enableRuntime.set(extension.js.runtime.inject.get()) } } } init { with(project) { destinationDirectory.set( file("${rootProject.buildDir}/js/elideRuntime") ) modulesPath.set( file("${destinationDirectory.get()}/node_modules") ) runtimePackage.set( InflateRuntimeTask::class.java.getResourceAsStream( RUNTIME_PKG ) ?: throw FileNotFoundException( "Failed to locate JS runtime package. This is an internal error; please report it to the Elide " + "project at https://github.com/elide-dev/elide/issues." ) ) } } // Raw/unwrapped input stream for the runtime tarball package. @get:Internal internal abstract val runtimePackage: Property<InputStream> /** Output path prefix to use. */ @get:OutputDirectory @get:Option( option = "destinationDirectory", description = "Where to write the inflated runtime package to", ) internal abstract val destinationDirectory: DirectoryProperty /** Node modules path to inject for the runtime. */ @get:OutputDirectory @get:Option( option = "modulesPath", description = "Path which should be used as a 'node_modules' entry for the JS runtime", ) internal abstract val modulesPath: Property<File> /** Whether to enable runtime overrides. */ @get:Input @get:Option( option = "enableRuntime", description = "Whether to enable Elide's JS runtime overrides", ) internal abstract val enableRuntime: Property<Boolean> /** * Run the inflate-runtime action, by finding the runtime tarball and inflating it to the target [modulesPath]. */ @TaskAction public fun inflateRuntime() { val nodeModsTarget = destinationDirectory.get().dir( "node_modules" ).asFile if (!nodeModsTarget.exists()) { // create the root nodeModsTarget.mkdirs() } // expand the tarball stream into it project.logger.info("Expanding packaged JS runtime...") UntarUtil.untar( runtimePackage.get(), nodeModsTarget, StandardCopyOption.REPLACE_EXISTING, ) } }
39
null
16
97
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
3,800
elide
MIT License
src/fundamentos/Controle/if.kt
ravi2612
327,423,746
false
{"XML": 11, "Text": 1, "Git Attributes": 1, "Markdown": 1, "Kotlin": 109, "Java": 1, "Ignore List": 1}
package fundamentos.Controle fun main() { val nota: Double = 8.3 if(nota >= 7.0){ println("Aprovado") } }
0
Kotlin
0
0
10bcb2e03dc1074a92b7914c9d157f2246dd8f78
127
Kotlin
MIT License
ui/core/src/commonMain/kotlin/br/alexandregpereira/hunter/ui/theme/Theme.kt
alexandregpereira
347,857,709
false
{"Kotlin": 1443810, "Swift": 754, "Shell": 139}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = Color(0xFFFFFFFF), primaryVariant = Color(0xFFFFFFFF), secondary = Color(0xFFE1AFAF), secondaryVariant = Color(0xFFE1AFAF), background = Color(0xFF333333), surface = Color(0xFFFFFFFF).copy(alpha = 0.15f), error = Color(0xFFCF6679), onPrimary = Color(0xFF333333), onSecondary = Color(0xFF333333), onBackground = Color(0xFFF0EAE2), onSurface = Color.White.copy(alpha = 0.80f), onError = Color.Black ) private val LightColorPalette = lightColors( primary = Color(0xFF333333), primaryVariant = Color(0xFF33333), secondary = Color(0xFF886363), secondaryVariant = Color(0xFF886363), background = Color(0xFFF0EAE2), surface = Color.White.copy(alpha = 0.85f), error = Color(0xFFB00020), onPrimary = Color.White, onSecondary = Color.White, onBackground = Color(0xFF655454), onSurface = Color(0xFF333333).copy(alpha = 0.8f), onError = Color.White ) @Composable fun MyTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = typography, shapes = shapes, content = content ) } @Composable fun PreviewTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = previewTypography, shapes = shapes, content = content ) }
4
Kotlin
5
85
5256ca9553e070f11a8cde5515afb74503b1a23c
2,638
Monster-Compendium
Apache License 2.0
src/main/kotlin/g2001_2100/s2011_final_value_of_variable_after_performing_operations/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2011_final_value_of_variable_after_performing_operations // #Easy #Array #String #Simulation #2023_06_23_Time_178_ms_(44.55%)_Space_37.3_MB_(66.34%) class Solution { fun finalValueAfterOperations(operations: Array<String>): Int { var xValue = 0 for (word in operations) { if (word.contains("+")) { xValue++ } else { xValue-- } } return xValue } }
0
Kotlin
20
43
e8b08d4a512f037e40e358b078c0a091e691d88f
477
LeetCode-in-Kotlin
MIT License
catalogue/src/main/kotlin/com/tidal/sdk/catalogue/generated/models/ArtistAttributes.kt
tidal-music
806,866,286
false
{"Kotlin": 1644272, "Shell": 9249}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.tidal.sdk.catalogue.generated.models import com.tidal.sdk.catalogue.generated.models.ExternalLink import com.tidal.sdk.catalogue.generated.models.ImageLink import kotlinx.serialization.Serializable import kotlinx.serialization.SerialName import kotlinx.serialization.Contextual /** * * * @param name Artist name * @param popularity Artist popularity (ranged in 0.00 ... 1.00). Conditionally visible * @param imageLinks Represents available links to, and metadata about, an artist images * @param externalLinks Represents available links to something that is related to an artist resource, but external to the TIDAL API */ @Serializable data class ArtistAttributes ( /* Artist name */ @SerialName(value = "name") val name: kotlin.String, /* Artist popularity (ranged in 0.00 ... 1.00). Conditionally visible */ @SerialName(value = "popularity") val popularity: kotlin.Double, /* Represents available links to, and metadata about, an artist images */ @SerialName(value = "imageLinks") val imageLinks: kotlin.collections.List<ImageLink>? = null, /* Represents available links to something that is related to an artist resource, but external to the TIDAL API */ @SerialName(value = "externalLinks") val externalLinks: kotlin.collections.List<ExternalLink>? = null )
27
Kotlin
0
22
127085338619bab6d540bedf05f7d34a3cd1a9da
1,612
tidal-sdk-android
Apache License 2.0
data/src/main/java/com/jslee/data/paging/extension/Paging.kt
JaesungLeee
675,525,103
false
{"Kotlin": 298357}
package com.jslee.data.paging.extension import androidx.paging.Pager import androidx.paging.PagingConfig import com.jslee.data.PAGING_REQUEST_DATA_SIZE import com.jslee.data.paging.base.MooBesidePagingSource /** * MooBeside * @author jaesung * @created 2023/08/25 */ fun <T : Any> createPager( pageSize: Int = PAGING_REQUEST_DATA_SIZE, executor: suspend (Int) -> List<T> ): Pager<Int, T> = Pager( config = PagingConfig( pageSize = pageSize, enablePlaceholders = false, ), pagingSourceFactory = { MooBesidePagingSource(executor) } )
10
Kotlin
0
4
e2ccbf7e088f0b6c082ea08ae9e8a288bd98fd76
573
MooBeside
MIT License
app/src/main/java/ch/nevis/exampleapp/coroutines/ui/home/HomeViewModel.kt
nevissecurity
580,013,451
false
{"Kotlin": 304631, "Ruby": 7708}
/** * Nevis Mobile Authentication SDK Example App * * Copyright © 2022. Nevis Security AG. All rights reserved. */ package ch.nevis.exampleapp.coroutines.ui.home import androidx.lifecycle.viewModelScope import ch.nevis.exampleapp.coroutines.common.configuration.ConfigurationProvider import ch.nevis.exampleapp.coroutines.common.configuration.Environment import ch.nevis.exampleapp.coroutines.domain.model.error.BusinessException import ch.nevis.exampleapp.coroutines.domain.model.operation.Operation import ch.nevis.exampleapp.coroutines.domain.model.response.* import ch.nevis.exampleapp.coroutines.domain.usecase.GetAccountsUseCase import ch.nevis.exampleapp.coroutines.domain.usecase.GetAuthenticatorsUseCase import ch.nevis.exampleapp.coroutines.domain.usecase.InitializeClientUseCase import ch.nevis.exampleapp.coroutines.ui.base.OutOfBandOperationViewModel import ch.nevis.mobile.sdk.api.localdata.Account import ch.nevis.mobile.sdk.api.localdata.Authenticator import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject /** * View model implementation of Home view. */ @HiltViewModel class HomeViewModel @Inject constructor( /** * An instance of a [ConfigurationProvider] implementation. */ private val configurationProvider: ConfigurationProvider, /** * An instance of a [InitializeClientUseCase] implementation. */ private val initializeClientUseCase: InitializeClientUseCase, /** * An instance of a [GetAccountsUseCase] implementation. */ private val getAccountsUseCase: GetAccountsUseCase, /** * An instance of a [GetAuthenticatorsUseCase] implementation. */ private val getAuthenticatorsUseCase: GetAuthenticatorsUseCase, ) : OutOfBandOperationViewModel() { //region Public Interface /** * Starts initialization of [ch.nevis.mobile.sdk.api.MobileAuthenticationClient]. */ fun initClient() { viewModelScope.launch(errorHandler) { val operationResponse = initializeClientUseCase.execute(configurationProvider.configuration) mutableResponseLiveData.postValue(operationResponse) } } /** * Starts initialization of Home view. This method should be called after a successful client * initialization. */ fun initView() { viewModelScope.launch(errorHandler) { val response = getAccountsUseCase.execute() mutableResponseLiveData.postValue(response) } } /** * Starts an in-band authentication operation. */ fun inBandAuthentication() { viewModelScope.launch(errorHandler) { var response = getAccountsUseCase.execute() if (response is GetAccountsResponse) { response = if (response.accounts.isNotEmpty()) { SelectAccountResponse( Operation.AUTHENTICATION, response.accounts ) } else { ErrorResponse(BusinessException.accountsNotFound()) } } mutableResponseLiveData.postValue(response) } } /** * Starts a change PIN operation. */ fun changePin() { viewModelScope.launch(errorHandler) { var response: Response? = getAuthenticatorsUseCase.execute() if (response is GetAuthenticatorsResponse) { var accounts: Set<Account>? = null response.authenticators.forEach { if (it.aaid() == Authenticator.PIN_AUTHENTICATOR_AAID) { accounts = it.registration().registeredAccounts() } } response = accounts?.let { if (it.isNotEmpty()) { SelectAccountResponse( Operation.CHANGE_PIN, it ) } else { null } } } mutableResponseLiveData.postValue( response ?: ErrorResponse(BusinessException.accountsNotFound()) ) } } /** * Starts de-registration operation. */ fun deregister() { viewModelScope.launch(errorHandler) { when (configurationProvider.environment) { Environment.AUTHENTICATION_CLOUD -> { val operationResponse = deregisterUseCase.execute() mutableResponseLiveData.postValue(operationResponse) } Environment.IDENTITY_SUITE -> { // In this case var response = getAccountsUseCase.execute() if (response is GetAccountsResponse) { response = if (response.accounts.isNotEmpty()) { SelectAccountResponse( Operation.DEREGISTRATION, response.accounts ) } else { ErrorResponse(BusinessException.accountsNotFound()) } } mutableResponseLiveData.postValue(response) } } } } //endregion }
0
Kotlin
0
2
ed9acf8728fd46056f4a9f78caca9c49319cc37e
5,435
nevis-mobile-authentication-sdk-example-app-android-coroutines
MIT License
navigation/navigation-common-lint/src/test/java/androidx/navigation/common/lint/MissingKeepAnnotationDetectorTest.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.common.lint import androidx.navigation.lint.common.KEEP_ANNOTATION import androidx.navigation.lint.common.NAVIGATION_STUBS import androidx.navigation.lint.common.NAV_DEEP_LINK import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Issue import org.junit.Test class MissingKeepAnnotationDetectorTest : LintDetectorTest() { override fun getDetector(): Detector = TypeSafeDestinationMissingAnnotationDetector() override fun getIssues(): List<Issue> = listOf(TypeSafeDestinationMissingAnnotationDetector.MissingKeepAnnotationIssue) @Test fun testNavDestinationBuilderConstructor_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { NavDestinationBuilder<NavGraph>(route = TestClass::class) } """ ) .indented(), *STUBS, ) .allowDuplicates() .run() .expectClean() } @Test fun testNavDestinationBuilderConstructor_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { NavDestinationBuilder<NavGraph>(route = TestClass::class) } """ ) .indented(), *STUBS, ) .allowDuplicates() .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } @Test fun testNavGraphBuilderConstructor_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { NavGraphBuilder(route = TestClass::class) } """ ) .indented(), *STUBS, ) .run() .expectClean() } @Test fun testNavGraphBuilderConstructor_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { NavGraphBuilder(route = TestClass::class) } """ ) .indented(), *STUBS, ) .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings""" ) } @Test fun testNavGraphBuilderNavigation_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { val builder = NavGraphBuilder(provider, TestGraph, null) builder.navigation<TestClass>() } """ ) .indented(), *STUBS, ) .run() .expectClean() } @Test fun testNavGraphBuilderNavigation_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { val builder = NavGraphBuilder(provider, TestGraph, null) builder.navigation<TestClass>() } """ ) .indented(), *STUBS, ) .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } @Test fun testNavProviderNavigation_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { val provider = NavigatorProvider() provider.navigation(route = TestClass::class) } """ ) .indented(), *STUBS, ) .run() .expectClean() } @Test fun testNavProviderNavigation_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class TestClass(val enum: TestEnum) fun navigation() { val provider = NavigatorProvider() provider.navigation(route = TestClass::class) } """ ) .indented(), *STUBS, ) .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } @Test fun testDeeplink_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import kotlinx.serialization.* import androidx.annotation.Keep @Serializable class TestClass @Keep enum class DeepLinkArg @Serializable class DeepLink(val arg: DeepLinkArg) fun navigation() { val builder = NavDestinationBuilder<NavGraph>(route = TestClass::class) builder.deepLink<DeepLink>() } """ ) .indented(), *STUBS, ) .run() .expectClean() } @Test fun testDeeplink_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import kotlinx.serialization.* import androidx.annotation.Keep @Serializable class TestClass enum class DeepLinkArg @Serializable class DeepLink(val arg: DeepLinkArg) fun navigation() { val builder = NavDestinationBuilder<NavGraph>(route = TestClass::class) builder.deepLink<DeepLink>() } """ ) .indented(), *STUBS, ) .run() .expect( """ src/com/example/TestClass.kt:8: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class DeepLinkArg ~~~~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } @Test fun testDeeplinkBuilderSetUriPattern_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class DeepLink(val arg: TestEnum) fun navigation() { val builder = NavDeepLink.Builder() builder.setUriPattern<DeepLink>() } """ ) .indented(), *STUBS, NAV_DEEP_LINK ) .run() .expectClean() } @Test fun testDeeplinkBuilderSetUriPattern_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class DeepLink(val arg: TestEnum) fun navigation() { val builder = NavDeepLink.Builder() builder.setUriPattern<DeepLink>() } """ ) .indented(), *STUBS, NAV_DEEP_LINK ) .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } @Test fun testNavDeepLink_noError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* import androidx.annotation.Keep @Keep enum class TestEnum { ONE, TWO } class DeepLink(val arg: TestEnum) class DeepLink fun navigation() { navDeepLink<DeepLink>() } """ ) .indented(), *STUBS, NAV_DEEP_LINK ) .run() .expectClean() } @Test fun testNavDeepLink_hasError() { lint() .files( kotlin( """ package com.example import androidx.navigation.* enum class TestEnum { ONE, TWO } class DeepLink(val arg: TestEnum) fun navigation() { navDeepLink<DeepLink>() } """ ) .indented(), *STUBS, NAV_DEEP_LINK ) .run() .expect( """ src/com/example/TestEnum.kt:5: Warning: To prevent this Enum's serializer from being obfuscated in minified builds, annotate it with @androidx.annotation.Keep [MissingKeepAnnotation] enum class TestEnum { ONE, TWO } ~~~~~~~~ 0 errors, 1 warnings """ .trimIndent() ) } val STUBS = arrayOf(*NAVIGATION_STUBS, KEEP_ANNOTATION) }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
13,721
androidx
Apache License 2.0
booster-transform-javassist/src/main/kotlin/com/didiglobal/booster/transform/javassist/ClassTransformer.kt
didi
182,968,735
false
null
package com.didiglobal.booster.transform.javassist import com.didiglobal.booster.transform.TransformContext import com.didiglobal.booster.transform.TransformListener import javassist.CtClass import java.io.File /** * Represents class transformer * * @author johnsonlee */ interface ClassTransformer : TransformListener { val name: String get() = javaClass.simpleName fun getReportDir(context: TransformContext): File = File(File(context.reportsDir, name), context.name) fun getReport(context: TransformContext, name: String): File = File(getReportDir(context), name) /** * Transform the specified class node * * @param context The transform context * @param klass The class node to be transformed * @return The transformed class node */ fun transform(context: TransformContext, klass: CtClass) = klass }
41
null
577
4,831
3a72faebf8590537983ca74c0012b69636da3b5d
874
booster
Apache License 2.0
booster-transform-javassist/src/main/kotlin/com/didiglobal/booster/transform/javassist/ClassTransformer.kt
didi
182,968,735
false
null
package com.didiglobal.booster.transform.javassist import com.didiglobal.booster.transform.TransformContext import com.didiglobal.booster.transform.TransformListener import javassist.CtClass import java.io.File /** * Represents class transformer * * @author johnsonlee */ interface ClassTransformer : TransformListener { val name: String get() = javaClass.simpleName fun getReportDir(context: TransformContext): File = File(File(context.reportsDir, name), context.name) fun getReport(context: TransformContext, name: String): File = File(getReportDir(context), name) /** * Transform the specified class node * * @param context The transform context * @param klass The class node to be transformed * @return The transformed class node */ fun transform(context: TransformContext, klass: CtClass) = klass }
41
null
577
4,831
3a72faebf8590537983ca74c0012b69636da3b5d
874
booster
Apache License 2.0
crash-reporter/src/release/kotlin/reporter/CrashReporterImpl.kt
stoyicker
291,049,724
false
null
package reporter import android.content.Context internal sealed class CrashReporterImpl : CrashReporter { object Void : CrashReporterImpl() { override fun init(context: Context) = Unit override fun report(throwable: Throwable) = Unit } object Bugsnag : CrashReporterImpl() { override fun init(context: Context) { com.bugsnag.android.Bugsnag.init(context) } override fun report(throwable: Throwable) { com.bugsnag.android.Bugsnag.notify(throwable) } } }
1
null
1
1
fecfefd7a64dc8c9397343850b9de4d52117b5c3
502
dinger-unpublished
MIT License
sample-link-ui/src/main/java/com/tink/sample/MainLinkUiActivity.kt
mohan88
287,527,619
true
{"Kotlin": 279977, "Shell": 2831}
package com.tink.sample import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.tink.core.Tink import com.tink.link.ui.LinkUser import com.tink.link.ui.TinkLinkUiActivity import com.tink.model.user.Scope import com.tink.model.user.User import com.tink.sample.configuration.Configuration import com.tink.service.network.TinkConfiguration import kotlinx.android.synthetic.main.activity_main_link_ui.* private val MainLinkUiActivity.testTinkLinkConfig get() = TinkConfiguration( environment = Configuration.sampleEnvironment, oAuthClientId = Configuration.sampleOAuthClientId, redirectUri = Uri.Builder() .scheme(getString(R.string.redirect_uri_scheme)) .encodedAuthority(getString(R.string.redirect_uri_host)) .build() ) class MainLinkUiActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main_link_ui) Tink.init(testTinkLinkConfig, applicationContext) linkUiButton.setOnClickListener { val linkUser = createdUser()?.let { LinkUser.ExistingUser(it) } ?: LinkUser.TemporaryUser(market = "SE", locale = "sv_SE") startActivityForResult( TinkLinkUiActivity.createIntent( context = this, linkUser = linkUser, scopes = listOf(Scope.AccountsRead), styleResId = R.style.TinkLinkUiStyle ), REQUEST_CODE ) } } private fun createdUser(): User? { // This can be replaced with a created user for testing permanent user scenarios, etc. return null } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE) { handleResultFromLinkUi(resultCode, data?.extras) } } private fun handleResultFromLinkUi(resultCode: Int, data: Bundle?) { when (resultCode) { TinkLinkUiActivity.RESULT_SUCCESS -> { val authorizationCode = data?.getString(TinkLinkUiActivity.RESULT_KEY_AUTHORIZATION_CODE) if (!authorizationCode.isNullOrEmpty()) { Toast.makeText( this, "Received user authorization code: $authorizationCode", Toast.LENGTH_LONG ).show() } else if (createdUser() == null) { Toast.makeText(this, "Error: Invalid authorization code", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Connection successful", Toast.LENGTH_SHORT).show() } } TinkLinkUiActivity.RESULT_CANCELLED -> { /* Handle cancellation */ } TinkLinkUiActivity.RESULT_FAILURE -> { /* Handle error */ } } } companion object { const val REQUEST_CODE = 100 } }
0
null
0
0
8d7a61d09ca5a40c3e467d668dc0845352714e40
3,265
tink-link-android
MIT License
kotlin-code-generation/src/main/kotlin/spec/KotlinValueClassSpec.kt
toolisticon
804,098,315
false
{"Kotlin": 324780}
package io.toolisticon.kotlin.generation.spec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ExperimentalKotlinPoetApi import com.squareup.kotlinpoet.TypeSpec import io.toolisticon.kotlin.generation.KotlinCodeGeneration.typeSpec.isValueClass import io.toolisticon.kotlin.generation.poet.KDoc import kotlin.reflect.KClass /** * Represents a value class. */ @ExperimentalKotlinPoetApi data class KotlinValueClassSpec( override val className: ClassName, private val spec: TypeSpec ) : KotlinGeneratorTypeSpec<KotlinValueClassSpec>, KotlinValueClassSpecSupplier, KotlinDocumentableSpec { init { require(spec.isValueClass) { "Not a valueClass spec: $spec." } } override fun <T : Any> tag(type: KClass<T>): T? = get().tag(type) override val kdoc: KDoc get() = KDoc(spec.kdoc) override fun spec(): KotlinValueClassSpec = this override fun get(): TypeSpec = spec } /** * Marks the builder and the spec so they are interchangeable. */ @ExperimentalKotlinPoetApi interface KotlinValueClassSpecSupplier : KotlinGeneratorSpecSupplier<KotlinValueClassSpec>, ToFileTypeSpecSupplier { override fun get(): TypeSpec = spec().get() }
5
Kotlin
0
2
fc7f6d6eb9f8a05f41cbe30c17c8e9dfc81b6f7f
1,172
kotlin-code-generation
Apache License 2.0
src/main/kotlin/no/fintlabs/testrunner/TestRunnerService.kt
FINTLabs
871,181,627
false
{"Kotlin": 18814, "Dockerfile": 282}
package no.fintlabs.testrunner import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import no.fintlabs.testrunner.resource.ResourceRepository import no.fintlabs.testrunner.model.ResourceResult import no.fintlabs.testrunner.model.TestRequest import no.fintlabs.testrunner.model.TestResult import org.springframework.stereotype.Service @Service class TestRunnerService( val resourceRepository: ResourceRepository, val fintApiService: FintApiService ) { suspend fun run(orgName: String, testRequest: TestRequest): TestResult = resourceRepository.getResources(testRequest.endpoint)?.let { resources -> createTestResult(orgName, testRequest, resources) } ?: TestResult( emptyList(), "Sorry but we can't find the service: ${testRequest.baseUrl}${testRequest.endpoint}" ) private suspend fun createTestResult(orgName: String, testRequest: TestRequest, resources: MutableList<String>): TestResult = coroutineScope { val resourceResults = resources.map { resource -> async { val resourceResult = ResourceResult( resource, fintApiService.getLastUpdated(testRequest.baseUrl, "${testRequest.endpoint}/$resource", orgName, testRequest.clientName), fintApiService.getCacheSize(testRequest.baseUrl, "${testRequest.endpoint}/$resource", orgName, testRequest.clientName) ) resourceResult.generateStatus() resourceResult } }.awaitAll() TestResult(resourceResults) } }
0
Kotlin
0
0
3010ac394a27aa733d8c3106490e9d02cef85bfc
1,722
fint-test-runner-kotlin
MIT License
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/contenttypes/services/actions/Extensions.kt
TIBHannover
197,416,205
false
{"Kotlin": 2627763, "Cypher": 216189, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package eu.tib.orkg.prototype.contenttypes.services.actions internal val String.isTempId: Boolean get() = startsWith('#') || startsWith('^') internal fun <T, S> List<Action<T, S>>.execute(command: T, initialState: S) = fold(initialState) { state, executor -> executor(command, state) }
0
Kotlin
2
5
31ef68d87499cff09551febb72ae3d38bfbccb98
292
orkg-backend
MIT License
app/src/main/java/com/haoduyoudu/DailyAccounts/showfind.kt
HaoduStudio
495,053,221
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 2, "Proguard": 4, "XML": 107, "Java": 49, "JSON": 1, "Kotlin": 44}
package com.haoduyoudu.DailyAccounts import android.app.ActivityOptions import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.os.Build import android.os.Bundle import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicBlur import android.util.Log import android.view.View import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.activity_showfind.f_background import kotlinx.android.synthetic.main.activity_showfind.f_title import kotlinx.android.synthetic.main.activity_showfind.img_background import kotlinx.android.synthetic.main.activity_showfind.listView import java.io.File class showfind : AppCompatActivity() { lateinit var adapter: TextviewButtonListAdapter private val textviewbuttonList = ArrayList<TextviewButtonList>() lateinit var y:String lateinit var m:String lateinit var lastitem:TextviewButtonList lateinit var lastitemview:View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_showfind) y = intent.getStringExtra("y").toString() m = intent.getStringExtra("m").toString() try{ adapter = TextviewButtonListAdapter(this, R.layout.tewtviewbuttonlistwithnotes_item, textviewbuttonList) initTextviewButtonList() refreshTBL(adapter) listView.adapter = adapter }catch (e:Exception){ e.printStackTrace() } listView.setOnItemClickListener { _, view, position, _ -> val textviewobj = textviewbuttonList[position] val image: ImageView = view.findViewById(R.id.ListImage) val intent = Intent(this,showdailyaccount::class.java) intent.putExtra("path",textviewobj.path) intent.putExtra("date",textviewobj.name) intent.putExtra("index",textviewobj.index) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try{ image.transitionName = "Image" val options = ActivityOptions.makeSceneTransitionAnimation(this, image,"Image") startActivity(intent,options.toBundle()) }catch (e:Exception){ e.printStackTrace() startActivity(intent) } }else{ startActivity(intent) } } listView.setOnItemLongClickListener { _, view, position, _ -> DeleteFileUtil.delete(File(cacheDir.absolutePath,"shot.jpg").absolutePath) FileUtils.savebitmap(rsBlur(this,viewConversionBitmap(f_background)!!,8),cacheDir.absolutePath,"shot.jpg",80) lastitem = textviewbuttonList[position] lastitemview = view if(MyApplication.SHIELD_SHARE_NOTES_ACTON) startActivityForResult(Intent(this,more_ac2::class.java),4) else startActivityForResult(Intent(this,more_ac::class.java),4) true } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode){ 4 -> if(resultCode == RESULT_OK){ if(data != null){ when(data.getStringExtra("type")){ "edit" -> { val image:ImageView = lastitemview.findViewById(R.id.ListImage) val intent = Intent(this,showdailyaccount::class.java) intent.putExtra("path",lastitem.path) intent.putExtra("date",lastitem.name) intent.putExtra("index",lastitem.index) intent.putExtra("rewrite",true) startActivity(intent) } "del" -> { DeleteFileUtil.delete(lastitem.path) initTextviewButtonList() refreshTBL(adapter) Toast.makeText(this,getString(R.string.del_ok), Toast.LENGTH_SHORT).show() } "share" -> { val image:ImageView = lastitemview.findViewById(R.id.ListImage) val intent = Intent(this,showdailyaccount::class.java) intent.putExtra("path",lastitem.path) intent.putExtra("date",lastitem.name) intent.putExtra("index",lastitem.index) intent.putExtra("ac","shot") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try{ image.transitionName = "Image" val options = ActivityOptions.makeSceneTransitionAnimation(this, image,"Image") startActivity(intent,options.toBundle()) }catch (e:Exception){ e.printStackTrace() startActivity(intent) } }else{ startActivity(intent) } } } } } } } private fun refreshTBL(adapter: TextviewButtonListAdapter){ initTextviewButtonList() val pathofdailyaccounts = "/sdcard/Android/data/com.haoduyoudu.DailyAccounts/" var r:MutableList<String> = mutableListOf() for(i in 0..GFN(pathofdailyaccounts).size-1){ if(m!="00"){ println("!=00") if((GFN(pathofdailyaccounts)[i].substring(0,4) == y) && (GFN(pathofdailyaccounts)[i].substring(4,6) == m)){ r.add(0,GFN(pathofdailyaccounts)[i]) } }else{ println("00") if((GFN(pathofdailyaccounts)[i].substring(0,4) == y)) { r.add(0, GFN(pathofdailyaccounts)[i]) } } } var Filenamesofdailyaccounts = r if (Filenamesofdailyaccounts.size != 0) { for (i in 0..Filenamesofdailyaccounts.size-1) { var name = try { (Filenamesofdailyaccounts[i].substring(0,4) + "-" + //87 Filenamesofdailyaccounts[i].substring(4,6) + "-" +Filenamesofdailyaccounts[i].substring(6,8)) }catch (e:Exception){ "Nonedate" } val moodtext = FileUtils.readTxtFile(pathofdailyaccounts+Filenamesofdailyaccounts[i]+"/"+"mood.txt") val moodsplit = moodtext.split("$[%|!|%]$") var imageId: Int if (moodsplit.size == 2) imageId = moodsplit[0].toInt() else imageId = MyApplication.NumberToMoodImage[moodtext.toInt()] ?: R.mipmap.isnoneface textviewbuttonList.add( TextviewButtonList( name, imageId, pathofdailyaccounts+Filenamesofdailyaccounts[i]+"/", "DailyAccounts", notes = FileUtils.readTxtFile(pathofdailyaccounts+ Filenamesofdailyaccounts[i]+ "/week.txt"), index = i)) Log.d("xxx",FileUtils.readTxtFile(pathofdailyaccounts+ Filenamesofdailyaccounts[i]+ "/week.txt")) } try{ Glide.with(this) .load(MyApplication.Mapofweather[MyApplication.weather]) .into(img_background) }catch (e:Exception){ e.printStackTrace() } }else{ f_title.setBackgroundColor(Color.parseColor("#000000")) listView.setBackgroundResource(R.mipmap.weizhaodao) img_background.visibility = View.GONE } adapter.notifyDataSetChanged() } override fun onResume() { super.onResume() print("onRestart()") if(MyApplication.newwrite){ print("ref") initTextviewButtonList() refreshTBL(adapter) } } private fun initTextviewButtonList(){ textviewbuttonList.clear() } fun GFN(dirpathx:String):MutableList<String>{ val fileNames: MutableList<String> = mutableListOf() //在该目录下走一圈,得到文件目录树结构 val fileTree: FileTreeWalk = File(dirpathx).walk() fileTree.maxDepth(1) //需遍历的目录层次为1,即无须检查子目录 .filter { it.isDirectory && it.name != "assest"} //只挑选文件,不处理文件夹 //.filter { it.extension in listOf("m4a","mp3") } .forEach { fileNames.add(it.name) }//循环 处理符合条件的文件 if(fileNames.size!=0){ fileNames.removeAt(0) fileNames.sort() fileNames.reverse() } return fileNames } private fun rsBlur(context: Context, source: Bitmap, radius: Int): Bitmap { val renderScript = RenderScript.create(context) Log.i("blur", "scale size:" + source.width + "*" + source.height) val input = Allocation.createFromBitmap(renderScript, source) val output = Allocation.createTyped(renderScript, input.type) val scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript)) scriptIntrinsicBlur.setInput(input) scriptIntrinsicBlur.setRadius(radius.toFloat()) scriptIntrinsicBlur.forEach(output) output.copyTo(source) renderScript.destroy() return source } fun viewConversionBitmap(v: View,config: Bitmap.Config = Bitmap.Config.ARGB_4444): Bitmap? { val w = v.width val h = v.height val bmp = Bitmap.createBitmap(w, h, config) val c = Canvas(bmp) /** 如果不设置canvas画布为白色,则生成透明 */ v.layout(0, 0, w, h) v.draw(c) return bmp } }
1
Java
7
18
dd15592e9aa9ce24e13d7647ed3a6fb44fa9d876
10,577
DailyNotes
Apache License 2.0
app/src/main/java/com/nide/pocketpass/domain/di/CategoryUseCaseModule.kt
IamDebashis
536,854,826
false
null
package com.nide.pocketpass.domain.di import com.nide.pocketpass.domain.repository.CategoryRepository import com.nide.pocketpass.domain.usecase.GetAllCategoryUseCase import com.nide.pocketpass.domain.usecase.SaveNewCategoryUseCase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent @Module @InstallIn(ViewModelComponent::class) class CategoryUseCaseModule { @Provides fun provideGetAllCategoryUseCase(repository: CategoryRepository): GetAllCategoryUseCase { return GetAllCategoryUseCase(repository) } @Provides fun provideSaveNewCategoryUseCase(repository: CategoryRepository): SaveNewCategoryUseCase { return SaveNewCategoryUseCase(repository) } }
0
Kotlin
0
0
3166737fa1d45beb78a09cd8b4490bd3334cbcd2
775
pocketpass
MIT License
kotlin/src/main/kotlin/net/iamtakagi/tsuki/common/Utils.kt
yude
377,868,015
false
{"TypeScript": 18258, "Kotlin": 18151, "Dockerfile": 1086, "CSS": 367, "JavaScript": 62}
package net.iamtakagi.tsuki.common import java.text.Normalizer operator fun <A, B> Pair<A, B>?.component1(): A? { return this?.first } operator fun <A, B> Pair<A, B>?.component2(): B? { return this?.second } /** * 文字列をあいまいに [Boolean] に変換する * * 1 -> true * "true" -> true * null -> false * else -> false */ internal fun String?.toBooleanFuzzy(): Boolean { return when { this == null -> false toIntOrNull() == 1 -> true else -> toLowerCase().toBoolean() } } fun String.normalize(): String { return Normalizer.normalize(this, Normalizer.Form.NFKC) }
0
TypeScript
0
0
d43e0e25c0bd00676ed2fe4d4b275e842bb37188
616
tsuki-tsukuruzo
MIT License
app/src/main/java/com/example/okegas/model/remote/retrofit/MovieInterface.kt
Sbanyu
763,658,371
false
{"Kotlin": 51352}
package com.example.okegas.model.remote.retrofit import com.example.okegas.model.remote.response.MovieResponse import com.example.okegas.model.remote.response.MovieVidResponse import com.example.okegas.model.remote.response.ReviewResponse import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path interface MovieInterface { @GET("/3/movie/popular?api_key=8cfc3dab986cec364c40f23d9de18456") fun getPopular(): Call<MovieResponse> @GET("/3/movie/top_rated?api_key=8cfc3dab986cec364c40f23d9de18456") fun getTopRated(): Call<MovieResponse> @GET("/3/movie/now_playing?api_key=8cfc3dab986cec364c40f23d9de18456") fun getNowPlaying(): Call<MovieResponse> @GET("/3/movie/{id}/reviews?api_key=8cfc3dab986cec364c40f23d9de18456") fun getReview(@Path("id") id: String): Call<ReviewResponse> @GET("/3/movie/{id}/videos?api_key=8cfc3dab986cec364c40f23d9de18456") fun getMovieVideos(@Path("id") id: String): Call<MovieVidResponse> }
0
Kotlin
0
0
62b1e969907caf140e9945ff3d7a8d1917030bb2
980
OkeGas
MIT License
utils/src/main/java/sergio/sastre/uitesting/utils/testrules/locale/OnActivityCreatedCallback.kt
sergio-sastre
455,446,218
false
{"Kotlin": 291023, "Java": 37391}
package sergio.sastre.uitesting.inapplocale import android.app.Activity import android.app.Application import android.os.Bundle internal interface OnActivityCreatedCallback: Application.ActivityLifecycleCallbacks { override fun onActivityStarted(activity: Activity) { // no-op } override fun onActivityResumed(activity: Activity) { // no-op } override fun onActivityPaused(activity: Activity) { // no-op } override fun onActivityStopped(activity: Activity) { // no-op } override fun onActivitySaveInstanceState( activity: Activity, outState: Bundle ) { // no-op } override fun onActivityDestroyed(activity: Activity) { // no-op } }
3
Kotlin
5
293
c2a1c42d6c354eaa0d0109588529bcab252d79b2
755
AndroidUiTestingUtils
MIT License
analysis/analysis-api/testData/components/resolver/singleByPsi/codeFragment/expressionCodeFragment/ArrayPlusAssignmentOperator.kt
JetBrains
3,432,266
false
null
// IGNORE_FE10 // MODULE: context interface MyList { operator fun get(index: Int): String operator fun set(index: Int, value: String) } // FILE: context.kt fun test(list: MyList) { <caret_context>Unit } // MODULE: main // MODULE_KIND: CodeFragment // CONTEXT_MODULE: context // FILE: fragment.kt // CODE_FRAGMENT_KIND: EXPRESSION list[10] <caret>+= "value"
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
373
kotlin
Apache License 2.0
ekscore/src/main/kotlin/js/node/string_decoder/index.kt
kazhida
141,879,098
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "UNUSED") @file:JsModule("string_decoder") package js.node.string_decoder import js.node.Buffer import kotlin.js.* external interface NodeStringDecoder { fun write(buffer: Buffer): String fun end(buffer: Buffer? = definedExternally /* null */): String } external object StringDecoder
0
Kotlin
0
0
0db86fad2dea30ccd8d31916ea9a4fee784e43ee
487
eks
Apache License 2.0
src/main/resources/archetype-resources/src/test/kotlin/step_definitions/MainPageSteps.kt
secugrow
423,127,303
false
null
package ${package}.step_definitions import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isGreaterThan import ${package}.pageobjects.MainPage class MainPageSteps(testDataContainer: TestDataContainer) : AbstractStepDefs(testDataContainer) { init { } }
6
Kotlin
1
2
05fddae340285e75689574d5ffdffb319d16320f
298
kotlin-archetype
Apache License 2.0
data/musicbrainz/src/commonMain/kotlin/ly/david/musicsearch/data/musicbrainz/di/MusicBrainzAuthModule.kt
lydavid
458,021,427
false
{"Kotlin": 1354732, "HTML": 674577, "Python": 3489, "Shell": 1543, "Ruby": 955}
package ly.david.musicsearch.data.musicbrainz.di import org.koin.core.module.Module expect val musicBrainzAuthModule: Module
104
Kotlin
0
6
4f49e75742e4c2135161e98df9db15b418c6c3fe
127
MusicSearch
Apache License 2.0
src/main/kotlin/org/invenit/hello/kotlin/cli/command/AddSpot.kt
lamao
113,463,656
false
null
package org.invenit.hello.kotlin.cli.command import org.invenit.hello.kotlin.service.SpotService import org.invenit.hello.kotlin.model.Spot /** * @author <NAME> (<EMAIL>) */ class AddSpot : Command { override val description: String get() = "Add new spot to parking" override fun execute(args: List<String>) { val parkingId: Int if (args.isEmpty()) { print("Parking ID: ") parkingId = readLine()?.toInt() ?: throw IllegalArgumentException("Required") } else { parkingId = args[0].toInt() } print("Price: ") val price = readLine()?.toDouble() ?: throw IllegalArgumentException("Wrong format") print("Description (optional): ") val description = readLine() ?: "" val spot = SpotService.save(parkingId, Spot(price, description)) println("Parking spot created: #${spot.id}") } }
1
null
1
1
5db2205464b254444d0b295cab780ec38c8f39d4
917
parking-cli
MIT License
src/main/kotlin/io/github/dockyardmc/protocol/packets/play/serverbound/ServerboundPlayPluginMessagePacket.kt
DockyardMC
650,731,309
false
{"Kotlin": 645767, "Java": 112198}
package io.github.dockyardmc.protocol.packets.play.serverbound import io.github.dockyardmc.annotations.ServerboundPacketInfo import io.github.dockyardmc.annotations.WikiVGEntry import io.github.dockyardmc.extentions.readUtf import io.github.dockyardmc.extentions.toByteArraySafe import io.github.dockyardmc.protocol.PacketProcessor import io.github.dockyardmc.protocol.packets.ProtocolState import io.github.dockyardmc.protocol.packets.ServerboundPacket import io.netty.buffer.ByteBuf import io.netty.channel.ChannelHandlerContext @WikiVGEntry("Serverbound Plugin Message (play)") @ServerboundPacketInfo(18, ProtocolState.PLAY) class ServerboundPlayPluginMessagePacket(val channel: String, val data: ByteArray): ServerboundPacket { override fun handle(processor: PacketProcessor, connection: ChannelHandlerContext, size: Int, id: Int) { processor.playHandler.handlePluginMessage(this, connection) } companion object { fun read(byteBuf: ByteBuf, size: Int): ServerboundPlayPluginMessagePacket { val channel = byteBuf.readUtf() val data = byteBuf.readBytes(byteBuf.readableBytes()) return ServerboundPlayPluginMessagePacket(channel, data.toByteArraySafe()) } } }
4
Kotlin
3
39
ee6b0c7882bb5cfffae4409fc73db0caadad20fe
1,241
Dockyard
MIT License
app/src/main/java/com/repository/androidrepository/data/local/RepositoryDao.kt
Imranseu17
505,557,379
false
{"Kotlin": 45642, "Java": 8779}
package com.repository.androidrepository.data.local import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.repository.androidrepository.models.Items @Dao interface RepositoryDao { @Query("SELECT * FROM items") fun getAllRepositorys() : LiveData<List<Items>> @Query("SELECT * FROM items WHERE id = :id") fun getRepository(id: String): LiveData<Items> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(Repository: List<Items>?) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(Repository: List<Items>?) }
0
Kotlin
0
1
89544d213b706765fd3f28eb620fe2bffafd2501
680
GitRepoAndroid
Apache License 2.0
idea/testData/quickfix/typeMismatch/parameterTypeMismatch/changeFunctionParameterType4.kt
staltz
50,647,805
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
// "Change parameter 'z' type of function 'foo' to '(Int) -> String'" "false" fun foo(y: Int = 0, z: (Int) -> String = {""}) { foo { ""<caret> as Int "" } }
0
Java
0
1
c9cc9c55cdcc706c1d382a1539998728a2e3ca50
181
kotlin
Apache License 2.0
widgetssdk/src/main/java/com/glia/widgets/helper/IntentConfigurationHelper.kt
salemove
312,288,713
false
null
package com.glia.widgets.helper import android.app.Activity import android.content.Context import android.content.Intent import android.provider.Settings import androidx.core.net.toUri import com.glia.androidsdk.Engagement.MediaType import com.glia.widgets.call.CallActivity import com.glia.widgets.call.Configuration import com.glia.widgets.di.Dependencies internal interface IntentConfigurationHelper { fun createForCall(context: Context, mediaType: MediaType, upgradeToCall: Boolean = true): Intent fun createForOverlayPermissionScreen(activity: Activity): Intent } internal class IntentConfigurationHelperImpl : IntentConfigurationHelper { private val defaultBuilder: Configuration.Builder get() = Dependencies.getSdkConfigurationManager() .createWidgetsConfiguration() .let(Configuration.Builder()::setWidgetsConfiguration) override fun createForCall(context: Context, mediaType: MediaType, upgradeToCall: Boolean): Intent = defaultBuilder .setMediaType(mediaType) .setIsUpgradeToCall(upgradeToCall) .run { CallActivity.getIntent(context, build()) } override fun createForOverlayPermissionScreen(activity: Activity): Intent = activity.run { Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, "package:${packageName}".toUri()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } }
3
null
1
7
40ee60fa683c155eee923b5c3ae1a2c0610f0677
1,368
android-sdk-widgets
MIT License
src/main/kotlin/io/github/intellij/dlanguage/inspections/DeleteIsDeprecated.kt
intellij-dlanguage
27,922,930
false
null
package io.github.intellij.dlanguage.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import io.github.intellij.dlanguage.DlangBundle import io.github.intellij.dlanguage.psi.DLanguageDeleteExpression import io.github.intellij.dlanguage.psi.DlangVisitor /** * Created by francis on 1/5/2018. */ class DeleteIsDeprecated : LocalInspectionTool() { override fun getDescriptionFileName(): String = "DeleteIsDeprecated.html" override fun getDisplayName(): String = "DeleteIsDeprecated" override fun getGroupDisplayName(): String = DlangBundle.message("d.inspections.groupname") override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return DeleteIsDeprecatedVisitor(holder) } } class DeleteIsDeprecatedVisitor(val holder: ProblemsHolder) : DlangVisitor() { override fun visitDeleteExpression(o: DLanguageDeleteExpression) { holder.registerProblem(o, "Avoid using the 'delete' keyword. It is deprecated") } }
170
null
51
328
298d1db45d2b35c1715a1b1b2e1c548709101f05
1,099
intellij-dlanguage
MIT License
wallet-sdk/src/main/java/com/metaverse/world/wallet/sdk/repository/network/response/nft/NftMetaInfoResponse.kt
FNCYchain
676,828,824
false
null
package com.metaverse.world.wallet.sdk.repository.network.response.nft import com.metaverse.world.wallet.sdk.model.nft.FncyNFTMetaInfo @kotlinx.serialization.Serializable internal data class NFTMetaInfoResponse( var gameName: String? = null ) { var name: String? = null var description: String? = null var properties: Map<String, String>? = null var status: String? = null } internal fun NFTMetaInfoResponse.asDomain() = FncyNFTMetaInfo( gameName = gameName, ).also { it.name = name it.description = description it.properties = properties it.status = status }
0
Kotlin
1
0
0b07766840a014acb3baaa892f7257f0e03eb92f
603
fncy-wallet-android-sdk
Apache License 2.0
src/main/kotlin/io/kotlintest/matchers/DoubleMatchers.kt
coacoas
103,796,706
true
{"Kotlin": 152626}
package io.kotlintest.matchers infix fun Double.plusOrMinus(tolerance: Double): ToleranceMatcher = ToleranceMatcher(this, tolerance) fun exactly(d: Double): Matcher<Double> = object : Matcher<Double> { override fun test(value: Double) = Result(value == d, "$value is not equal to expected value $d") } class ToleranceMatcher(val expected: Double, val tolerance: Double) : Matcher<Double> { override fun test(value: Double): Result { if (tolerance == 0.0) println("[WARN] When comparing doubles consider using tolerance, eg: a shouldBe b plusOrMinus c") val diff = Math.abs(value - expected) return Result(diff <= tolerance, "$value should be equal to $expected") } infix fun plusOrMinus(tolerance: Double): ToleranceMatcher = ToleranceMatcher(expected, tolerance) }
0
Kotlin
0
0
00f36555db3a5bfd16daf2a8cbfff478b710f0ff
796
kotlintest
Apache License 2.0
libs/hello-libs/hello-app/src/jsMain/kotlin/com/bkahlert/hello/app/env/environmentView.kt
bkahlert
439,967,726
false
{"Kotlin": 1721426, "CSS": 20318, "JavaScript": 11584, "Shell": 6384, "HTML": 2857, "SCSS": 588}
package com.bkahlert.hello.app.env import com.bkahlert.hello.dataview.dataView import com.bkahlert.hello.fritz2.lensForFirst import com.bkahlert.hello.fritz2.lensForSecond import dev.fritz2.core.RenderContext import dev.fritz2.core.Store import dev.fritz2.core.lensOf import dev.fritz2.core.storeOf public fun RenderContext.environmentView( environment: Environment, ): Unit = environmentView(storeOf(environment)) public fun RenderContext.environmentView( environment: Store<Environment>, ) { dataView( name = "Environment", store = environment .map( lensOf( id = "properties", getter = { it.toList() }, setter = { p, _ -> p }, ) ), lenses = listOf( lensForFirst(), lensForSecond(), ), ) }
0
Kotlin
0
0
92e60b7eb9a74cfa957e05e3bf9e59f3ce3a582d
882
hello
MIT License
src/main/kotlin/org/randomcat/agorabot/commands/Irc.kt
cybernetics
334,786,714
true
{"Kotlin": 247212}
package org.randomcat.agorabot.commands import org.randomcat.agorabot.commands.impl.* import org.randomcat.agorabot.irc.IrcUserListConfig import org.randomcat.agorabot.irc.MutableIrcUserListMessageMap import org.randomcat.agorabot.permissions.GuildScope private val USER_LIST_PERMISSION = GuildScope.command("irc").action("user_list_manage") class IrcCommand( strategy: BaseCommandStrategy, private val lookupConnectedIrcChannel: (guildId: String, channelId: String) -> String?, private val persistentWhoMessageMap: MutableIrcUserListMessageMap, ) : BaseCommand(strategy) { override fun TopLevelArgumentDescriptionReceiver<ExecutionReceiverImpl, PermissionsExtensionMarker>.impl() { subcommands { subcommand("user_list") { subcommand("create") { noArgs().permissions(USER_LIST_PERMISSION) { _ -> requiresGuild { guildInfo -> val connectedIrcChannel = lookupConnectedIrcChannel(guildInfo.guildId, currentChannel().id) if (connectedIrcChannel == null) { respond("There is no IRC channel connected to this Discord channel.") return@permissions } currentChannel().sendMessage("**IRC USER LIST TO BE FILLED**").queue { message -> persistentWhoMessageMap.addConfigForGuild( guildId = guildInfo.guildId, config = IrcUserListConfig( discordChannelId = currentChannel().id, discordMessageId = message.id, ircChannelName = connectedIrcChannel, ), ) } } } } subcommand("remove_all") { noArgs().permissions(USER_LIST_PERMISSION) { _ -> requiresGuild { guildInfo -> persistentWhoMessageMap.clearConfigsForGuild(guildInfo.guildId) respond( "Persistent who messages will no longer update. You probably want to delete them now." ) } } } } } } }
0
null
0
0
95e5dcf7e3baeb7a4ce35b37b32f922ad5d38016
2,548
AgoraBot
MIT License
src/main/kotlin/entity/locations/PokemonEncounter.kt
Tykok
518,240,433
false
null
package entity.locations import entity.common.NamedApiResource import entity.common.VersionEncounterDetail import entity.pokemon.Pokemon /** * @see <a href="https://pokeapi.co/docs/v2#pokemonencounter">Documentation of PokeApi</a> * * @author Tykok * @version 1.0.0 * @since 2022-08-27 */ class PokemonEncounter( /** * The Pokémon being encountered. * @see NamedApiResource * @see Pokemon */ val pokemon: NamedApiResource, /** * A list of versions and encounters with Pokémon that might happen in the referenced location area. * @see VersionEncounterDetail */ val version_details: Array<VersionEncounterDetail> )
12
Kotlin
0
1
b017ec3b0cacc436e6ce975610b6bb9209e88026
672
PokeAPI-Kotlin
MIT License
libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/route/line/model/RouteLineClearValue.kt
Imanrt1981
415,142,931
true
{"Kotlin": 3905745, "Java": 25631, "Python": 11580, "Makefile": 6255, "Shell": 1686}
package com.mapbox.navigation.ui.maps.route.line.model import com.mapbox.geojson.FeatureCollection /** * Represents data used to remove the route line(s) from the map. * * @param primaryRouteSource a feature collection representing the primary route * @param alternativeRouteSourceSources feature collections representing alternative routes * @param waypointsSource a feature collection representing the origin and destination icons */ class RouteLineClearValue internal constructor( val primaryRouteSource: FeatureCollection, val alternativeRouteSourceSources: List<FeatureCollection>, val waypointsSource: FeatureCollection, )
0
null
0
0
50930196797ea3c77a2faee9976ed31acd5eecca
649
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/richmat/mytuya/ui/Home/Routes.kt
jasonpanjunnan
424,535,534
false
{"Kotlin": 369748}
package com.richmat.mytuya.ui.Home import androidx.annotation.StringRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.LightMode import androidx.compose.material.icons.rounded.PersonPinCircle import androidx.compose.ui.graphics.vector.ImageVector import com.richmat.mytuya.R //lei si mei ju sealed class Page(val route: String) { object Home : Page("home_page") object Smart : Page("smart_page") object Myself : Page("myself_page") object SearchDevice : Page("searchDevice_page") object SignIn : Page("signIn_page") object SignUp : Page("signUp_page") object Login : Page("login_page") object VerificationCode : Page("verificationCode_page") object SetPassword : Page("setPassword_page") object Setting : Page("setting_page") object SelectDevice : Page("selectDevice_page") object SearchUiState : Page("searchUiState_page") object DevSetting : Page("devSetting_page") } sealed class DevicePage(val route: String) { object Gateway : DevicePage("gateway_devicePage") object DetailDevice : DevicePage("detailDevice_devicePage") object SearchChildDevice : DevicePage("searchDevice_devicePage") object BodySensor : DevicePage("bodySensor_devicePage") object BulbLight : DevicePage("bulbLight_devicePage") } sealed class Login(val route: String) { object LoginScreen : Login("login_screen") object SendVerifyCodeScreen : Login("send_verifyCode_screen") object ForgetLoginScreen : Login("forget_login_screen") object VerifyRegisterCodeScreen : Login("verify_register_code_screen") object SetAccountPasswordScreen : Login("set_account_password_screen") object SelectCountryScreen : Login("select_country_screen") object RegisterScreen : Login("register_screen") } sealed class TabItem(val page: Page, @StringRes val resourceId: Int, val iconImage: ImageVector) { object HomeTab : TabItem(Page.Home, R.string.home, Icons.Rounded.Home) object SmartTab : TabItem(Page.Smart, R.string.smart, Icons.Rounded.LightMode) object MyselfTab : TabItem(Page.Myself, R.string.myself, Icons.Rounded.PersonPinCircle) }
0
Kotlin
0
1
e3d1c1a859369485ec7ef675f4e574cf32e0e01d
2,212
RichmatTuya
Apache License 2.0
rest-api-server/src/integrationTest/kotlin/org/orkg/community/adapter/input/rest/ContributorControllerTest.kt
TIBHannover
197,416,205
false
{"Kotlin": 2686425, "Cypher": 216726, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package org.orkg.community.adapter.input.rest import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.orkg.auth.domain.User import org.orkg.auth.input.AuthUseCase import org.orkg.auth.output.UserRepository import org.orkg.testing.spring.restdocs.RestDocumentationBaseTest import org.springframework.beans.factory.annotation.Autowired import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document import org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath import org.springframework.restdocs.payload.PayloadDocumentation.responseFields import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status import org.springframework.transaction.annotation.Transactional @DisplayName("Contributor Controller") @Transactional internal class ContributorControllerTest : RestDocumentationBaseTest() { @Autowired private lateinit var service: AuthUseCase @Autowired private lateinit var repository: UserRepository @AfterEach fun cleanup() { repository.deleteAll() } @Test @DisplayName("When contributor is found Then returns contributor information") fun getById() { service.registerUser("<EMAIL>", "IRRELEVANT", "Some User") val id = service .findByEmail("<EMAIL>") .map(User::id) .orElseThrow { IllegalStateException("Test setup broken! Should find the user created!") } mockMvc .perform(getRequestTo("/api/contributors/$id")) .andExpect(status().isOk) .andDo( document( snippet, contributorListResponseFields() ) ) } private fun contributorListResponseFields() = responseFields( fieldWithPath("id").description("The contributor ID."), fieldWithPath("display_name").description("The name of the contributor."), fieldWithPath("joined_at").description("The time the contributor joined the project (in ISO 8601 format)."), fieldWithPath("organization_id").description("The ID of the organization the contributor belongs to. All zeros if the contributor is not part of an organization."), fieldWithPath("observatory_id").description("The ID of the observatory the contributor belongs to. All zeros if the contributor has not joined an observatory."), fieldWithPath("gravatar_id").description("The ID of the contributor on https://gravatar.com/[Gravatar]. (Useful for generating profile pictures.)"), fieldWithPath("avatar_url").description("A URL to an avatar representing the user. Currently links to https://gravatar.com/[Gravatar].") ) }
0
Kotlin
2
5
0df68801d82d8c36f6d3778d1971694b1b88b062
2,792
orkg-backend
MIT License
api/src/main/kotlin/com/projectfawkes/api/authentication/UseAuth.kt
Justin9four
320,391,812
false
null
package com.projectfawkes.api.auth @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) annotation class UseAuth(val authType: AuthType) enum class AuthType { SERVICEACCOUNT, ADMIN, USER, PUBLIC }
0
Kotlin
0
1
fc9f0b6c62f2018723cb7aa4e96c008c73e33d8b
209
NarwhalNotesAPI
MIT License
lib/oas-stub-engine/src/main/kotlin/io/github/ktakashi/oas/engine/plugins/PluginService.kt
ktakashi
673,843,773
false
null
package io.github.ktakashi.oas.engine.plugins import com.fasterxml.jackson.databind.ObjectMapper import com.github.benmanes.caffeine.cache.CacheLoader import com.github.benmanes.caffeine.cache.Caffeine import io.github.ktakashi.oas.engine.storages.StorageService import io.github.ktakashi.oas.model.PluginDefinition import io.github.ktakashi.oas.plugin.apis.ApiPlugin import io.github.ktakashi.oas.plugin.apis.PluginContext import io.github.ktakashi.oas.plugin.apis.RequestContext import io.github.ktakashi.oas.plugin.apis.ResponseContext import io.github.ktakashi.oas.plugin.apis.Storage import jakarta.inject.Inject import jakarta.inject.Named import jakarta.inject.Singleton import java.time.Duration import java.util.Optional @Named @Singleton class PluginService @Inject constructor(private val pluginCompilers: Set<PluginCompiler>, private val storageService: StorageService, private val objectMapper: ObjectMapper) { private val pluginCache = Caffeine.newBuilder() .expireAfterWrite(Duration.ofHours(1)) .build(CacheLoader<PluginDefinition, Class<ApiPlugin>> { pluginCompilers.firstOrNull { c -> c.support(it.type) }?.compileScript(it.script) }) fun applyPlugin(requestContext: RequestContext, responseContext: ResponseContext): ResponseContext = storageService.getPluginDefinition(requestContext.applicationName, requestContext.apiPath).map { plugin -> try { val compiled = pluginCache.get(plugin) val stubData = storageService.getApiData(requestContext.applicationName) val code = compiled.getConstructor().newInstance() val context = PluginContextData(requestContext, responseContext, storageService.sessionStorage, stubData.orElseGet { mapOf() }, objectMapper) code.customize(context) } catch (e: Exception) { responseContext } }.orElse(responseContext) } data class PluginContextData(override val requestContext: RequestContext, override val responseContext: ResponseContext, override val sessionStorage: Storage, private val apiData: Map<String, ByteArray>, private val objectMapper: ObjectMapper) :PluginContext { override fun getApiData(label: String): Optional<ByteArray> = Optional.ofNullable(apiData[label]) override fun <T> getApiData(label: String, clazz: Class<T>): Optional<T> = getApiData(label).map { v -> objectMapper.readValue(v, clazz)} }
0
Kotlin
0
1
00f9c8368d3b6292e9fddd0e5f55212c19de6dfc
2,771
oas-stub
Apache License 2.0
main/src/main/java/com/pyamsoft/tetherfi/main/MainView.kt
pyamsoft
475,225,784
false
null
package com.pyamsoft.tetherfi.main sealed class MainView(val name: String) { object Status : MainView("Hotspot") object Info : MainView("How To") }
4
Kotlin
2
52
75adef3c88e8957b874c0e58f2bdec5d5ef3151c
153
tetherfi
Apache License 2.0
feature/home/src/main/java/st/slex/csplashscreen/feature/home/domain/MainScreenInteractorImpl.kt
stslex
413,161,718
false
null
package st.slex.csplashscreen.feature.home.domain import st.slex.csplashscreen.core.collection.data.CollectionsRepository import st.slex.csplashscreen.core.photos.data.PhotosRepository import st.slex.csplashscreen.core.network.model.mapToDomain import st.slex.csplashscreen.core.network.model.toDomain import st.slex.csplashscreen.core.network.model.ui.CollectionDomainModel import st.slex.csplashscreen.core.network.model.ui.ImageModel class MainScreenInteractorImpl( private val photosRepository: PhotosRepository, private val collectionsRepository: CollectionsRepository ) : MainScreenInteractor { override suspend fun getAllCollections( page: Int, pageSize: Int ): List<CollectionDomainModel> = collectionsRepository .getAllCollections( page = page, pageSize = pageSize ) .mapToDomain() override suspend fun getAllPhotos( page: Int, pageSize: Int ): List<ImageModel> = photosRepository .getAllPhotos( page = page, pageSize = pageSize ) .toDomain() }
2
Kotlin
0
3
60a9a26b597d8d8a3a7749b1506bd7230f04cb06
1,109
CSplashScreen
Apache License 2.0
app/src/main/java/com/twilio/conversations/app/manager/ConnectivityMonitor.kt
twilio
351,834,939
false
null
package com.twilio.conversations.app.manager import android.content.Context import android.content.Context.CONNECTIVITY_SERVICE import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET import android.net.NetworkRequest import android.os.Build import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow interface ConnectivityMonitor { val isNetworkAvailable: StateFlow<Boolean> } class ConnectivityMonitorImpl(context: Context) : ConnectivityMonitor { private val connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager override val isNetworkAvailable = MutableStateFlow(getInitialConnectionStatus()) init { connectivityManager.registerNetworkCallback(NetworkRequest.Builder().build(), ConnectionStatusCallback()) } @Suppress("DEPRECATION") private fun getInitialConnectionStatus(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val network = connectivityManager.activeNetwork val capabilities = connectivityManager.getNetworkCapabilities(network) capabilities?.hasCapability(NET_CAPABILITY_INTERNET) ?: false } else { val activeNetwork = connectivityManager.activeNetworkInfo // Deprecated in 29 activeNetwork != null && activeNetwork.isConnectedOrConnecting // // Deprecated in 28 } } private inner class ConnectionStatusCallback : ConnectivityManager.NetworkCallback() { private val activeNetworks: MutableList<Network> = mutableListOf() override fun onLost(network: Network) { activeNetworks.removeAll { activeNetwork -> activeNetwork == network } isNetworkAvailable.value = activeNetworks.isNotEmpty() } override fun onAvailable(network: Network) { if (activeNetworks.none { activeNetwork -> activeNetwork == network }) { activeNetworks.add(network) } isNetworkAvailable.value = activeNetworks.isNotEmpty() } } }
3
Kotlin
7
7
3d7660e01b23cea30231d3e1523dd9ebceff21d8
2,139
twilio-conversations-demo-kotlin
MIT License
api/src/main/kotlin/org/web3j/corda/networkmap/NotariesResource.kt
iantstaley
733,498,695
false
null
/* * Copyright 2019 Web3 Labs 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.web3j.corda.networkmap import javax.ws.rs.Consumes import javax.ws.rs.DELETE import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.core.MediaType interface NotariesResource { /** * Upload a signed NodeInfo object to the network map. */ @POST @Path("{notaryType}") @Consumes(MediaType.APPLICATION_OCTET_STREAM) fun create(@PathParam("notaryType") type: NotaryType, nodeInfo: ByteArray): String /** * Delete a notary with the node key. */ @DELETE @Path("{notaryType}") @Consumes(MediaType.TEXT_PLAIN) fun delete(@PathParam("notaryType") type: NotaryType, nodeKey: String) }
1
null
1
3
c5786f5e822cf95d3e5e17e167217f75db2eba3d
1,275
web3j-corda
Apache License 2.0
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/exceptions/InvalidTopicException.kt
kinshuk4
628,399,574
false
null
package io.pleo.antaeus.core.exceptions class InvalidTopicException(topicName: String) : Exception("Producer for topic name '$topicName' does not exist")
0
Kotlin
0
0
418c12a68af05ef74b68bb8d5897d2d531f0c614
160
antaeus
Creative Commons Zero v1.0 Universal
core/descriptors/src/org/jetbrains/kotlin/builtins/functions/BuiltInFictitiousFunctionClassFactory.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * 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.jetbrains.kotlin.builtins.functions import org.jetbrains.kotlin.builtins.BuiltInsPackageFragment import org.jetbrains.kotlin.builtins.FunctionInterfacePackageFragment import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.deserialization.ClassDescriptorFactory import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.storage.StorageManager /** * Produces descriptors representing the fictitious classes for function types, such as kotlin.Function1 or kotlin.reflect.KFunction2. */ class BuiltInFictitiousFunctionClassFactory( private val storageManager: StorageManager, private val module: ModuleDescriptor ) : ClassDescriptorFactory { @OptIn(AllowedToUsedOnlyInK1::class) override fun shouldCreateClass(packageFqName: FqName, name: Name): Boolean { val string = name.asString() return (string.startsWith("Function") || string.startsWith("KFunction") || string.startsWith("SuspendFunction") || string.startsWith("KSuspendFunction")) // an optimization && FunctionTypeKindExtractor.Default.getFunctionalClassKindWithArity(packageFqName, string) != null } @OptIn(AllowedToUsedOnlyInK1::class) override fun createClass(classId: ClassId): ClassDescriptor? { if (classId.isLocal || classId.isNestedClass) return null val className = classId.relativeClassName.asString() if ("Function" !in className) return null // An optimization val packageFqName = classId.packageFqName val (kind, arity) = FunctionTypeKindExtractor.Default.getFunctionalClassKindWithArity(packageFqName, className) ?: return null val builtInsFragments = module.getPackage(packageFqName).fragments.filterIsInstance<BuiltInsPackageFragment>() // JS IR backend uses separate FunctionInterfacePackageFragment for function interfaces val containingPackageFragment = builtInsFragments.filterIsInstance<FunctionInterfacePackageFragment>().firstOrNull() ?: builtInsFragments.first() return FunctionClassDescriptor(storageManager, containingPackageFragment, kind, arity) } override fun getAllContributedClassesIfPossible(packageFqName: FqName): Collection<ClassDescriptor> { // We don't want to return 256 classes here since it would cause them to appear in every import list of every file // and likely slow down compilation very much return emptySet() } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,232
kotlin
Apache License 2.0
me-domain/src/main/kotlin/shop/hyeonme/domain/inventory/mapper/InventoryPersistenceMapper.kt
TEAM-hyeonme
776,784,109
false
{"Kotlin": 82183, "Dockerfile": 204}
package shop.hyeonme.domain.inventory.mapper import shop.hyeonme.domain.gifticon.mapper.toDomain import shop.hyeonme.domain.gifticon.mapper.toModel import shop.hyeonme.domain.inventory.entity.InventoryEntity import shop.hyeonme.domain.inventory.model.Inventory fun Inventory.toDomain() = InventoryEntity( id = id, expiredAt = expiredAt, barcodeUrl = barcodeUrl, gifticon = gifticon.toDomain() ) fun InventoryEntity.toModel() = Inventory( id = id, expiredAt = expiredAt, barcodeUrl = barcodeUrl, gifticon = gifticon.toModel() )
0
Kotlin
0
0
6ac080310d2d7721e8a1e191fff03382a237e31a
561
ME-server
MIT License
src/jvmMain/kotlin/tools/empathy/studio/EditorContext.kt
ontola
624,799,212
false
null
package tools.empathy.studio import kotlinx.serialization.Serializable @Serializable data class EditorContext( val core: String = "", val localOntologies: Map<String, String> = emptyMap(), val ontologies: Map<String, String> = emptyMap(), )
0
Kotlin
0
0
2e9fa6622e00ebf5ffd1cf6156e8abd774430f7e
255
libro-cache
MIT License
src/main/java/org/radarbase/management/web/rest/errors/RadarWebApplicationException.kt
RADAR-base
90,646,368
false
{"Kotlin": 1000491, "TypeScript": 476028, "HTML": 280734, "Java": 24215, "SCSS": 20166, "Scala": 16198, "JavaScript": 3395, "Dockerfile": 2950, "Shell": 734, "CSS": 425}
package org.radarbase.management.web.rest.errors import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException import java.text.SimpleDateFormat import java.util.* /** * A base parameterized exception, which can be translated on the client side. * * * For example: * * * `throw new RadarWebApplicationException("Message to client", "entity", * "error.errorCode")` * * * can be translated with: * * * `"error.myCustomError" : "The server says {{param0}} to {{param1}}"` */ open class RadarWebApplicationException @JvmOverloads constructor( status: HttpStatus?, message: String?, entityName: String, errorCode: String?, params: Map<String, String?>? = emptyMap<String, String>() ) : ResponseStatusException(status, message, null) { override val message: String? val entityName: String val errorCode: String? private val paramMap: MutableMap<String, String?> = HashMap() /** * A base parameterized exception, which can be translated on the client side. * @param status [HttpStatus] code. * @param message message to client. * @param entityName entityRelated from [EntityName] * @param errorCode errorCode from [ErrorConstants] * @param params map of optional information. */ /** * Create an exception with the given parameters. This will be used to to create response * body of the request. * * @param message Error message to the client * @param entityName Entity related to the exception * @param errorCode error code defined in MP if relevant. */ init { // add default timestamp first, so a timestamp key in the paramMap will overwrite it paramMap["timestamp"] = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) .format(Date()) paramMap.putAll(params!!) this.message = message this.entityName = entityName this.errorCode = errorCode } val exceptionVM: RadarWebApplicationExceptionVM get() = RadarWebApplicationExceptionVM(message, entityName, errorCode, paramMap) }
71
Kotlin
15
21
b1187914f832fcaa0321b3b440a68612b6fc8196
2,115
ManagementPortal
Apache License 2.0
src/main/kotlin/me/cephetir/bladecore/utils/minecraft/render/shaders/Stencil.kt
Cephetir
580,488,458
false
null
package me.cephetir.bladecore.utils.minecraft.render.shaders import me.cephetir.bladecore.utils.mc import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.shader.Framebuffer import org.lwjgl.opengl.EXTFramebufferObject import org.lwjgl.opengl.GL11 object Stencil { fun dispose() { GL11.glDisable(GL11.GL_STENCIL_TEST) GlStateManager.disableAlpha() GlStateManager.disableBlend() } fun erase(invert: Boolean) { GL11.glStencilFunc(if (invert) GL11.GL_EQUAL else GL11.GL_NOTEQUAL, 1, 65535) GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE) GlStateManager.colorMask(true, true, true, true) GlStateManager.enableAlpha() GlStateManager.enableBlend() GL11.glAlphaFunc(GL11.GL_GREATER, 0.0f) } fun write(renderClipLayer: Boolean) { checkSetupFBO() GL11.glClearStencil(0) GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT) GL11.glEnable(GL11.GL_STENCIL_TEST) GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 65535) GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE) if (!renderClipLayer) GlStateManager.colorMask(false, false, false, false) } fun write(renderClipLayer: Boolean, fb: Framebuffer?) { checkSetupFBO(fb) GL11.glClearStencil(0) GL11.glClear(GL11.GL_STENCIL_BUFFER_BIT) GL11.glEnable(GL11.GL_STENCIL_TEST) GL11.glStencilFunc(GL11.GL_ALWAYS, 1, 65535) GL11.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE) if (!renderClipLayer) GlStateManager.colorMask(false, false, false, false) } fun checkSetupFBO() { val fbo = mc.framebuffer if (fbo != null && fbo.depthBuffer > -1) { setupFBO(fbo) fbo.depthBuffer = -1 } } fun checkSetupFBO(fbo: Framebuffer?) { if (fbo != null && fbo.depthBuffer > -1) { setupFBO(fbo) fbo.depthBuffer = -1 } } fun setupFBO(fbo: Framebuffer) { EXTFramebufferObject.glDeleteRenderbuffersEXT(fbo.depthBuffer) val stencil_depth_buffer_ID = EXTFramebufferObject.glGenRenderbuffersEXT() EXTFramebufferObject.glBindRenderbufferEXT(36161, stencil_depth_buffer_ID) EXTFramebufferObject.glRenderbufferStorageEXT(36161, 34041, mc.displayWidth, mc.displayHeight) EXTFramebufferObject.glFramebufferRenderbufferEXT(36160, 36128, 36161, stencil_depth_buffer_ID) EXTFramebufferObject.glFramebufferRenderbufferEXT(36160, 36096, 36161, stencil_depth_buffer_ID) } }
0
Kotlin
1
4
392d5331b3baff739e6b47d1dbf4968af0149c7d
2,589
BladeCore
MIT License