path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/testdata/filetypes/skin/inspections/com/example/KColorArrayHolder.kt
mmmika
96,202,635
true
{"Kotlin": 726544, "Java": 50280, "Lex": 3443, "HTML": 754}
package com.example import com.badlogic.gdx.graphics.Color import com.example.ColorArrayHolder class KColorArrayHolder { val colors = arrayOf(Color.BLACK) val ccolors = arrayOf(arrayOf(Color.BLUE)) val bool = true val i = 1 val f = 1.0 val byte: Byte = 1 var nc: Array<Color>? = null var nnc: Array<Color?>? = null val m = arrayOf(arrayOf(ColorArrayHolder())) }
0
Kotlin
0
0
f7791fe64f69d345f612586d7cc0d38a41d60bae
384
LibGDXPlugin
Apache License 2.0
modules/module-compose/src/main/java/com/bbgo/module_compose/theme/Dimens.kt
bbggo
371,705,786
false
null
package com.bytebitx.compose.theme import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp val dp05 = 0.5.dp val dp2 = 2.dp val dp5 = 5.dp val dp4 = 4.dp val dp8 = 8.dp val dp10 = 10.dp val dp20 = 20.dp val sp8 = 8.sp val sp10 = 10.sp val sp12 = 12.sp val sp16 = 16.sp
3
null
3
8
9c983af26f5bd9cd5e08b7a6080190305738b435
286
WanAndroid
Apache License 2.0
app/src/main/java/com/are/magicboxtwo/data/model/Movie.kt
Andreu35
548,239,119
false
{"Kotlin": 55999}
package com.are.magicboxtwo.data.model import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity data class Movie( @PrimaryKey val id: Int = 0, val imdb_id: String = "", val adult: Boolean = false, val backdrop_path: String? = "", val budget: Int = 0, val genres: List<Genre> = listOf(), val homepage: String = "", val original_language: String = "", val original_title: String = "", val overview: String = "", val popularity: Float = 0.0f, val poster_path: String = "", val release_date: String = "", val revenue: Int = 0, val runtime: Int = 0, val status: String = "", val tagline: String = "", val title: String = "", val video: Boolean = false, val vote_average: Float = 0.0f, val vote_count: Int = 0 ) : Serializable
0
Kotlin
0
0
91bd4ee7be51f0aa1e91a58d459835b5eebe069d
848
MagicBox2
Apache License 2.0
sdk/src/main/kotlin/io/github/wulkanowy/sdk/mapper/HomeworkMapper.kt
wulkanowy
138,756,468
false
{"Kotlin": 705036, "HTML": 70768}
package io.github.wulkanowy.sdk.mapper import io.github.wulkanowy.sdk.pojo.Homework import io.github.wulkanowy.sdk.pojo.HomeworkAttachment import io.github.wulkanowy.sdk.scrapper.homework.Homework as ScrapperHomework internal fun List<ScrapperHomework>.mapHomework() = map { Homework( date = it.date.toLocalDate(), teacher = it.teacher, teacherSymbol = it.teacherSymbol, content = it.content, subject = it.subject, entryDate = it.entryDate.toLocalDate(), attachments = it._attachments.map { (url, name) -> HomeworkAttachment(url, name) }, ) }
11
Kotlin
5
8
340245d8ccc2790dcb75219c2839e8bdd8b448a4
629
sdk
Apache License 2.0
presentation/src/main/java/org/lotka/xenon/presentation/compose/StandardScaffold.kt
armanqanih
860,856,530
false
{"Kotlin": 300166}
package org.lotka.xenon.presentation.compose import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Explore import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material.icons.outlined.Explore import androidx.compose.material.icons.outlined.ShoppingCart import androidx.compose.material.icons.rounded.BorderColor import androidx.compose.material.icons.rounded.Favorite import androidx.compose.material.icons.rounded.FavoriteBorder import androidx.compose.material.icons.rounded.Person import androidx.compose.material3.Badge import androidx.compose.material3.BadgedBox import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationBarItemDefaults import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.navigation.NavController import org.lotka.xenon.domain.util.Constants.SpaceMedium import org.lotka.xenon.domain.util.Constants.SpaceSmall import org.lotka.xenon.presentation.ui.navigation.ScreensNavigation @Composable fun StandardScaffold( navController: NavController, modifier: Modifier = Modifier, showBottomBar: Boolean = true, content: @Composable () -> Unit, ){ val items = listOf( BottomNavItem( title = "Explore", route = ScreensNavigation.ExploreScreen.route, selectedItem = Icons.Filled.Explore, unSelectedItem = Icons.Outlined.Explore, ), BottomNavItem( title = "Cart", route = ScreensNavigation.MyCardScreen.route, selectedItem = Icons.Filled.ShoppingCart, unSelectedItem = Icons.Outlined.ShoppingCart, badgeCount = 2 ), BottomNavItem( title = "WishList", route = ScreensNavigation.WishList.route , selectedItem = Icons.Rounded.Favorite, unSelectedItem = Icons.Rounded.FavoriteBorder, ), BottomNavItem( title = "MyOrder", route = ScreensNavigation.MyOrderScreen.route , selectedItem = Icons.Rounded.BorderColor, unSelectedItem = Icons.Rounded.BorderColor, hasNews = false ), BottomNavItem( title = "Profile", route = ScreensNavigation.Profile.route , selectedItem = Icons.Rounded.Person, unSelectedItem = Icons.Rounded.Person, hasNews = false ), ) var selectedItemIndex by rememberSaveable { mutableStateOf(0) } Surface(modifier = modifier.fillMaxSize()) { Scaffold( bottomBar = { if(showBottomBar){ NavigationBar ( containerColor = MaterialTheme.colors.primary, modifier = Modifier .padding(horizontal = SpaceSmall.dp, vertical =SpaceSmall.dp ) .clip(shape = RoundedCornerShape(SpaceMedium)) .height(75.dp) ){ items.forEachIndexed { index, item -> NavigationBarItem( colors = NavigationBarItemDefaults.colors( indicatorColor = MaterialTheme.colors.primary, ), selected = selectedItemIndex == index, onClick = { selectedItemIndex = index if(navController.currentDestination?.route != item.route){ navController.navigate(item.route) } }, label = { Text(text = item.title, color = MaterialTheme.colors.onBackground, style = MaterialTheme.typography.body2 ) }, alwaysShowLabel = false, icon = { BadgedBox( modifier = Modifier.background( color = MaterialTheme.colors.primary ) ,badge = { if(item.badgeCount != null) { Badge { androidx.compose.material3.Text(text = item.badgeCount.toString()) } } else if(item.hasNews) { Badge() } } ) { Icon( modifier = Modifier.size(28.dp), imageVector = if (index == selectedItemIndex) { item.selectedItem } else item.unSelectedItem, contentDescription = item.title, ) } }, ) } } } } ) { Column(modifier = Modifier.padding(it)) { content() } } } } data class BottomNavItem( val title: String, val route:String, val selectedItem: ImageVector, val unSelectedItem: ImageVector, val hasNews: Boolean = false, val badgeCount: Int? = null )
0
Kotlin
0
0
6b639355540fcc96477726f700c8dee702c99a1d
7,075
ModernNews
Apache License 2.0
ktx-account-annotations/src/main/java/co/windly/ktxaccount/annotation/DefaultBoolean.kt
tommus
220,719,220
false
null
package co.windly.ktxaccount.annotation /** * Indicates a wrapper methods for given Boolean property should be generated. * <p> * One can configure what default value will be used in case if given property was * not set previously, */ @Target(AnnotationTarget.FIELD) annotation class DefaultBoolean( /** * The default value for given Boolean property. * @return the default value for given Boolean property */ val value: Boolean )
1
Kotlin
3
3
f379ee6d1528af6a9eea8ccac01a124e835b0d6e
451
ktx-account
Apache License 2.0
common/src/commonMain/kotlin/io/xorum/codeforceswatcher/network/responses/codeforces/ProblemsResponse.kt
firdausai
351,858,949
true
{"Kotlin": 218135, "Swift": 206959, "Ruby": 2648}
package io.xorum.codeforceswatcher.network.responses.codeforces import io.xorum.codeforceswatcher.features.problems.models.Problem import kotlinx.serialization.Serializable @Serializable data class ProblemsResponse( val status: String, val result: Result ) @Serializable data class Result(val problems: List<Problem>)
0
null
0
0
ada2113b45f4b2d20b7f54f4fd04c7a72599240a
336
codeforces_watcher
MIT License
kotlin/codegen/src/main/java/com/squareup/moshi/kotlin/codegen/metadata.kt
airbnb
154,227,824
true
null
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.moshi.kotlin.codegen import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName import com.squareup.kotlinpoet.metadata.ImmutableKmConstructor import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview import com.squareup.kotlinpoet.metadata.isAbstract import com.squareup.kotlinpoet.metadata.isClass import com.squareup.kotlinpoet.metadata.isEnum import com.squareup.kotlinpoet.metadata.isInner import com.squareup.kotlinpoet.metadata.isInternal import com.squareup.kotlinpoet.metadata.isLocal import com.squareup.kotlinpoet.metadata.isPublic import com.squareup.kotlinpoet.metadata.isSealed import com.squareup.kotlinpoet.metadata.specs.TypeNameAliasTag import com.squareup.kotlinpoet.tag import com.squareup.moshi.Json import com.squareup.moshi.JsonQualifier import com.squareup.moshi.kotlin.codegen.api.DelegateKey import com.squareup.moshi.kotlin.codegen.api.PropertyGenerator import com.squareup.moshi.kotlin.codegen.api.TargetConstructor import com.squareup.moshi.kotlin.codegen.api.TargetParameter import com.squareup.moshi.kotlin.codegen.api.TargetProperty import com.squareup.moshi.kotlin.codegen.api.TargetType import com.squareup.moshi.kotlin.codegen.api.mapTypes import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import java.util.TreeSet import javax.annotation.processing.Messager import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.TypeElement import javax.lang.model.util.Elements import javax.lang.model.util.Types import javax.tools.Diagnostic.Kind.ERROR private val JSON_QUALIFIER = JsonQualifier::class.java private val JSON = Json::class.asClassName() private val OBJECT_CLASS = ClassName("java.lang", "Object") private val VISIBILITY_MODIFIERS = setOf( KModifier.INTERNAL, KModifier.PRIVATE, KModifier.PROTECTED, KModifier.PUBLIC ) private fun Collection<KModifier>.visibility(): KModifier { return find { it in VISIBILITY_MODIFIERS } ?: KModifier.PUBLIC } @KotlinPoetMetadataPreview internal fun primaryConstructor( targetElement: TypeElement, kotlinApi: TypeSpec, elements: Elements, messager: Messager ): TargetConstructor? { val primaryConstructor = kotlinApi.primaryConstructor ?: return null val parameters = LinkedHashMap<String, TargetParameter>() for ((index, parameter) in primaryConstructor.parameters.withIndex()) { val name = parameter.name parameters[name] = TargetParameter( name = name, index = index, type = parameter.type, hasDefault = parameter.defaultValue != null, qualifiers = parameter.annotations.qualifiers(elements), jsonName = parameter.annotations.jsonName() ) } val kmConstructorSignature = primaryConstructor.tag<ImmutableKmConstructor>()?.signature?.toString() ?: run { messager.printMessage(ERROR, "No KmConstructor found for primary constructor.", targetElement) null } return TargetConstructor(parameters, primaryConstructor.modifiers.visibility(), kmConstructorSignature) } /** Returns a target type for `element`, or null if it cannot be used with code gen. */ @KotlinPoetMetadataPreview internal fun targetType(messager: Messager, elements: Elements, types: Types, element: TypeElement, cachedClassInspector: MoshiCachedClassInspector ): TargetType? { val typeMetadata = element.getAnnotation(Metadata::class.java) if (typeMetadata == null) { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must be a Kotlin class", element) return null } val kmClass = try { cachedClassInspector.toImmutableKmClass(typeMetadata) } catch (e: UnsupportedOperationException) { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must be a Class type", element) return null } when { kmClass.isEnum -> { messager.printMessage( ERROR, "@JsonClass with 'generateAdapter = \"true\"' can't be applied to $element: code gen for enums is not supported or necessary", element) return null } !kmClass.isClass -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must be a Kotlin class", element) return null } kmClass.isInner -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must not be an inner class", element) return null } kmClass.isSealed -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must not be sealed", element) return null } kmClass.isAbstract -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must not be abstract", element) return null } kmClass.isLocal -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must not be local", element) return null } !kmClass.isPublic && !kmClass.isInternal -> { messager.printMessage( ERROR, "@JsonClass can't be applied to $element: must be internal or public", element) return null } } val kotlinApi = cachedClassInspector.toTypeSpec(kmClass) val typeVariables = kotlinApi.typeVariables val appliedType = AppliedType.get(element) val constructor = primaryConstructor(element, kotlinApi, elements, messager) if (constructor == null) { messager.printMessage(ERROR, "No primary constructor found on $element", element) return null } if (constructor.visibility != KModifier.INTERNAL && constructor.visibility != KModifier.PUBLIC) { messager.printMessage(ERROR, "@JsonClass can't be applied to $element: " + "primary constructor is not internal or public", element) return null } val properties = mutableMapOf<String, TargetProperty>() val superTypes = appliedType.supertypes(types) .filterNot { supertype -> supertype.element.asClassName() == OBJECT_CLASS || // Don't load properties for java.lang.Object. supertype.element.kind != ElementKind.CLASS // Don't load properties for interface types. } .onEach { supertype -> if (supertype.element.getAnnotation(Metadata::class.java) == null) { messager.printMessage(ERROR, "@JsonClass can't be applied to $element: supertype $supertype is not a Kotlin type", element) return null } } .associateWithTo(LinkedHashMap()) { supertype -> // Load the kotlin API cache into memory eagerly so we can reuse the parsed APIs if (supertype.element == element) { // We've already parsed this api above, reuse it kotlinApi } else { cachedClassInspector.toTypeSpec(supertype.element) } } for (supertypeApi in superTypes.values) { val supertypeProperties = declaredProperties(constructor, supertypeApi) for ((name, property) in supertypeProperties) { properties.putIfAbsent(name, property) } } val visibility = kotlinApi.modifiers.visibility() // If any class in the enclosing class hierarchy is internal, they must all have internal // generated adapters. val resolvedVisibility = if (visibility == KModifier.INTERNAL) { // Our nested type is already internal, no need to search visibility } else { // Implicitly public, so now look up the hierarchy val forceInternal = generateSequence<Element>(element) { it.enclosingElement } .filterIsInstance<TypeElement>() .map { cachedClassInspector.toImmutableKmClass(it.metadata) } .any { it.isInternal } if (forceInternal) KModifier.INTERNAL else visibility } return TargetType( typeName = element.asType().asTypeName(), constructor = constructor, properties = properties, typeVariables = typeVariables, isDataClass = KModifier.DATA in kotlinApi.modifiers, visibility = resolvedVisibility) } /** Returns the properties declared by `typeElement`. */ @KotlinPoetMetadataPreview private fun declaredProperties( constructor: TargetConstructor, kotlinApi: TypeSpec ): Map<String, TargetProperty> { val result = mutableMapOf<String, TargetProperty>() for (initialProperty in kotlinApi.propertySpecs) { val property = initialProperty.toBuilder(type = initialProperty.type.unwrapTypeAlias()).build() val name = property.name val parameter = constructor.parameters[name] result[name] = TargetProperty( propertySpec = property, parameter = parameter, visibility = property.modifiers.visibility(), jsonName = parameter?.jsonName ?: property.annotations.jsonName() ?: name.escapeDollarSigns() ) } return result } private val TargetProperty.isTransient get() = propertySpec.annotations.any { it.className == Transient::class.asClassName() } private val TargetProperty.isSettable get() = propertySpec.mutable || parameter != null private val TargetProperty.isVisible: Boolean get() { return visibility == KModifier.INTERNAL || visibility == KModifier.PROTECTED || visibility == KModifier.PUBLIC } /** * Returns a generator for this property, or null if either there is an error and this property * cannot be used with code gen, or if no codegen is necessary for this property. */ internal fun TargetProperty.generator( messager: Messager, sourceElement: TypeElement, elements: Elements ): PropertyGenerator? { if (isTransient) { if (!hasDefault) { messager.printMessage( ERROR, "No default value for transient property $name", sourceElement) return null } return PropertyGenerator(this, DelegateKey(type, emptyList()), true) } if (!isVisible) { messager.printMessage(ERROR, "property $name is not visible", sourceElement) return null } if (!isSettable) { return null // This property is not settable. Ignore it. } // Merge parameter and property annotations val qualifiers = parameter?.qualifiers.orEmpty() + propertySpec.annotations.qualifiers(elements) for (jsonQualifier in qualifiers) { // Check Java types since that covers both Java and Kotlin annotations. val annotationElement = elements.getTypeElement(jsonQualifier.className.canonicalName) ?: continue annotationElement.getAnnotation(Retention::class.java)?.let { if (it.value != RetentionPolicy.RUNTIME) { messager.printMessage(ERROR, "JsonQualifier @${jsonQualifier.className.simpleName} must have RUNTIME retention") } } annotationElement.getAnnotation(Target::class.java)?.let { if (ElementType.FIELD !in it.value) { messager.printMessage(ERROR, "JsonQualifier @${jsonQualifier.className.simpleName} must support FIELD target") } } } val jsonQualifierSpecs = qualifiers.map { it.toBuilder() .useSiteTarget(AnnotationSpec.UseSiteTarget.FIELD) .build() } return PropertyGenerator(this, DelegateKey(type, jsonQualifierSpecs)) } private fun List<AnnotationSpec>?.qualifiers(elements: Elements): Set<AnnotationSpec> { if (this == null) return setOf() return filterTo(mutableSetOf()) { elements.getTypeElement(it.className.toString()).getAnnotation(JSON_QUALIFIER) != null } } private fun List<AnnotationSpec>?.jsonName(): String? { if (this == null) return null return find { it.className == JSON }?.let { annotation -> val mirror = requireNotNull(annotation.tag<AnnotationMirror>()) { "Could not get the annotation mirror from the annotation spec" } mirror.elementValues.entries.single { it.key.simpleName.contentEquals("name") }.value.value as String } } private fun String.escapeDollarSigns(): String { return replace("\$", "\${\'\$\'}") } internal fun TypeName.unwrapTypeAlias(): TypeName { return mapTypes<ClassName> { tag<TypeNameAliasTag>()?.type?.let { unwrappedType -> // If any type is nullable, then the whole thing is nullable var isAnyNullable = isNullable // Keep track of all annotations across type levels. Sort them too for consistency. val runningAnnotations = TreeSet<AnnotationSpec>(compareBy { it.toString() }).apply { addAll(annotations) } val nestedUnwrappedType = unwrappedType.unwrapTypeAlias() runningAnnotations.addAll(nestedUnwrappedType.annotations) isAnyNullable = isAnyNullable || nestedUnwrappedType.isNullable nestedUnwrappedType.copy(nullable = isAnyNullable, annotations = runningAnnotations.toList()) } } } internal val TypeElement.metadata: Metadata get() { return getAnnotation(Metadata::class.java) ?: throw IllegalStateException("Not a kotlin type! $this") }
0
Java
7
9
b287596c609e1e6535a3ca3d82acb24ea3b3ff65
13,929
moshi
Apache License 2.0
app/src/main/java/com/emirk/appterndeezer/data/remote/dto/album_detail/ArtistX.kt
emirkarabey
637,855,049
false
null
package com.emirk.appterndeezer.data.remote.dto.album_detail import com.google.gson.annotations.SerializedName data class ArtistX( @SerializedName("id") val id: Int, @SerializedName("name") val name: String, @SerializedName("tracklist") val tracklist: String, @SerializedName("type") val type: String )
0
Kotlin
0
0
a165b212489bd7efacb356001e8d246422acdd2b
336
AppTernDeezer
Apache License 2.0
app/src/main/java/com/nagopy/android/aplin/ui/main/MainActivity.kt
75py
43,955,994
false
{"Kotlin": 92163}
package com.nagopy.android.aplin.ui.main import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.collectAsState import com.nagopy.android.aplin.domain.model.PackageModel import com.nagopy.android.aplin.ui.ads.AdsViewModel import com.nagopy.android.aplin.ui.main.compose.RootScreen import org.koin.androidx.viewmodel.ext.android.viewModel class MainActivity : ComponentActivity() { private val mainViewModel: MainViewModel by viewModel() private val adsViewModel: AdsViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val state = mainViewModel.viewModelState.collectAsState().value RootScreen( state = state, mainViewModel = mainViewModel, startDetailSettingsActivity = { pkg: String -> mainViewModel.startDetailSettingsActivity( this@MainActivity, pkg ) }, searchByWeb = { packageModel: PackageModel -> mainViewModel.searchByWeb(this@MainActivity, packageModel) }, sharePackages = { packages -> mainViewModel.sharePackages(this@MainActivity, packages) }, startOssLicensesActivity = { mainViewModel.startOssLicensesActivity(this) }, adsStatus = adsViewModel.adsState.collectAsState().value, isGDPR = adsViewModel.isGDPRState.collectAsState().value, showConsentForm = { adsViewModel.loadForm(this, force = true) }, updateAds = adsViewModel::updateAds, ) } adsViewModel.init(this) } override fun onRestart() { super.onRestart() mainViewModel.updatePackages() } }
5
Kotlin
4
27
c98651d6b6fe44c610c59fa479614e0512651e9b
2,046
Aplin
Apache License 2.0
app/src/main/java/org/stepik/android/view/achievement/ui/resolver/AchievementResourceResolver.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.view.achievement.ui.resolver import android.content.Context import org.stepic.droid.R import org.stepic.droid.di.AppSingleton import org.stepik.android.domain.achievement.model.AchievementItem import org.stepic.droid.util.liftM2 import javax.inject.Inject @AppSingleton class AchievementResourceResolver @Inject constructor( private val context: Context ) { companion object { private const val KIND_STEPS_SOLVED = "steps_solved" private const val KIND_STEPS_SOLVED_STREAK = "steps_solved_streak" private const val KIND_STEPS_SOLVED_CHOICE = "steps_solved_choice" private const val KIND_STEPS_SOLVED_CODE = "steps_solved_code" private const val KIND_STEPS_SOLVED_NUMBER = "steps_solved_number" private const val KIND_CODE_QUIZZES_SOLVED_PYTHON = "code_quizzes_solved_python" private const val KIND_CODE_QUIZZES_SOLVED_CPP = "code_quizzes_solved_cpp" private const val KIND_CODE_QUIZZES_SOLVED_JAVA = "code_quizzes_solved_java" private const val KIND_ACTIVE_DAYS_STREAK = "active_days_streak" private const val KIND_CERTIFICATES_REGULAR_COUNT = "certificates_regular_count" private const val KIND_CERTIFICATES_DISTINCTION_COUNT = "certificates_distinction_count" private const val KIND_COURSE_REVIEWS_COUNT = "course_reviews_count" } private val kindToTitleResId = mapOf( KIND_STEPS_SOLVED to R.string.achievement_steps_solved_title, KIND_STEPS_SOLVED_STREAK to R.string.achievement_steps_solved_streak_title, KIND_STEPS_SOLVED_CHOICE to R.string.achievement_steps_solved_choice_title, KIND_STEPS_SOLVED_CODE to R.string.achievement_steps_solved_code_title, KIND_STEPS_SOLVED_NUMBER to R.string.achievement_steps_solved_number_title, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.string.achievement_code_quizzes_solved_python_title, KIND_CODE_QUIZZES_SOLVED_CPP to R.string.achievement_code_quizzes_solved_cpp_title, KIND_CODE_QUIZZES_SOLVED_JAVA to R.string.achievement_code_quizzes_solved_java_title, KIND_ACTIVE_DAYS_STREAK to R.string.achievement_active_days_streak_title, KIND_CERTIFICATES_REGULAR_COUNT to R.string.achievement_certificates_regular_count_title, KIND_CERTIFICATES_DISTINCTION_COUNT to R.string.achievement_certificates_distinction_count_title, KIND_COURSE_REVIEWS_COUNT to R.string.achievement_course_reviews_count_title ) private val kindToDescriptionResID = mapOf( KIND_STEPS_SOLVED to R.string.achievement_steps_solved_description, KIND_STEPS_SOLVED_STREAK to R.string.achievement_steps_solved_streak_description, KIND_STEPS_SOLVED_CHOICE to R.string.achievement_steps_solved_choice_description, KIND_STEPS_SOLVED_CODE to R.string.achievement_steps_solved_code_description, KIND_STEPS_SOLVED_NUMBER to R.string.achievement_steps_solved_number_description, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.string.achievement_code_quizzes_solved_python_description, KIND_CODE_QUIZZES_SOLVED_CPP to R.string.achievement_code_quizzes_solved_cpp_description, KIND_CODE_QUIZZES_SOLVED_JAVA to R.string.achievement_code_quizzes_solved_java_description, KIND_ACTIVE_DAYS_STREAK to R.string.achievement_active_days_streak_description, KIND_CERTIFICATES_REGULAR_COUNT to R.string.achievement_certificates_regular_count_description, KIND_CERTIFICATES_DISTINCTION_COUNT to R.string.achievement_certificates_distinction_count_description, KIND_COURSE_REVIEWS_COUNT to R.string.achievement_course_reviews_count_description ) private val kindToPluralResID = mapOf( KIND_STEPS_SOLVED to R.plurals.task, KIND_STEPS_SOLVED_STREAK to R.plurals.task, KIND_STEPS_SOLVED_CHOICE to R.plurals.task, KIND_STEPS_SOLVED_CODE to R.plurals.task, KIND_STEPS_SOLVED_NUMBER to R.plurals.task, KIND_CODE_QUIZZES_SOLVED_PYTHON to R.plurals.problem, KIND_CODE_QUIZZES_SOLVED_CPP to R.plurals.problem, KIND_CODE_QUIZZES_SOLVED_JAVA to R.plurals.problem, KIND_ACTIVE_DAYS_STREAK to R.plurals.day, KIND_CERTIFICATES_REGULAR_COUNT to R.plurals.certificate, KIND_CERTIFICATES_DISTINCTION_COUNT to R.plurals.certificate, KIND_COURSE_REVIEWS_COUNT to R.plurals.course_review ) fun resolveTitleForKind(kind: String): String = context.getString(kindToTitleResId[kind] ?: R.string.achievement_unknown_title) fun resolveDescription(achievementItem: AchievementItem): String = kindToPluralResID[achievementItem.kind].liftM2(kindToDescriptionResID[achievementItem.kind]) { plural, description -> context.getString(description, context.resources.getQuantityString(plural, achievementItem.targetScore, achievementItem.targetScore)) } ?: context.getString(R.string.achievement_unknown_description) fun resolveAchievementIcon(achievementItem: AchievementItem, size: Int): String = when { achievementItem.isLocked || achievementItem.currentLevel == 0 -> "file:///android_asset/images/vector/achievements/ic_empty_achievement.svg" achievementItem.uploadcareUUID != null -> "https://ucarecdn.com/${achievementItem.uploadcareUUID}/-/resize/${size}x$size/" else -> "file:///android_asset/images/vector/achievements/${achievementItem.kind}/${achievementItem.currentLevel}.svg" } }
13
null
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
5,673
stepik-android
Apache License 2.0
app/src/main/java/com/taitascioredev/android/tvseriesdemo/dagger/searchtvshows/SearchTvShowsModule.kt
phanghos
119,651,014
false
null
package com.taitascioredev.android.tvseriesdemo.dagger.searchtvshows import com.taitascioredev.android.tvseriesdemo.dagger.DataModule import com.taitascioredev.android.tvseriesdemo.dagger.FragmentScope import com.taitascioredev.android.tvseriesdemo.data.repository.MovieRepository import com.taitascioredev.android.tvseriesdemo.feature.searchtvshows.SearchTvShowsActionProcessor import com.taitascioredev.android.tvseriesdemo.feature.searchtvshows.SearchTvShowsStateReducer import com.taitascioredev.android.tvseriesdemo.feature.searchtvshows.usecase.SearchTvShowsUseCase import com.taitascioredev.android.tvseriesdemo.feature.searchtvshows.usecase.impl.SearchTvShowsUseCaseImpl import com.taitascioredev.android.tvseriesdemo.feature.searchtvshows.viewmodel.SearchTvShowsViewModelFactory import dagger.Module import dagger.Provides /** * Created by rrtatasciore on 30/01/18. */ @Module(includes = [DataModule::class, SearchTvShowsAbstractModule::class]) class SearchTvShowsModule { @Provides @FragmentScope fun provideSearchTvShowsViewModelFactory(actionProcessor: SearchTvShowsActionProcessor, stateReducer: SearchTvShowsStateReducer): SearchTvShowsViewModelFactory { return SearchTvShowsViewModelFactory(actionProcessor, stateReducer) } @Provides @FragmentScope fun provideSearchTvShowsActionProcessor(useCase: SearchTvShowsUseCase): SearchTvShowsActionProcessor { return SearchTvShowsActionProcessor(useCase) } @Provides @FragmentScope fun provideSearchTvShowsStateReducer(): SearchTvShowsStateReducer { return SearchTvShowsStateReducer() } @Provides @FragmentScope fun provideSearchTvShowsUseCaseImpl(repository: MovieRepository): SearchTvShowsUseCaseImpl { return SearchTvShowsUseCaseImpl(repository) } }
0
Kotlin
0
1
f2992ac104f0733d0707027e1c025d1f3ed6bf85
1,797
tv-series-demo
MIT License
foosball/app/src/phone/java/com/instructure/androidfoosball/models/User.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2016 - present Instructure, Inc. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.instructure.androidfoosball.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize class User( var id: String = "", var name: String = "", var email: String = "", var avatar: String = "", var wins: Int = 0, var losses: Int = 0 ) : Parcelable
2
Kotlin
85
99
1bac9958504306c03960bdce7fbb87cc63bc6845
961
canvas-android
Apache License 2.0
core/src/com/mygdx/game/widgets/InventoryObserver.kt
apiorno
263,664,301
false
{"Gradle": 5, "INI": 2, "Shell": 1, "Text": 5, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 83, "XML": 11, "JSON": 29, "Java": 1}
package com.mygdx.game.widgets interface InventoryObserver { enum class InventoryEvent { UPDATED_AP, UPDATED_DP, ITEM_CONSUMED, ADD_WAND_AP, REMOVE_WAND_AP, NONE } fun onNotify(value: String, event: InventoryEvent) }
1
null
1
1
f721d6bc5d11a2fea9f932b94214deccfe1505b2
238
RpgTest
MIT License
feature/settings/src/main/java/com/google/jetpackcamera/settings/SettingsScreen.kt
google
591,101,391
false
{"Kotlin": 414064, "Shell": 724}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jetpackcamera.settings import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.hilt.navigation.compose.hiltViewModel import com.google.jetpackcamera.settings.model.AspectRatio import com.google.jetpackcamera.settings.model.CaptureMode import com.google.jetpackcamera.settings.model.DEFAULT_CAMERA_APP_SETTINGS import com.google.jetpackcamera.settings.model.DarkMode import com.google.jetpackcamera.settings.model.FlashMode import com.google.jetpackcamera.settings.model.LensFacing import com.google.jetpackcamera.settings.model.Stabilization import com.google.jetpackcamera.settings.model.TYPICAL_SYSTEM_CONSTRAINTS import com.google.jetpackcamera.settings.ui.AspectRatioSetting import com.google.jetpackcamera.settings.ui.CaptureModeSetting import com.google.jetpackcamera.settings.ui.DarkModeSetting import com.google.jetpackcamera.settings.ui.DefaultCameraFacing import com.google.jetpackcamera.settings.ui.FlashModeSetting import com.google.jetpackcamera.settings.ui.SectionHeader import com.google.jetpackcamera.settings.ui.SettingsPageHeader import com.google.jetpackcamera.settings.ui.StabilizationSetting import com.google.jetpackcamera.settings.ui.TargetFpsSetting import com.google.jetpackcamera.settings.ui.VersionInfo import com.google.jetpackcamera.settings.ui.theme.SettingsPreviewTheme /** * Screen used for the Settings feature. */ @Composable fun SettingsScreen( versionInfo: VersionInfoHolder, viewModel: SettingsViewModel = hiltViewModel(), onNavigateBack: () -> Unit ) { val settingsUiState by viewModel.settingsUiState.collectAsState() SettingsScreen( uiState = settingsUiState, versionInfo = versionInfo, onNavigateBack = onNavigateBack, setDefaultLensFacing = viewModel::setDefaultLensFacing, setFlashMode = viewModel::setFlashMode, setTargetFrameRate = viewModel::setTargetFrameRate, setAspectRatio = viewModel::setAspectRatio, setCaptureMode = viewModel::setCaptureMode, setVideoStabilization = viewModel::setVideoStabilization, setPreviewStabilization = viewModel::setPreviewStabilization, setDarkMode = viewModel::setDarkMode ) } @Composable private fun SettingsScreen( uiState: SettingsUiState, versionInfo: VersionInfoHolder, onNavigateBack: () -> Unit = {}, setDefaultLensFacing: (LensFacing) -> Unit = {}, setFlashMode: (FlashMode) -> Unit = {}, setTargetFrameRate: (Int) -> Unit = {}, setAspectRatio: (AspectRatio) -> Unit = {}, setCaptureMode: (CaptureMode) -> Unit = {}, setVideoStabilization: (Stabilization) -> Unit = {}, setPreviewStabilization: (Stabilization) -> Unit = {}, setDarkMode: (DarkMode) -> Unit = {} ) { Column( modifier = Modifier .verticalScroll(rememberScrollState()) .background(color = MaterialTheme.colorScheme.background) ) { SettingsPageHeader( title = stringResource(id = R.string.settings_title), navBack = onNavigateBack ) if (uiState is SettingsUiState.Enabled) { SettingsList( uiState = uiState, versionInfo = versionInfo, setDefaultLensFacing = setDefaultLensFacing, setFlashMode = setFlashMode, setTargetFrameRate = setTargetFrameRate, setAspectRatio = setAspectRatio, setCaptureMode = setCaptureMode, setVideoStabilization = setVideoStabilization, setPreviewStabilization = setPreviewStabilization, setDarkMode = setDarkMode ) } } } @Composable fun SettingsList( uiState: SettingsUiState.Enabled, versionInfo: VersionInfoHolder, setDefaultLensFacing: (LensFacing) -> Unit = {}, setFlashMode: (FlashMode) -> Unit = {}, setTargetFrameRate: (Int) -> Unit = {}, setAspectRatio: (AspectRatio) -> Unit = {}, setCaptureMode: (CaptureMode) -> Unit = {}, setVideoStabilization: (Stabilization) -> Unit = {}, setPreviewStabilization: (Stabilization) -> Unit = {}, setDarkMode: (DarkMode) -> Unit = {} ) { SectionHeader(title = stringResource(id = R.string.section_title_camera_settings)) DefaultCameraFacing( settingValue = (uiState.cameraAppSettings.cameraLensFacing == LensFacing.FRONT), enabled = with(uiState.systemConstraints.availableLenses) { size > 1 && contains(LensFacing.FRONT) }, setDefaultLensFacing = setDefaultLensFacing ) FlashModeSetting( currentFlashMode = uiState.cameraAppSettings.flashMode, setFlashMode = setFlashMode ) TargetFpsSetting( currentTargetFps = uiState.cameraAppSettings.targetFrameRate, supportedFps = uiState.systemConstraints.perLensConstraints.values.fold(emptySet()) { union, constraints -> union + constraints.supportedFixedFrameRates }, setTargetFps = setTargetFrameRate ) AspectRatioSetting( currentAspectRatio = uiState.cameraAppSettings.aspectRatio, setAspectRatio = setAspectRatio ) CaptureModeSetting( currentCaptureMode = uiState.cameraAppSettings.captureMode, setCaptureMode = setCaptureMode ) StabilizationSetting( currentVideoStabilization = uiState.cameraAppSettings.videoCaptureStabilization, currentPreviewStabilization = uiState.cameraAppSettings.previewStabilization, currentTargetFps = uiState.cameraAppSettings.targetFrameRate, supportedStabilizationMode = uiState.systemConstraints.perLensConstraints.values.fold( emptySet() ) { union, constraints -> union + constraints.supportedStabilizationModes }, setVideoStabilization = setVideoStabilization, setPreviewStabilization = setPreviewStabilization ) SectionHeader(title = stringResource(id = R.string.section_title_app_settings)) DarkModeSetting( currentDarkMode = uiState.cameraAppSettings.darkMode, setDarkMode = setDarkMode ) SectionHeader(title = stringResource(id = R.string.section_title_software_info)) VersionInfo( versionName = versionInfo.versionName, buildType = versionInfo.buildType ) } data class VersionInfoHolder( val versionName: String, val buildType: String ) @Preview(name = "Light Mode") @Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun Preview_SettingsScreen() { SettingsPreviewTheme { SettingsScreen( uiState = SettingsUiState.Enabled( DEFAULT_CAMERA_APP_SETTINGS, TYPICAL_SYSTEM_CONSTRAINTS ), versionInfo = VersionInfoHolder( versionName = "1.0.0", buildType = "release" ) ) } }
47
Kotlin
23
96
4005d59356a80cd2d2e2b6056120f8646017361e
8,074
jetpack-camera-app
Apache License 2.0
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/ic/IncrementalCache.kt
vmichalak
364,875,385
true
{"Kotlin": 69686329, "Java": 7040677, "Swift": 4240529, "C": 2633594, "C++": 2415282, "Objective-C": 580704, "JavaScript": 209639, "Objective-C++": 165277, "Groovy": 103211, "Python": 43460, "Shell": 31275, "TypeScript": 22854, "Lex": 18369, "Batchfile": 11692, "CSS": 11259, "EJS": 5241, "Ruby": 4878, "HTML": 4793, "CMake": 4448, "Dockerfile": 2787, "Pascal": 1698, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ir.backend.js.ic import org.jetbrains.kotlin.backend.common.serialization.IdSignatureDeserializer import org.jetbrains.kotlin.ir.util.IdSignature import org.jetbrains.kotlin.protobuf.CodedInputStream import org.jetbrains.kotlin.protobuf.CodedOutputStream import org.jetbrains.kotlin.utils.addToStdlib.ifTrue import java.io.File internal class IncrementalCache(private val library: KotlinLibraryHeader, val cacheDir: File) { companion object { private const val CACHE_HEADER = "ic.header.bin" private const val BINARY_AST_SUFFIX = "ast.bin" private const val METADATA_SUFFIX = "metadata.bin" private const val METADATA_TMP_SUFFIX = "metadata.tmp.bin" } private val cacheHeaderFile = File(cacheDir, CACHE_HEADER) private var cacheHeaderShouldBeUpdated = false private var removedSrcFiles: Collection<KotlinSourceFile> = emptyList() private val kotlinLibrarySourceFileMetadata = hashMapOf<KotlinSourceFile, KotlinSourceFileMetadata>() private val signatureToIndexMappingFromMetadata = hashMapOf<KotlinSourceFile, MutableMap<IdSignature, Int>>() private val cacheHeaderFromDisk by lazy { cacheHeaderFile.useCodedInputIfExists { CacheHeader.fromProtoStream(this, library.libraryFingerprint) } } val libraryFileFromHeader by lazy { cacheHeaderFromDisk?.libraryFile } private class CacheHeader( val libraryFile: KotlinLibraryFile, private val libraryFingerprint: ICHash?, val sourceFileFingerprints: Map<KotlinSourceFile, ICHash>? ) { constructor(library: KotlinLibraryHeader) : this(library.libraryFile, library.libraryFingerprint, library.sourceFileFingerprints) fun toProtoStream(out: CodedOutputStream) { libraryFile.toProtoStream(out) libraryFingerprint?.toProtoStream(out) ?: notFoundIcError("library fingerprint", libraryFile) sourceFileFingerprints?.let { fingerprints -> out.writeInt32NoTag(fingerprints.size) for ((srcFile, fingerprint) in fingerprints) { srcFile.toProtoStream(out) fingerprint.toProtoStream(out) } } ?: notFoundIcError("source file fingerprints", libraryFile) } companion object { fun fromProtoStream(input: CodedInputStream, newLibraryFingerprint: ICHash?): CacheHeader { val libraryFile = KotlinLibraryFile.fromProtoStream(input) val oldLibraryFingerprint = ICHash.fromProtoStream(input) val sourceFileFingerprints = (oldLibraryFingerprint != newLibraryFingerprint).ifTrue { buildMapUntil(input.readInt32()) { val file = KotlinSourceFile.fromProtoStream(input) put(file, ICHash.fromProtoStream(input)) } } return CacheHeader(libraryFile, oldLibraryFingerprint, sourceFileFingerprints) } } } private class KotlinSourceFileMetadataFromDisk( override val inverseDependencies: KotlinSourceFileMap<Set<IdSignature>>, override val directDependencies: KotlinSourceFileMap<Map<IdSignature, ICHash>>, ) : KotlinSourceFileMetadata() private fun KotlinSourceFile.getCacheFile(suffix: String) = File(cacheDir, "${File(path).name}.${path.stringHashForIC()}.$suffix") fun buildIncrementalCacheArtifact(signatureToIndexMapping: Map<KotlinSourceFile, Map<IdSignature, Int>>): IncrementalCacheArtifact { if (cacheHeaderShouldBeUpdated) { cacheHeaderFile.useCodedOutput { CacheHeader(library).toProtoStream(this) } } for (removedFile in removedSrcFiles) { removedFile.getCacheFile(BINARY_AST_SUFFIX).delete() removedFile.getCacheFile(METADATA_SUFFIX).delete() } val fileArtifacts = library.sourceFileFingerprints.keys.map { srcFile -> commitSourceFileMetadata(srcFile.getCacheFile(BINARY_AST_SUFFIX), srcFile, signatureToIndexMapping[srcFile] ?: emptyMap()) } return IncrementalCacheArtifact(cacheDir, removedSrcFiles.isNotEmpty(), fileArtifacts, library.jsOutputName) } data class ModifiedFiles( val addedFiles: List<KotlinSourceFile> = emptyList(), val removedFiles: Map<KotlinSourceFile, KotlinSourceFileMetadata> = emptyMap(), val modifiedFiles: Map<KotlinSourceFile, KotlinSourceFileMetadata> = emptyMap(), val nonModifiedFiles: List<KotlinSourceFile> = emptyList() ) fun collectModifiedFiles(): ModifiedFiles { val cachedFingerprints = cacheHeaderFromDisk?.let { it.sourceFileFingerprints ?: return ModifiedFiles() } ?: emptyMap() val addedFiles = mutableListOf<KotlinSourceFile>() val modifiedFiles = hashMapOf<KotlinSourceFile, KotlinSourceFileMetadata>() val nonModifiedFiles = mutableListOf<KotlinSourceFile>() for ((file, fileNewFingerprint) in library.sourceFileFingerprints) { when (cachedFingerprints[file]) { fileNewFingerprint -> nonModifiedFiles.add(file) null -> addedFiles.add(file) else -> modifiedFiles[file] = fetchSourceFileMetadata(file, false) } } val removedFiles = (cachedFingerprints.keys - library.sourceFileFingerprints.keys).associateWith { fetchSourceFileMetadata(it, false) } removedSrcFiles = removedFiles.keys cacheHeaderShouldBeUpdated = true return ModifiedFiles(addedFiles, removedFiles, modifiedFiles, nonModifiedFiles) } fun fetchSourceFileFullMetadata(srcFile: KotlinSourceFile): KotlinSourceFileMetadata { return fetchSourceFileMetadata(srcFile, true) } fun updateSourceFileMetadata(srcFile: KotlinSourceFile, sourceFileMetadata: KotlinSourceFileMetadata) { kotlinLibrarySourceFileMetadata[srcFile] = sourceFileMetadata } private fun fetchSourceFileMetadata(srcFile: KotlinSourceFile, loadSignatures: Boolean) = kotlinLibrarySourceFileMetadata.getOrPut(srcFile) { val signatureToIndexMapping = signatureToIndexMappingFromMetadata.getOrPut(srcFile) { hashMapOf() } val deserializer: IdSignatureDeserializer by lazy { library.sourceFileDeserializers[srcFile] ?: notFoundIcError("signature deserializer", library.libraryFile, srcFile) } fun CodedInputStream.deserializeIdSignatureAndSave() = readIdSignature { index -> val signature = deserializer.deserializeIdSignature(index) signatureToIndexMapping[signature] = index signature } fun <T> CodedInputStream.readDependencies(signaturesReader: () -> T) = buildMapUntil(readInt32()) { val libFile = KotlinLibraryFile.fromProtoStream(this@readDependencies) val depends = buildMapUntil(readInt32()) { val dependencySrcFile = KotlinSourceFile.fromProtoStream(this@readDependencies) put(dependencySrcFile, signaturesReader()) } put(libFile, depends) } fun CodedInputStream.readDirectDependencies() = readDependencies { if (loadSignatures) { buildMapUntil(readInt32()) { val signature = deserializeIdSignatureAndSave() put(signature, ICHash.fromProtoStream(this@readDirectDependencies)) } } else { repeat(readInt32()) { skipIdSignature() ICHash.fromProtoStream(this@readDirectDependencies) } emptyMap() } } fun CodedInputStream.readInverseDependencies() = readDependencies { if (loadSignatures) { buildSetUntil(readInt32()) { add(deserializeIdSignatureAndSave()) } } else { repeat(readInt32()) { skipIdSignature() } emptySet() } } srcFile.getCacheFile(METADATA_SUFFIX).useCodedInputIfExists { val directDependencies = KotlinSourceFileMap(readDirectDependencies()) val reverseDependencies = KotlinSourceFileMap(readInverseDependencies()) KotlinSourceFileMetadataFromDisk(reverseDependencies, directDependencies) } ?: KotlinSourceFileMetadataNotExist } private fun commitSourceFileMetadata( binaryAstFile: File, srcFile: KotlinSourceFile, signatureToIndexMapping: Map<IdSignature, Int> ): SourceFileCacheArtifact { val headerCacheFile = srcFile.getCacheFile(METADATA_SUFFIX) val sourceFileMetadata = kotlinLibrarySourceFileMetadata[srcFile] ?: return SourceFileCacheArtifact.DoNotChangeMetadata(srcFile, binaryAstFile) if (sourceFileMetadata.isEmpty()) { return SourceFileCacheArtifact.RemoveMetadata(srcFile, binaryAstFile, headerCacheFile) } if (sourceFileMetadata is KotlinSourceFileMetadataFromDisk) { return SourceFileCacheArtifact.DoNotChangeMetadata(srcFile, binaryAstFile) } val signatureToIndexMappingSaved = signatureToIndexMappingFromMetadata[srcFile] ?: emptyMap() fun CodedOutputStream.serializeIdSignature(signature: IdSignature) = writeIdSignature(signature) { signatureToIndexMapping[it] ?: signatureToIndexMappingSaved[it] } fun <T> CodedOutputStream.writeDependencies(depends: KotlinSourceFileMap<T>, signaturesWriter: (T) -> Unit) { writeInt32NoTag(depends.size) for ((dependencyLibFile, dependencySrcFiles) in depends) { dependencyLibFile.toProtoStream(this) writeInt32NoTag(dependencySrcFiles.size) for ((dependencySrcFile, signatures) in dependencySrcFiles) { dependencySrcFile.toProtoStream(this) signaturesWriter(signatures) } } } fun CodedOutputStream.writeDirectDependencies(depends: KotlinSourceFileMap<Map<IdSignature, ICHash>>) = writeDependencies(depends) { writeInt32NoTag(it.size) for ((signature, hash) in it) { serializeIdSignature(signature) hash.toProtoStream(this) } } fun CodedOutputStream.writeInverseDependencies(depends: KotlinSourceFileMap<Set<IdSignature>>) = writeDependencies(depends) { writeInt32NoTag(it.size) for (signature in it) { serializeIdSignature(signature) } } val tmpCacheFile = srcFile.getCacheFile(METADATA_TMP_SUFFIX) tmpCacheFile.useCodedOutput { writeDirectDependencies(sourceFileMetadata.directDependencies) writeInverseDependencies(sourceFileMetadata.inverseDependencies) } return SourceFileCacheArtifact.CommitMetadata(srcFile, binaryAstFile, headerCacheFile, tmpCacheFile) } }
7
Kotlin
1
1
6614714c9465ed122ad8f36b6e8149dbcfcd41bb
11,461
kotlin
Apache License 2.0
app/src/main/java/com/kemalatli/techchallenge/base/di/AppModule.kt
kemalatli
209,587,874
false
null
package com.kemalatli.techchallenge.base.di import com.kemalatli.techchallenge.data.LoginRepositoryImpl import com.kemalatli.techchallenge.data.OrdersRepositoryImpl import com.kemalatli.techchallenge.data.TechPrefs import com.kemalatli.techchallenge.domain.LoginRepository import com.kemalatli.techchallenge.domain.OrdersRepository import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit val appModule = module{ // OkHttp Client single { OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .readTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES) .callTimeout(1, TimeUnit.MINUTES) .connectTimeout(1, TimeUnit.MINUTES) .build() } // Retrofit single { Retrofit.Builder() .baseUrl("http://kariyertechchallenge.mockable.io/") .addConverterFactory(GsonConverterFactory.create()) .client(get()) .addCallAdapterFactory((RxJava2CallAdapterFactory.create())) .build() } // Shared preferences to persist login state single { TechPrefs(androidContext()) } // Login repository single<LoginRepository> { LoginRepositoryImpl(get()) } // Order repository single<OrdersRepository> { OrdersRepositoryImpl(get()) } }
0
Kotlin
0
0
03ea28d2a1f7e7832fa4e32bd0a038591e0b2c5d
1,640
TechChallenge
MIT License
src/app/src/test/kotlin/org/vaccineimpact/orderlyweb/tests/database_tests/SettingsRepositoryTests.kt
vimc
173,126,600
false
null
package org.vaccineimpact.orderlyweb.tests.database_tests import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.vaccineimpact.orderlyweb.db.JooqContext import org.vaccineimpact.orderlyweb.db.Tables import org.vaccineimpact.orderlyweb.db.repositories.OrderlySettingsRepository import org.vaccineimpact.orderlyweb.test_helpers.CleanDatabaseTests import org.vaccineimpact.orderlyweb.db.Tables.ORDERLYWEB_SETTINGS class SettingsRepositoryTests : CleanDatabaseTests() { @BeforeEach fun addDefaultSettings() { //Settings table has been cleaned by base class JooqContext().use { it.dsl.insertInto(ORDERLYWEB_SETTINGS) .set(ORDERLYWEB_SETTINGS.AUTH_ALLOW_GUEST, false) .execute() } } @Test fun `can get auth allow guest`() { val sut = OrderlySettingsRepository() assertThat(sut.getAuthAllowGuest()).isFalse() JooqContext().use { it.dsl.update(Tables.ORDERLYWEB_SETTINGS) .set(ORDERLYWEB_SETTINGS.AUTH_ALLOW_GUEST, true) .execute() } assertThat(sut.getAuthAllowGuest()).isTrue() } @Test fun `can set auth allow guest`() { val sut = OrderlySettingsRepository() sut.setAuthAllowGuest(true) JooqContext().use { val result = it.dsl.select(ORDERLYWEB_SETTINGS.AUTH_ALLOW_GUEST) .from(ORDERLYWEB_SETTINGS) .fetchOne() assertThat(result[ORDERLYWEB_SETTINGS.AUTH_ALLOW_GUEST]).isTrue() } } }
6
Kotlin
4
4
4c18736db6263fe8115699f036ab2469081bfb97
1,675
orderly-web
MIT License
app/src/main/java/com/rodrigolmti/lunch/money/companion/composition/bridge/adapter/HomeFeatureAdapter.kt
Rodrigolmti
737,641,287
false
{"Kotlin": 366824, "Ruby": 351}
package com.rodrigolmti.lunch.money.companion.composition.bridge.adapter import com.rodrigolmti.lunch.money.companion.composition.bridge.mapper.toView import com.rodrigolmti.lunch.money.companion.composition.domain.model.AssetStatus import com.rodrigolmti.lunch.money.companion.composition.domain.model.TransactionModel import com.rodrigolmti.lunch.money.companion.composition.domain.repository.ILunchRepository import com.rodrigolmti.lunch.money.companion.core.DEFAULT_CURRENCY import com.rodrigolmti.lunch.money.companion.core.LunchError import com.rodrigolmti.lunch.money.companion.core.Outcome import com.rodrigolmti.lunch.money.companion.core.getOrElse import com.rodrigolmti.lunch.money.companion.core.mapThrowable import com.rodrigolmti.lunch.money.companion.core.runCatching import com.rodrigolmti.lunch.money.companion.core.utils.formatDate import com.rodrigolmti.lunch.money.companion.features.home.model.AssetOverviewView import com.rodrigolmti.lunch.money.companion.features.home.model.HomeView import com.rodrigolmti.lunch.money.companion.features.home.model.PeriodSummaryView import kotlinx.collections.immutable.toImmutableList import java.util.Date internal class HomeFeatureAdapter( private val lunchRepository: ILunchRepository, ) { suspend fun getAssetOverview( start: Date, end: Date ): Outcome<HomeView, LunchError> { return runCatching { val currency = lunchRepository.getPrimaryCurrency() ?: DEFAULT_CURRENCY val assets = lunchRepository.getAssets() val overviews = assets.groupBy { it.type }.map { (key, value) -> AssetOverviewView( value.sumOf { it.balance }, key.toView(), value.map { asset -> asset.toView() }, ) } val result = lunchRepository.getTransactions(formatDate(start), formatDate(end)) val transactions = result.getOrElse { emptyList() } val (totalIncome, totalExpense) = calculateTotalIncomeAndExpense(transactions) val netIncome = totalIncome - totalExpense val savingsRate = if (totalIncome > 0) (netIncome / totalIncome) * 100 else 0.0 HomeView( overviews = overviews.toImmutableList(), summary = PeriodSummaryView( totalIncome = totalIncome, totalExpense = totalExpense, netIncome = netIncome, savingsRate = savingsRate.toInt(), currency = transactions.firstOrNull()?.currency ?: currency ), pendingAssets = assets.filter { it.status == AssetStatus.RELINK || it.status == AssetStatus.ERROR }.map { it.name }, ) }.mapThrowable { LunchError.EmptyDataError } } private fun calculateTotalIncomeAndExpense(transactions: List<TransactionModel>): Pair<Float, Float> { val totalIncome = transactions.filter { it.isIncome && !it.excludeFromTotals } .sumOf { it.amount.toDouble() }.toFloat() * -1 val totalExpense = transactions.filter { !it.isIncome && !it.excludeFromTotals } .sumOf { it.amount.toDouble() }.toFloat() return totalIncome to totalExpense } }
0
Kotlin
0
4
457be1007ee1a642fab38f84ff6ebcd0ebf98753
3,347
lunch_money_companion
Apache License 2.0
app/src/androidTest/java/com/mreigar/postapp/espresso/CounterIdleResource.kt
mreigosa
267,906,034
false
null
package com.grela.clean import androidx.test.espresso.IdlingResource import com.grela.domain.interactor.IdleNotifier import java.util.concurrent.atomic.AtomicInteger class CounterIdleResource(private val resourceName: String) : IdlingResource, IdleNotifier { private val counter = AtomicInteger(0) private var resourceCallback: IdlingResource.ResourceCallback? = null override fun getName(): String = resourceName override fun isIdleNow(): Boolean = counter.get() == 0 override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback?) { resourceCallback = callback } override fun increment() = counter.getAndIncrement() @Throws(IllegalArgumentException::class) override fun decrement() { val counterValue = counter.decrementAndGet() if (counterValue == 0) { resourceCallback?.onTransitionToIdle() } if (counterValue < 0) { throw IllegalArgumentException("Counter has been corrupted!") } } }
1
Kotlin
0
1
d9b9433d084d791bc8bfe2bee91704d60b0c626e
1,034
post-app-kotlin
MIT License
app/src/main/java/com/wiryadev/bootstrapiconscompose/ui/theme/Color.kt
wiryadev
380,639,096
false
null
package com.wiryadev.bootstrapiconscompose.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFF8F13FE) val Purple500 = Color(0xFF6B10F4) val Purple700 = Color(0xFF5409C3) val Teal200 = Color(0xFF03DAC5)
0
Kotlin
0
2
1c199d953dc96b261aab16ac230dc7f01fb14a53
229
bootstrap-icons-compose
MIT License
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimMotionGroup.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api import com.maddyhome.idea.vim.action.motion.leftright.TillCharacterMotionType import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.handler.Motion interface VimMotionGroup { // Note that the following methods require the caret to access the intended vertical position, such as "end of line" fun getOffsetOfHorizontalMotion(editor: VimEditor, caret: ImmutableVimCaret, count: Int, allowPastEnd: Boolean): Int fun getVerticalMotionOffset(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Motion // TODO: Consider naming. These don't move the caret, but calculate offsets. Also consider returning Motion // Move caret to specific buffer line fun moveCaretToLineStart(editor: VimEditor, line: Int): Int fun moveCaretToLineStartSkipLeading(editor: VimEditor, line: Int): Int fun moveCaretToLineWithStartOfLineOption(editor: VimEditor, line: Int, caret: ImmutableVimCaret): Int fun moveCaretToLineEnd(editor: VimEditor, line: Int, allowPastEnd: Boolean): Int fun moveCaretToLineWithSameColumn(editor: VimEditor, line: Int, caret: ImmutableVimCaret): Int fun moveCaretToLinePercent(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int // Move caret relative to current line fun moveCaretToRelativeLineStartSkipLeading(editor: VimEditor, caret: ImmutableVimCaret, linesOffset: Int): Int fun moveCaretToRelativeLineEnd(editor: VimEditor, caret: ImmutableVimCaret, cntForward: Int, allowPastEnd: Boolean): Int fun moveCaretToRelativeLineEndSkipTrailing(editor: VimEditor, caret: ImmutableVimCaret, linesOffset: Int): Int // Move caret to (IntelliJ visual) line relative to the bounds of the display (aka window) // (This describes what these functions *currently* do, not what they are *supposed* to do) // TODO: These should move to the Vim logical line at the top/bottom/middle of the display fun moveCaretToFirstDisplayLine(editor: VimEditor, caret: ImmutableVimCaret, count: Int, normalizeToScreen: Boolean): Int fun moveCaretToMiddleDisplayLine(editor: VimEditor, caret: ImmutableVimCaret): Int fun moveCaretToLastDisplayLine(editor: VimEditor, caret: ImmutableVimCaret, count: Int, normalizeToScreen: Boolean): Int // Move caret to buffer column fun moveCaretToColumn(editor: VimEditor, caret: ImmutableVimCaret, count: Int, allowEnd: Boolean): Motion // Move caret to buffer column on current line fun moveCaretToCurrentLineStart(editor: VimEditor, caret: ImmutableVimCaret): Int fun moveCaretToCurrentLineStartSkipLeading(editor: VimEditor, caret: ImmutableVimCaret): Int fun moveCaretToCurrentLineEnd(editor: VimEditor, caret: ImmutableVimCaret): Int // Move caret to column relative to the bounds of the display (aka window) fun moveCaretToCurrentDisplayLineStart(editor: VimEditor, caret: ImmutableVimCaret): Motion fun moveCaretToCurrentDisplayLineStartSkipLeading(editor: VimEditor, caret: ImmutableVimCaret): Int fun moveCaretToCurrentDisplayLineMiddle(editor: VimEditor, caret: ImmutableVimCaret): Motion fun moveCaretToCurrentDisplayLineEnd(editor: VimEditor, caret: ImmutableVimCaret, allowEnd: Boolean): Motion // Move caret to other fun moveCaretToMark(caret: ImmutableVimCaret, ch: Char, toLineStart: Boolean): Motion fun moveCaretToJump(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Motion fun moveCaretToMatchingPair(editor: VimEditor, caret: ImmutableVimCaret): Motion /** * Find the offset of the start of the next/previous word/WORD * * @param editor The editor to search in * @param searchFrom The buffer offset to start searching from * @param count The number of words to skip * @param bigWord If true then find WORD, if false then find word * @return a [Motion] representing the offset to move to, or [Motion.Error] if not found */ fun findOffsetOfNextWord(editor: VimEditor, searchFrom: Int, count: Int, bigWord: Boolean): Motion // Next/previous matching character - f/F and t/T motions val lastFTCmd: TillCharacterMotionType val lastFTChar: Char fun setLastFTCmd(lastFTCmd: TillCharacterMotionType, lastChar: Char) /** * Get the offset of the next/previous matching character on the caret's buffer line * * @param editor The editor to search in * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @return the buffer offset to move to, or -1 if not found */ fun moveCaretToNextCharacterOnLine(editor: VimEditor, caret: ImmutableVimCaret, count: Int, ch: Char): Int /** * Get the offset of the character preceding (in direction of travel) the next/previous matching character on the * caret's buffer line * * @param editor The editor to search in * @param caret The caret to be moved * @param count The number of occurrences to move to * @param ch The character to search for * @return the buffer offset to move to, or -1 if not found */ fun moveCaretToBeforeNextCharacterOnLine(editor: VimEditor, caret: ImmutableVimCaret, count: Int, ch: Char): Int fun repeatLastMatchChar(editor: VimEditor, caret: ImmutableVimCaret, count: Int): Int fun getMotionRange(editor: VimEditor, caret: ImmutableVimCaret, context: ExecutionContext, argument: Argument, operatorArguments: OperatorArguments): TextRange? // TODO: These aren't caret motions. Should be moved to VimWindowGroup? fun moveCaretGotoNextTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int fun moveCaretGotoPreviousTab(editor: VimEditor, context: ExecutionContext, rawCount: Int): Int fun onAppCodeMovement(editor: VimEditor, caret: VimCaret, offset: Int, oldOffset: Int) }
9
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
6,067
ideavim
MIT License
rocket-launcher-core/src/main/kotlin/com/github/funczz/rocket_launcher/core/domain/model/launcher/LauncherEvent.kt
funczz
438,511,484
false
{"Kotlin": 67143, "HTML": 2823}
package com.github.funczz.rocket_launcher.core.domain.model.launcher sealed class LauncherEvent { class START(val counter: UInt): LauncherEvent() object DECREMENT: LauncherEvent() object LAUNCH: LauncherEvent() object ABORT: LauncherEvent() object FINISH: LauncherEvent() }
0
Kotlin
0
0
329665a170f96a2c3ed76728104d8297e9553201
300
kotlin-rocket-launcher
Apache License 2.0
kmdc/kmdc-menu/src/jsMain/kotlin/MDCMenuItem.kt
mpetuska
430,798,310
false
null
package dev.petuska.kmdc.menu import androidx.compose.runtime.Composable import dev.petuska.kmdc.core.Builder import dev.petuska.kmdc.core.ComposableBuilder import dev.petuska.kmdc.core.MDCDsl import dev.petuska.kmdc.list.MDCListItem import dev.petuska.kmdc.list.MDCListItemOpts import dev.petuska.kmdc.list.MDCListItemScope import org.jetbrains.compose.web.attributes.AttrsBuilder import org.w3c.dom.HTMLLIElement @MDCDsl @Composable public fun MDCMenuScope.MDCMenuItem( opts: Builder<MDCListItemOpts>? = null, attrs: Builder<AttrsBuilder<HTMLLIElement>>? = null, content: ComposableBuilder<MDCListItemScope<HTMLLIElement>>? = null, ) { MDCListItem(attrs = { attrs?.invoke(this) }, opts = opts, content = content) }
22
Kotlin
8
29
67b31502b5f76b64f7571821fdd0b78a3df0a68c
733
kmdc
Apache License 2.0
navigation/src/commonMain/kotlin/com/amarcolini/joos/trajectory/constraints/AngularAccelVelocityConstraint.kt
amarcolini
424,457,806
false
null
package com.amarcolini.joos.trajectory.constraints import com.amarcolini.joos.geometry.Angle import com.amarcolini.joos.geometry.Pose2d import com.amarcolini.joos.util.epsilonEquals import kotlin.math.max import kotlin.math.min import kotlin.math.pow import kotlin.math.sqrt /** * A velocity constraint that prevents over-accelerating to ensure its corresponding angular and translational acceleration * constraints are satisfied. */ class AngularAccelVelocityConstraint( val maxAngAccel: Angle, val maxTranslationAccel: Double ) : TrajectoryVelocityConstraint { private val aW = maxAngAccel.radians private val aT = maxTranslationAccel override fun get(pose: Pose2d, deriv: Pose2d, lastDeriv: Pose2d, ds: Double, baseRobotVel: Pose2d): Double { val currentCurvature = deriv.heading.radians val lastCurvature = lastDeriv.heading.radians if (currentCurvature == lastCurvature) return Double.POSITIVE_INFINITY // Confused? See http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf#section.B.2 return when { currentCurvature > 0 && lastCurvature >= 0 -> when { currentCurvature > lastCurvature -> sqrt( (2 * ds * (aW + aT * currentCurvature).pow(2)) / ((aT * (currentCurvature + lastCurvature) + 2 * aW) * (currentCurvature - lastCurvature)) ) currentCurvature < lastCurvature -> { val thresh1 = sqrt((8 * currentCurvature * aW * ds) / (currentCurvature + lastCurvature).pow(2)) val tmp1 = sqrt( (4 * currentCurvature * ds * (currentCurvature * aT + aW)) / (lastCurvature - currentCurvature).pow(2) ) val tmp2 = sqrt( (2 * ds * (currentCurvature * aT + aW).pow(2)) / ((lastCurvature - currentCurvature) * (2 * aW + (currentCurvature + lastCurvature) * aT)) ) val threshTmp1 = min(tmp1, tmp2) val threshTmp2 = min(sqrt((2 * aW * ds) / lastCurvature), sqrt(2 * aT * ds)) var threshTmp3 = Double.NEGATIVE_INFINITY val tmp = min( (2 * aW * ds) / lastCurvature, (2 * ds * (currentCurvature * aT - aW).pow(2)) / ((lastCurvature - currentCurvature) * (2 * aW - (lastCurvature + currentCurvature) * aT)) ) if (tmp > (-4 * currentCurvature * ds * (currentCurvature * aT - aW)) / ((lastCurvature - currentCurvature) * (lastCurvature + currentCurvature)) && tmp > 2 * aT * ds) threshTmp3 = sqrt(tmp) max(max(thresh1, threshTmp1), max(threshTmp2, threshTmp3)) } else -> Double.POSITIVE_INFINITY } currentCurvature < 0 && lastCurvature <= 0 -> when { currentCurvature > lastCurvature -> { val thresh1 = sqrt((-8 * currentCurvature * aW * ds) / (currentCurvature + lastCurvature).pow(2)) val tmp1 = sqrt( (-4 * currentCurvature * ds * (aW - currentCurvature * aT)) / ((lastCurvature + currentCurvature) * (lastCurvature - currentCurvature)) ) val tmp2 = sqrt( (-2 * ds * (aW - currentCurvature * aT).pow(2)) / ((lastCurvature - currentCurvature) * (2 * aW - (currentCurvature + lastCurvature) * aT)) ) val threshTmp1 = min(tmp1, tmp2) val threshTmp2 = min(sqrt((-2 * aW * ds) / lastCurvature), sqrt(2 * aT * ds)) var threshTmp3 = Double.NEGATIVE_INFINITY val tmp = min( (-2 * aW * ds) / lastCurvature, (-2 * ds * (aW + currentCurvature * aT).pow(2)) / ((lastCurvature - currentCurvature) * (2 * aW + (lastCurvature + currentCurvature) * aT)) ) if (tmp > (-4 * currentCurvature * ds * (aW + currentCurvature * aT)) / ((lastCurvature - currentCurvature) * (lastCurvature + currentCurvature)) && tmp > 2 * aT * ds) threshTmp3 = sqrt(tmp) max(max(thresh1, threshTmp1), max(threshTmp2, threshTmp3)) } currentCurvature < lastCurvature -> sqrt( (-2 * ds * (aW - aT * currentCurvature).pow(2)) / ((aT * (currentCurvature + lastCurvature) - 2 * aW) * (lastCurvature - currentCurvature)) ) else -> Double.POSITIVE_INFINITY } currentCurvature < 0 && lastCurvature > 0 -> { val v2starpos = sqrt((2 * ds * aW) / lastCurvature) val precond = if (lastCurvature + currentCurvature < 0) sqrt( (-4 * currentCurvature * ds * (currentCurvature * aT - aW)) / ((lastCurvature + currentCurvature) * (lastCurvature - currentCurvature)) ) else Double.POSITIVE_INFINITY val threshTmp = max( min( precond, sqrt( (-2 * ds * (aT * currentCurvature - aW).pow(2)) / ((aT * (lastCurvature + currentCurvature) - 2 * aW) * (lastCurvature - currentCurvature)) ) ), sqrt(2 * ds * aT) ) min(threshTmp, v2starpos) } currentCurvature > 0 && lastCurvature < 0 -> { val v1starpos = sqrt((-2 * ds * aW) / lastCurvature) val precond = if (lastCurvature + currentCurvature > 0) sqrt( (-4 * currentCurvature * ds * (currentCurvature * aT + aW)) / ((lastCurvature + currentCurvature) * (lastCurvature - currentCurvature)) ) else Double.POSITIVE_INFINITY val threshTmp = max( min( precond, sqrt( (-2 * ds * (aT * currentCurvature + aW).pow(2)) / ((aT * (lastCurvature + currentCurvature) + 2 * aW) * (lastCurvature - currentCurvature)) ) ), sqrt(2 * ds * aT) ) min(threshTmp, v1starpos) } currentCurvature epsilonEquals 0.0 -> { when { lastCurvature > 0 -> { val v2hatpos = sqrt((2 * ds * aW) / lastCurvature) val threshTmp = max( sqrt(2 * ds * aT), sqrt( (-2 * ds * aW * aW) / (lastCurvature * (lastCurvature * aT - 2 * aW)) ) ) min(v2hatpos, threshTmp) } lastCurvature < 0 -> { val v1hatpos = sqrt(-(2 * ds * aW) / lastCurvature) val threshTmp = max( sqrt(2 * ds * aT), sqrt((-2 * ds * aW * aW) / (lastCurvature * (lastCurvature * aT + 2 * aW))) ) min(v1hatpos, threshTmp) } else -> Double.POSITIVE_INFINITY } } else -> Double.POSITIVE_INFINITY } } }
1
null
2
9
3ed0c4a444f8934b9bf39a9a95270447696e3a0c
7,852
joos
MIT License
app/src/main/kotlin/net/yuzumone/twltrus/tdr/model/Facility.kt
yuzumone
95,168,653
false
{"Kotlin": 57823}
package net.yuzumone.twltrus.tdr.model data class Facility( val greeting: Greeting? )
0
Kotlin
1
0
e1a5f6206eb87204532c93c7ba8c2b97c0e41291
94
TDR_for_Twltrus
Apache License 2.0
compiler/testData/diagnostics/tests/CompareToWithErrorType.kt
JakeWharton
99,388,807
false
null
// !WITH_NEW_INFERENCE fun test() { if (<!UNRESOLVED_REFERENCE!>x<!> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>><!> 0) { } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
125
kotlin
Apache License 2.0
src/test/kotlin/zoneddatetime/ZonedDateTimeParsingExtensionsTest.kt
seljabali
402,993,185
false
null
package zoneddatetime import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import javatimefun.zoneddatetime.extensions.toZonedDateTime import javatimefun.zoneddatetime.extensions.print import java.lang.RuntimeException import java.time.ZonedDateTime class ZonedDateTimeParsingExtensionsTest { companion object { private const val YYYY_MM_DD_DASH = "yyyy-MM-dd" private const val MM_DD_YYYY_SLASH = "MM/dd/yyyy" } @Test fun `given date in YYYY-MM-DD, when parsed without format & converted to date, then should match when printed back to text`() { // given val dateInText = "2021-06-07" // when val dateParsed: ZonedDateTime = dateInText.toZonedDateTime() ?: throw RuntimeException("Failed to parse") // then assertEquals(dateInText, dateParsed.print(YYYY_MM_DD_DASH)) } @Test fun `given date in YYYY-MM-DD, when parsed with format & converted to date, then should match when printed back to text`() { // given val dateInText = "2021-06-07" // when val dateParsed: ZonedDateTime = dateInText.toZonedDateTime(format = YYYY_MM_DD_DASH) ?: throw RuntimeException("Failed to parse") // then assertEquals(dateInText, dateParsed.print(YYYY_MM_DD_DASH)) } @Test fun `given date in MM-DD-YYYY, when parsed with format & converted to date, then should match when printed back to text`() { // given val dateInText = "06/07/2021" // when val dateParsed: ZonedDateTime = dateInText.toZonedDateTime(format = MM_DD_YYYY_SLASH) ?: throw RuntimeException("Failed to parse") // then assertEquals(dateInText, dateParsed.print(MM_DD_YYYY_SLASH)) } }
4
null
2
57
37fad7d1593da28e99924936b7559ca27e5573b1
1,792
java-time-fun
MIT License
src/me/anno/utils/process/DelayedTask.kt
AntonioNoack
456,513,348
false
null
package me.anno.utils.process import me.anno.Time import me.anno.maths.Maths.MILLIS_TO_NANOS import me.anno.studio.Events.addEvent import me.anno.utils.OS import kotlin.concurrent.thread class DelayedTask( private val function: () -> Unit, private val delayMillis: Long = 500 ) { constructor(function: () -> Unit) : this(function, 500) var isWorking = false var endTime = 0L fun update() { synchronized(this) { if (isWorking) return isWorking = true } if (OS.isWeb) {// no threading supported rn endTime = Time.nanoTime + delayMillis * MILLIS_TO_NANOS webUpdate() } else { thread(name = "DelayedTask") { try { Thread.sleep(delayMillis) } catch (e: InterruptedException) { // mmh... } try { function() } catch (e: Exception) { e.printStackTrace() // something went wrong; // we need to unlock it anyway } isWorking = false } } } private fun webUpdate() { if (Time.nanoTime >= endTime) { function() isWorking = false } else { addEvent(this::webUpdate) } } }
0
null
3
9
94bc7c74436aa567ec3c19f386dd67af0f1ced00
1,402
RemsEngine
Apache License 2.0
src/main/kotlin/io/kotest/generation/actual/SerializerVisitor.kt
AlexCue987
728,293,561
false
{"Kotlin": 180787}
package io.kotest.generation.actual import io.kotest.generation.common.CodeSnippet interface SerializerVisitor { fun serialize( instance: Any?, buffer: CodeSnippet, isLast: Boolean ): Boolean { if(canHandle((instance))) { handle(instance, buffer, isLast) return true } return false } fun canHandle(instance: Any?): Boolean fun handle( instance: Any?, buffer: CodeSnippet, isLast: Boolean ) }
0
Kotlin
0
0
c98fdcec436975e3754e190352d2eab8bdaa1d85
515
kotests-mockks-generator
Apache License 2.0
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/highlighting.kt
lots0logs
177,218,243
false
{"Text": 3529, "XML": 4474, "Ant Build System": 14, "Shell": 33, "Markdown": 24, "Ignore List": 34, "Git Attributes": 6, "Batchfile": 26, "SVG": 1874, "Java": 61724, "C++": 15, "HTML": 2676, "Kotlin": 3320, "DTrace": 1, "Gradle": 49, "Java Properties": 89, "Groovy": 2931, "INI": 217, "JFlex": 25, "XSLT": 109, "JavaScript": 148, "CSS": 53, "JSON": 759, "desktop": 1, "Python": 9049, "YAML": 385, "C#": 37, "Smalltalk": 17, "Diff": 125, "Rich Text Format": 2, "CoffeeScript": 3, "JSON with Comments": 2, "Vue": 8, "OpenStep Property List": 1, "Perl": 4, "Protocol Buffer": 2, "JAR Manifest": 9, "fish": 1, "EditorConfig": 213, "E-mail": 18, "Roff": 37, "Roff Manpage": 1, "Maven POM": 1, "Checksums": 58, "Java Server Pages": 8, "C": 41, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 6, "Microsoft Visual Studio Solution": 6, "Objective-C": 18, "VBScript": 1, "NSIS": 8, "PHP": 46, "Thrift": 3, "TeX": 7, "Cython": 9, "reStructuredText": 54, "TOML": 1, "Dockerfile": 1, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInspection.type import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.util.containers.toArray import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.highlighting.HighlightSink import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.createSignature import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments fun HighlightSink.highlightUnknownArgs(highlightElement: PsiElement) { registerProblem(highlightElement, ProblemHighlightType.WEAK_WARNING, message("cannot.infer.argument.types")) } fun HighlightSink.highlightCannotApplyError(invokedText: String, typesString: String, highlightElement: PsiElement) { registerError(highlightElement, message("cannot.apply.method.or.closure", invokedText, typesString)) } fun HighlightSink.highlightAmbiguousMethod(highlightElement: PsiElement) { registerError(highlightElement, message("constructor.call.is.ambiguous")) } fun HighlightSink.highlightInapplicableMethod(result: GroovyMethodResult, arguments: List<Argument>, argumentList: GrArgumentList?, highlightElement: PsiElement) { val method = result.element val containingClass = if (method is GrGdkMethod) method.staticMethod.containingClass else method.containingClass val argumentString = argumentsString(arguments) val methodName = method.name if (containingClass == null) { highlightCannotApplyError(methodName, argumentString, highlightElement) return } val message: String if (method is DefaultConstructor) { message = message("cannot.apply.default.constructor", methodName) } else { val factory = JavaPsiFacade.getElementFactory(method.project) val containingType = factory.createType(containingClass, result.substitutor) val canonicalText = containingType.internalCanonicalText if (method.isConstructor) { message = message("cannot.apply.constructor", methodName, canonicalText, argumentString) } else { message = message("cannot.apply.method1", methodName, canonicalText, argumentString) } } val fixes = generateCastFixes(result, arguments, argumentList) registerProblem(highlightElement, ProblemHighlightType.GENERIC_ERROR, message, *fixes) } private fun argumentsString(arguments: List<Argument>): String { return arguments.joinToString(", ", "(", ")") { it.type?.internalCanonicalText ?: "?" } } private fun generateCastFixes(result: GroovyMethodResult, arguments: Arguments, argumentList: GrArgumentList?): Array<out LocalQuickFix> { val signature = createSignature(result.element, result.substitutor) return GroovyTypeCheckVisitorHelper.genCastFixes(signature, arguments.map(Argument::type).toArray(PsiType.EMPTY_ARRAY), argumentList) }
1
null
1
1
ef9153d8a369982a9827f05207063664436a7660
3,600
intellij-community
Apache License 2.0
app/src/main/java/com/oscarliang/knews/db/NewsDatabase.kt
iamoscarliang
761,140,560
false
{"Kotlin": 151931}
package com.oscarliang.knews.db import androidx.room.Database import androidx.room.RoomDatabase import com.oscarliang.knews.model.BreakingNews import com.oscarliang.knews.model.News import com.oscarliang.knews.model.NewsSearchResult @Database( entities = [News::class, BreakingNews::class, NewsSearchResult::class], version = 1 ) abstract class NewsDatabase : RoomDatabase() { abstract fun newsDao(): NewsDao }
0
Kotlin
0
0
c03764f4d80338cff8fa98bc59a72ecbd892af6d
426
k-news
MIT License
main/src/main/java/com/google/android/apps/muzei/browse/BrowseProviderFragment.kt
ianhanniballake
24,799,536
false
null
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.browse import android.app.PendingIntent import android.os.Bundle import android.view.Menu import android.view.View import android.view.ViewGroup import androidx.appcompat.graphics.drawable.DrawerArrowDrawable import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import coil.load import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_MARK_ARTWORK_LOADED import com.google.android.apps.muzei.room.Artwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.room.getCommands import com.google.android.apps.muzei.sync.ProviderManager import com.google.android.apps.muzei.util.ContentProviderClientCompat import com.google.android.apps.muzei.util.addMenuProvider import com.google.android.apps.muzei.util.collectIn import com.google.android.apps.muzei.util.toast import com.google.firebase.Firebase import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.BrowseProviderFragmentBinding import net.nurik.roman.muzei.databinding.BrowseProviderItemBinding class BrowseProviderFragment: Fragment(R.layout.browse_provider_fragment) { companion object { const val REFRESH_DELAY = 300L // milliseconds } private val viewModel: BrowseProviderViewModel by viewModels() private val args: BrowseProviderFragmentArgs by navArgs() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = BrowseProviderFragmentBinding.bind(view) viewModel.providerInfo.collectIn(viewLifecycleOwner) { providerInfo -> if (providerInfo != null) { val pm = requireContext().packageManager binding.toolbar.title = providerInfo.loadLabel(pm) } else { // The contentUri is no longer valid, so we should pop findNavController().popBackStack() } } binding.swipeRefresh.setOnRefreshListener { refresh(binding.swipeRefresh) } binding.toolbar.apply { navigationIcon = DrawerArrowDrawable(requireContext()).apply { progress = 1f } setNavigationOnClickListener { val navController = findNavController() if (navController.currentDestination?.id == R.id.browse_provider) { navController.popBackStack() } } addMenuProvider(R.menu.browse_provider_fragment) { refresh(binding.swipeRefresh) true } } val adapter = Adapter() binding.list.adapter = adapter viewModel.client.collectIn(viewLifecycleOwner) { adapter.client = it } viewModel.artwork.collectIn(viewLifecycleOwner) { adapter.submitList(it) } } private fun refresh(swipeRefreshLayout: SwipeRefreshLayout) { viewLifecycleOwner.lifecycleScope.launch { ProviderManager.requestLoad(requireContext(), args.contentUri) // Show the refresh indicator for some visible amount of time // rather than immediately dismissing it. We don't know how long // the provider will actually take to refresh, if it does at all. delay(REFRESH_DELAY) withContext(Dispatchers.Main.immediate) { swipeRefreshLayout.isRefreshing = false } } } class ArtViewHolder( private val owner: LifecycleOwner, private val binding: BrowseProviderItemBinding, private val clientProvider: () -> ContentProviderClientCompat?, ): RecyclerView.ViewHolder(binding.root) { fun bind(artwork: Artwork) { val context = itemView.context binding.image.contentDescription = artwork.title binding.image.load(artwork.imageUri) { lifecycle(owner) } itemView.setOnClickListener { owner.lifecycleScope.launch(Dispatchers.Main) { Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority) param(FirebaseAnalytics.Param.ITEM_NAME, artwork.title ?: "") param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions") param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse") } // Ensure the date added is set to the current time artwork.dateAdded.time = System.currentTimeMillis() MuzeiDatabase.getInstance(context).artworkDao() .insert(artwork) clientProvider.invoke()?.call(METHOD_MARK_ARTWORK_LOADED, artwork.imageUri.toString()) context.toast(if (artwork.title.isNullOrBlank()) { context.getString(R.string.browse_set_wallpaper) } else { context.getString(R.string.browse_set_wallpaper_with_title, artwork.title) }) } } itemView.setOnCreateContextMenuListener(null) owner.lifecycleScope.launch(Dispatchers.Main.immediate) { val actions = artwork.getCommands(context).filterNot { it.title.isBlank() } if (actions.isNotEmpty()) { itemView.setOnCreateContextMenuListener { menu, _, _ -> actions.forEachIndexed { index, action -> menu.add(Menu.NONE, index, index, action.title).apply { setOnMenuItemClickListener { menuItem -> Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority) param(FirebaseAnalytics.Param.ITEM_NAME, menuItem.title.toString()) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions") param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse") } try { action.actionIntent.send() } catch (e: PendingIntent.CanceledException) { // Why do you give us a cancelled PendingIntent. // We can't do anything with that. } true } } } } } } } } inner class Adapter: ListAdapter<Artwork, ArtViewHolder>( object: DiffUtil.ItemCallback<Artwork>() { override fun areItemsTheSame(artwork1: Artwork, artwork2: Artwork) = artwork1.imageUri == artwork2.imageUri override fun areContentsTheSame(artwork1: Artwork, artwork2: Artwork) = artwork1 == artwork2 } ) { var client: ContentProviderClientCompat? = null override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ) = ArtViewHolder( viewLifecycleOwner, BrowseProviderItemBinding.inflate(layoutInflater, parent, false) ) { client } override fun onBindViewHolder(holder: ArtViewHolder, position: Int) { holder.bind(getItem(position)) } } }
40
null
959
7
14a0c0c41e2628375bc5a5e5a135ff933d8b7c27
9,146
muzei
Apache License 2.0
consumerapp/src/main/java/com/dnar/consumerapp/ui/main/profile/follow/ProfileFollowViewModel.kt
dimas-nur
267,992,206
false
null
package com.dnar.consumerapp.ui.main.profile.follow import androidx.lifecycle.ViewModel import com.dnar.consumerapp.data.repositories.ProfileRepository import javax.inject.Inject class ProfileFollowViewModel @Inject constructor( private val repository: ProfileRepository ) : ViewModel() { // Function : for get data list followers from api fun getFollowers(username: String) = repository.getFollowersUser(username) // Function : for get data list following from api fun getFollowing(username: String) = repository.getFollowingUser(username) override fun onCleared() { repository.disposeComposite() super.onCleared() } }
0
Kotlin
19
58
48bc4fb7209d5b116a0794fd26828699bfbaab14
668
dicoding-belajar-fundamental-aplikasi-android
Apache License 2.0
components/src/desktopMain/kotlin/com/paligot/movies/components/RatingPreviews.kt
GerardPaligot
312,828,696
false
null
package com.paligot.movies.components import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Preview @Composable fun RatingGreenPreview() { Rating(80, modifier = Modifier.size(100.dp)) } @Preview @Composable fun RatingOrangePreview() { Rating(54, modifier = Modifier.size(80.dp)) } @Preview @Composable fun RatingRedPreview() { Rating(22, modifier = Modifier.size(50.dp)) }
0
Kotlin
0
47
0ad52c9df8646f78a3496a6916aeb5d254079b87
555
discovering-movies
Apache License 2.0
.teamcity/_Self/subprojects/GitHub.kt
JetBrains
1,459,486
false
null
package _Self.subprojects import _Self.buildTypes.GithubTests import jetbrains.buildServer.configs.kotlin.v2019_2.Project object GitHub : Project({ name = "Pull Requests checks" description = "Automatic checking of GitHub Pull Requests" buildType(GithubTests) })
7
Kotlin
692
7,422
2a6b6f89f42f4d21a2f7c6e534191a3d8ac86428
272
ideavim
MIT License
src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/DelimiterParser.kt
JetBrains
27,873,341
false
{"Kotlin": 1305157, "Lex": 29252, "Ruby": 691, "Shell": 104}
package org.intellij.markdown.parser.sequentialparsers import org.intellij.markdown.IElementType abstract class DelimiterParser { /** * Finds all tokens that open or close element represented by this parser. * Invoked by [EmphasisLikeParser.collectDelimiters]. * * Delimiters matching will be handled by the [EmphasisLikeParser.balanceDelimiters] * after delimiters from all parsers will be collected. * * @return Number of steps to advance token iterator. */ abstract fun scan(tokens: TokensCache, iterator: TokensCache.Iterator, delimiters: MutableList<Info>): Int /** * Receives a list of delimiters collected by [scan] * (contains tokens from all parsers) and creates actual tree nodes from them. * * If there is a matching delimiter for the current one, it will have non-negative [Info.closerIndex]. */ abstract fun process( tokens: TokensCache, iterator: TokensCache.Iterator, delimiters: MutableList<Info>, result: SequentialParser.ParsingResultBuilder ) data class Info( val tokenType: IElementType, val position: Int, /** * Represents the length of the current delimiter run * and will be used to check [9 and 10 rules](https://spec.commonmark.org/0.30/#can-open-emphasis) * (rule of 3) for emphasises on the delimiter balancing phase (will be skipped if equals to 0). */ val length: Int = 0, var canOpen: Boolean, var canClose: Boolean, var marker: Char, /** * Index of the closing delimiter for the current one. * If it is less than 0, current delimiter does not have a matching closer. * * Will be set by the [EmphasisLikeParser.balanceDelimiters] after all delimiters will be collected. */ var closerIndex: Int = -1 ) /** * Checks if current token can open or close emphasis based on the current delimiter run. * * See [Rules for opening and closing emphasises](https://spec.commonmark.org/0.30/#can-open-emphasis). */ open fun canOpenClose( tokens: TokensCache, left: TokensCache.Iterator, right: TokensCache.Iterator, canSplitText: Boolean ): Pair<Boolean, Boolean> { val isLeftFlanking = isLeftFlankingRun(left, right) val isRightFlanking = isRightFlankingRun(tokens, left, right) val canOpen = when { canSplitText -> isLeftFlanking else -> isLeftFlanking && (!isRightFlanking || SequentialParserUtil.isPunctuation(left, -1)) } val canClose = when { canSplitText -> isRightFlanking else -> isRightFlanking && (!isLeftFlanking || SequentialParserUtil.isPunctuation(right, 1)) } return canOpen to canClose } /** * See [left flanking delimiter run](http://spec.commonmark.org/0.30/#left-flanking-delimiter-run) */ open fun isLeftFlankingRun(leftIt: TokensCache.Iterator, rightIt: TokensCache.Iterator): Boolean { return !isWhitespace(rightIt, 1) && (!isPunctuation(rightIt, 1) || isWhitespace(leftIt, -1) || isPunctuation(leftIt, -1)) } /** * See [right flanking delimiter run](https://spec.commonmark.org/0.30/#right-flanking-delimiter-run) */ open fun isRightFlankingRun(tokens: TokensCache, leftIt: TokensCache.Iterator, rightIt: TokensCache.Iterator): Boolean { return leftIt.charLookup(-1) != getType(leftIt) && !isWhitespace(leftIt, -1) && (!isPunctuation(leftIt, -1) || isWhitespace(rightIt, 1) || isPunctuation(rightIt, 1)) } open fun isWhitespace(info: TokensCache.Iterator, lookup: Int): Boolean { return SequentialParserUtil.isWhitespace(info, lookup) } open fun isPunctuation(info: TokensCache.Iterator, lookup: Int): Boolean { return SequentialParserUtil.isPunctuation(info, lookup) } companion object { const val maxAdvance = 50 fun getType(iterator: TokensCache.Iterator): Char { return iterator.firstChar } } }
56
Kotlin
75
661
43c06cb6a9d66caab8b431f738aba3c57aee559f
4,237
markdown
Apache License 2.0
app/src/main/java/com/example/worldcapitalsquiz/GameScreen.kt
cosmin-oros
509,459,475
false
null
package com.example.worldcapitalsquiz import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.navigation.NavController import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import com.google.android.gms.ads.MobileAds import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.* import kotlin.collections.ArrayList @SuppressLint("UnrememberedMutableState") @Composable fun GameScreen(navController: NavController, name: String?) { var textFieldState by remember{ mutableStateOf("") } val scaffoldState = rememberScaffoldState() val scope = rememberCoroutineScope() val countriesList = ListOfCountries.getData().sortedBy { country-> country.order } var counter = 0 //count until 195 var guessed = 0 var country = mutableStateOf(getCountry(countriesList, counter)) //percentage of the circular progress bar var percentage = 0F val type: String if (name == "0") { type = "0" }else { type = "1" } Scaffold( modifier = Modifier.fillMaxSize(), scaffoldState = scaffoldState, ) { Button( onClick = { navController.navigate(Screen.GameScreen.withArgs(type)) }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = Color.LightGray ), modifier = Modifier .padding(10.dp) .border( width = 5.dp, brush = Brush.horizontalGradient( listOf( Color.Magenta, Color.Yellow ) ), shape = RoundedCornerShape(15.dp) ) .width(100.dp) .background( Brush.horizontalGradient( colors = listOf( Color.Transparent, Color.Transparent ), startX = 150f ) ) ) { Text(text = "Restart") } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { var painter = painterResource(id = country.value.flagId) var countryName = country.value.country var capitalName = country.value.capital var hint = country.value.hint if (name == "0"){ Text(text = countryName) } Box( modifier = Modifier .fillMaxWidth(0.85f) .padding(16.dp), contentAlignment = Alignment.Center ){ ImageCard( painter = painter, contentDescription = countryName ) } Spacer(modifier = Modifier.size(32.dp)) OutlinedTextField( value = textFieldState, label = { Text(text = "Enter the capital") }, onValueChange = { textFieldState = it }, singleLine = true, modifier = Modifier .fillMaxWidth(0.6f), textStyle = TextStyle(color = Color.LightGray, fontSize = 20.sp), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text ) ) Spacer(modifier = Modifier.size(32.dp)) Row { Button( onClick = { if (counter < 192) { if (textFieldState.lowercase(Locale.getDefault()) == capitalName.lowercase( Locale.getDefault() ) ) { counter++ country.value = getCountry(countriesList, counter) guessed++ textFieldState = "" percentage += 0.0052F } else { scope.launch { scaffoldState.snackbarHostState.showSnackbar("Try again") textFieldState = "" } } } if (counter == 192){ scope.launch { scaffoldState.snackbarHostState.showSnackbar("Congratulations you got $guessed out of 193") textFieldState = "" delay(3000L) navController.navigate("main_screen") } } }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = Color.LightGray ), modifier = Modifier .border( width = 5.dp, brush = Brush.horizontalGradient( listOf( Color.Magenta, Color.Yellow ) ), shape = RoundedCornerShape(15.dp) ) .width(100.dp) .background( Brush.horizontalGradient( colors = listOf( Color.Transparent, Color.Transparent ), startX = 150f ) ) ) { Text(text = "Check") } Spacer(modifier = Modifier.width(32.dp)) /* has to be 192 else it would crash */ Button( onClick = { if (counter < 192) { counter++ country.value = getCountry(countriesList, counter) textFieldState = "" } if (counter == 192){ scope.launch { scaffoldState.snackbarHostState.showSnackbar("Congratulations you got $guessed out of 193") textFieldState = "" delay(3000L) navController.navigate("main_screen") } } }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = Color.LightGray ), modifier = Modifier .border( width = 5.dp, brush = Brush.horizontalGradient( listOf( Color.Magenta, Color.Yellow ) ), shape = RoundedCornerShape(15.dp) ) .width(100.dp) .background( Brush.horizontalGradient( colors = listOf( Color.Transparent, Color.Transparent ), startX = 150f ) ) ) { Text(text = "Skip") } } Spacer(modifier = Modifier.size(64.dp)) Row { ExpandableCard( title = "Hint", description = hint ) Spacer(modifier = Modifier.width(32.dp)) CircularProgressBar(percentage = percentage, number = 193) } } } } fun getCountry(countriesList: List<CountriesData>, counter: Int): CountriesData{ return countriesList[counter] }
0
Kotlin
0
2
87732f32a9f51446484de90f111cf1d4085e0d64
9,788
World-Capitals-Quiz-App
MIT License
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/collect/FromAnnotations.kt
arrow-kt
217,378,939
false
null
package arrow.meta.plugins.analysis.phases.analysis.solver.collect import arrow.meta.plugins.analysis.phases.analysis.solver.RESULT_VAR_NAME import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.ResolutionContext import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.AnalysisResult import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.AnnotationDescriptor import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.CallableDescriptor import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.DeclarationDescriptor import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.ModuleDescriptor import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.hasInterestingAnnotation import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements.FqName import arrow.meta.plugins.analysis.phases.analysis.solver.collect.model.NamedConstraint import arrow.meta.plugins.analysis.phases.analysis.solver.gather import arrow.meta.plugins.analysis.phases.analysis.solver.state.SolverState import org.sosy_lab.java_smt.api.BooleanFormula /** * Collects constraints by harvesting annotations. There are two sources: local declarations, and * the entire CLASSPATH. */ public fun SolverState.collectConstraintsFromAnnotations( localDeclarations: List<DeclarationDescriptor>, module: ModuleDescriptor, bindingTrace: ResolutionContext ): Pair<AnalysisResult, Set<FqName>> { // check local declarations for @Laws collectFromLocalDeclarations(localDeclarations, bindingTrace) // check rest of the CLASSPATH for @Laws collectFromClasspath(module, bindingTrace) return if (hadParseErrors()) { Pair(AnalysisResult.ParsingError, emptySet()) } else { // figure out which is the set of local elements // whose packages should be added in the hints val interesting = localDeclarations .flatMap { it.gather { callableConstraints.containsKey(it.fqNameSafe) } } .mapNotNull { it.containingPackage } .toSet() Pair(AnalysisResult.Retry, interesting) } } private fun SolverState.collectFromLocalDeclarations( localDeclarations: List<DeclarationDescriptor>, bindingTrace: ResolutionContext ) { localDeclarations.flatMap { it.gather { it.hasInterestingAnnotation } }.forEach { addConstraintsFromAnnotations(it, bindingTrace) } } private fun SolverState.collectFromClasspath( module: ModuleDescriptor, bindingTrace: ResolutionContext ) { val collectEntireClasspath = System.getProperty("ARROW_ANALYSIS_COLLECT_ENTIRE_CLASSPATH", "false").toBooleanStrictOrNull() ?: false if (collectEntireClasspath) { module.gather(addSubPackages = true) { it.hasInterestingAnnotation } } else { // usual case: figure out the right packages from the hints val packagesWithLaws = module .gather( initialPackages = listOf(FqName("arrow.analysis.hints")), addSubPackages = false ) { it.hasPackageWithLawsAnnotation } .flatMap { it.packageWithLawsAnnotation?.argumentValueAsArrayOfString("packages").orEmpty() } .map { FqName(it) } module.gather(packagesWithLaws, addSubPackages = false) { it.hasInterestingAnnotation } } .forEach { addConstraintsFromAnnotations(it, bindingTrace) } } internal fun SolverState.addConstraintsFromAnnotations( descriptor: DeclarationDescriptor, bindingContext: ResolutionContext ) { val constraints = descriptor.annotations().iterable().mapNotNull { ann -> when (ann.fqName) { FqName("arrow.analysis.Pre") -> "pre" FqName("arrow.analysis.Post") -> "post" FqName("arrow.analysis.DoNotLookAtArguments") -> "doNotLookAtArgumentsWhen" else -> null }?.let { element -> parseFormula(element, ann, descriptor) } } if (constraints.isNotEmpty()) { val preConstraints = arrayListOf<NamedConstraint>() val postConstraints = arrayListOf<NamedConstraint>() val notLookConstraints = arrayListOf<NamedConstraint>() constraints.forEach { (call, formula) -> if (call == "pre") preConstraints.addAll(formula) if (call == "post") postConstraints.addAll(formula) if (call == "doNotLookAtArgumentsWhen") notLookConstraints.addAll(formula) } addConstraints(descriptor, preConstraints, postConstraints, notLookConstraints, bindingContext) } } /** Parse constraints from annotations. */ private fun SolverState.parseFormula( element: String, annotation: AnnotationDescriptor, descriptor: DeclarationDescriptor ): Pair<String, List<NamedConstraint>> { val dependencies = annotation.argumentValueAsArrayOfString("dependencies") val formulae = annotation.argumentValueAsArrayOfString("formulae") val messages = annotation.argumentValueAsArrayOfString("messages") return element to messages.zip(formulae).map { (msg, formula) -> NamedConstraint(msg, parseFormula(descriptor, formula, dependencies.toList())) } } /** Parse constraints from annotations. */ internal fun SolverState.parseFormula( descriptor: DeclarationDescriptor, formula: String, dependencies: List<String> ): BooleanFormula { val VALUE_TYPE = "Int" val FIELD_TYPE = "Int" // build the parameters environment val params = (descriptor as? CallableDescriptor)?.let { function -> function.valueParameters.joinToString(separator = "\n") { param -> "(declare-fun ${param.name} () $VALUE_TYPE)" } } ?: "" // build the dependencies val deps = dependencies.joinToString(separator = "\n") { "(declare-fun $it () $FIELD_TYPE)" } // build the rest of the environment val rest = """ (declare-fun this () $VALUE_TYPE) (declare-fun $RESULT_VAR_NAME () $VALUE_TYPE) """.trimIndent() val fullString = "$params\n$deps\n$rest\n(assert $formula)" return solver.parse(fullString) }
97
null
40
316
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
5,999
arrow-meta
Apache License 2.0
library/src/main/java/ss_n/common_ktx/extension/LiveData_Extension.kt
sasa-nori
245,430,303
false
null
package ss_n.common_ktx.extension import androidx.lifecycle.LiveData import ss_n.common_ktx.test.TestObserver /** * Used in unit tests */ fun <T> LiveData<T>.testObserver() = TestObserver<T>().also { observeForever(it) }
10
Kotlin
3
4
8d3eb18676ef343f0f0da47b42f7ba1ac7c508e1
229
common-ktx
Apache License 2.0
tools/src/test/kotlin/pw/binom/material/lex/CompileTest.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.material.lex import org.junit.Test import pw.binom.material.EmptyModuleResolver import pw.binom.material.SourceModule import pw.binom.material.compiler.Compiler import java.io.StringReader class CompileTest { @Test fun incDecTest() { val compiler = Parser(StringReader(""" bool test(vec4 color2){ int gg=10 int b = gg++ } """)).let { Compiler(it, SourceModule(), EmptyModuleResolver) } } @Test fun inverTest() { val compiler = Parser(StringReader(""" bool test(vec4 color2){ int gg=10 int b = -gg } """)).let { Compiler(it, SourceModule(), EmptyModuleResolver) } } @Test fun parenthesisTest() { val compiler = Parser(StringReader(""" bool test(vec4 color2){ int gg=(2+2) } """)).let { Compiler(it, SourceModule(), EmptyModuleResolver) } } @Test fun constGlobalField() { val compiler = Parser(StringReader(""" float PI = 3.14159265359f """)).let { Compiler(it, SourceModule(), EmptyModuleResolver) } } @Test fun testNull() { val compiler = Parser(StringReader(""" @property sampler2D texture vec4 vertex(){ bool tex=false if (texture!=null){ tex=true } return vec4(1f,1f,1f,1f) } """)).let { Compiler(it, SourceModule(), EmptyModuleResolver) } } @Test fun annotationTest(){ val parser = Parser(StringReader(""" @test(value="123") """)) parser.global.size.eq(1) val ann = parser.global[0] as Annotation ann.name.eq("test") ann.properties.size.eq(1) ann.properties.first().also { it.key.eq("value") it.value.eq("123") } } }
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
1,949
mogot
Apache License 2.0
app/src/main/java/com/example/recycleview/pojo/TypeX.kt
sidkiamri
733,158,336
false
{"Kotlin": 113149}
package com.example.recycleview.pojo import com.google.gson.annotations.SerializedName data class TypeX( @SerializedName("_id") val id: String, @SerializedName("type_name") val typename: String )
0
Kotlin
0
0
9bf93bd95847eb157aa8d9df6edea0ef9e54c3ca
215
SearchAndRecycle-Android
MIT License
app/src/main/java/com/zql/travelassistant/http/RetrofitCallback.kt
zliu80
596,862,076
false
{"Kotlin": 142568, "JavaScript": 25356}
package com.zql.travelassistant.http import android.app.Activity import com.zql.travelassistant.R import com.zql.travelassistant.bean.AttractionList import dev.shreyaspatil.MaterialDialog.AbstractDialog import dev.shreyaspatil.MaterialDialog.MaterialDialog import retrofit2.Call import retrofit2.Callback import retrofit2.Response interface RetrofitCallback<T>:Callback<T>
0
Kotlin
0
0
08e0d5b31cdaec24acd1d2eed85b2b9fe478afec
375
Travel-Assistant-Kotlin-Android
MIT License
server/src/main/kotlin/net/horizonsend/ion/server/features/starship/subsystem/weapon/projectile/ParticleProjectile.kt
HorizonsEndMC
461,042,096
false
{"Kotlin": 2639036, "Java": 15809, "Shell": 1414, "JavaScript": 78}
package net.horizonsend.ion.server.features.starship.subsystem.weapon.projectile import net.horizonsend.ion.server.features.starship.active.ActiveStarship import net.horizonsend.ion.server.features.starship.damager.Damager import org.bukkit.Location import org.bukkit.util.Vector abstract class ParticleProjectile( starship: ActiveStarship?, loc: Location, dir: Vector, shooter: Damager ) : SimpleProjectile(starship, loc, dir, shooter) { override fun moveVisually(oldLocation: Location, newLocation: Location, travel: Double) { for (i in 0 until travel.toInt()) { val x = loc.x + dir.x * i val y = loc.y + dir.y * i val z = loc.z + dir.z * i val force = i % 3 == 0 spawnParticle(x, y, z, force) } } protected abstract fun spawnParticle(x: Double, y: Double, z: Double, force: Boolean) }
17
Kotlin
26
9
55b6783a93ab5f288ea2379a2b04d97bbcbf9f4b
817
Ion
MIT License
app/src/main/java/com/moegirlviewer/screen/compare/util/showUndoDialog.kt
koharubiyori
449,942,456
false
null
package com.moegirlviewer.screen.compare.util import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.MaterialTheme import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.pager.ExperimentalPagerApi import com.google.gson.Gson import com.moegirlviewer.R import com.moegirlviewer.component.PlainTextField import com.moegirlviewer.component.commonDialog.ButtonConfig import com.moegirlviewer.component.commonDialog.CommonAlertDialogProps import com.moegirlviewer.component.styled.StyledText import com.moegirlviewer.screen.compare.CompareScreenModel import com.moegirlviewer.theme.background2 import com.moegirlviewer.util.Globals import kotlinx.coroutines.launch @ExperimentalPagerApi fun showUndoDialog(model: CompareScreenModel) { var summary by mutableStateOf("") val quickInsertList = Gson().fromJson(Globals.context.getString(R.string.jsonArray_quickSummaryListOfUndo), Array<String>::class.java) fun submit() { model.coroutineScope.launch { val isCloseDialog = model.submitUndo(summary) if (isCloseDialog) { Globals.commonAlertDialog.hide() } } } Globals.commonAlertDialog.show(CommonAlertDialogProps( title = Globals.context.getString(R.string.execUndo), closeOnDismiss = false, closeOnAction = false, content = { val themeColors = MaterialTheme.colors Column { PlainTextField( modifier = Modifier .padding(vertical = 5.dp), value = summary, placeholder = stringResource(id = R.string.inputUndoReasonPlease), singleLine = true, underline = true, maxLength = 200, lengthIndicator = true, textStyle = TextStyle( fontSize = 16.sp ), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onAny = { submit() } ), onValueChange = { summary = it } ) StyledText( text = stringResource(id = R.string.quickInsert), fontSize = 16.sp ) Row( modifier = Modifier .horizontalScroll(rememberScrollState()) ) { for (item in quickInsertList) { StyledText( modifier = Modifier .padding(top = 10.dp, end = 5.dp) .clip(CircleShape) .clickable { summary += item } .background(themeColors.background2) .padding(vertical = 5.dp, horizontal = 10.dp), text = item, ) } } } }, secondaryButton = ButtonConfig.cancelButton(), primaryButtonText = Globals.context.getString(R.string.submit), onPrimaryButtonClick = { submit() } )) }
1
Kotlin
2
16
e09753e76c11932d6f7344302d48f7a214cccf3a
3,595
Moegirl-plus-native
MIT License
app/src/main/java/com/indisparte/moovaride/data/remote/dto/AccountDTO.kt
iamantoniodinuzzo
698,121,364
false
{"Kotlin": 170845}
package com.indisparte.moovaride.data.remote.dto data class AccountDTO( val activationToken: String, val creationDate: String, val credentialsExpired: Boolean, val enabled: Boolean, val firstAccess: Boolean, val id: String, val passwordReset: Boolean, val role: List<RoleDTO>, val username: String, )
2
Kotlin
0
0
ece192351030418549c8f01c11a684d555a66007
338
MoovaRide
Apache License 2.0
src/main/kotlin/pl/jwizard/core/audio/player/PlayerManagerFacade.kt
jwizard-bot
512,298,084
false
{"Kotlin": 272965}
/* * Copyright (c) 2024 by JWizard * Originally developed by <NAME> <https://miloszgilga.pl> */ package pl.jwizard.core.audio.player import com.sedmelluq.discord.lavaplayer.track.AudioTrack import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel import org.springframework.http.HttpMethod import org.springframework.stereotype.Component import pl.jwizard.core.audio.* import pl.jwizard.core.bot.BotConfiguration import pl.jwizard.core.command.CompoundCommandEvent import pl.jwizard.core.db.RadioStationDto import pl.jwizard.core.exception.AudioPlayerException import pl.jwizard.core.exception.UserException import pl.jwizard.core.log.AbstractLoggingBean import pl.jwizard.core.util.BotUtils import pl.jwizard.core.util.Formatter import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse @Component class PlayerManagerFacade( private val audioPlayerManager: AudioPlayerManager, private val botConfiguration: BotConfiguration, ) : PlayerManager, AbstractLoggingBean(PlayerManager::class) { private val musicManagers = mutableMapOf<String, MusicManager>() private val lockedGuilds = mutableListOf<String>() override fun loadAndPlay(event: CompoundCommandEvent, trackUrl: String, isUrlPattern: Boolean) { val musicManager = findMusicManager(event) // not creating, because it is instantiated in AbstractMusicCmd switchAudioTrackScheduler(event, musicManager, AudioSourceType.TRACK) musicManager.audioScheduler.setCompoundEvent(event) val audioLoadResultHandler = AudioLoadResultImpl( musicManager, botConfiguration, event, isUrlPattern, lockedGuilds ) event.invokedBySender = true // set hook to inform, that sending of this message was invoked by user event.guild?.audioManager?.isSelfDeafened = true audioPlayerManager.loadItemOrdered(musicManager, trackUrl, audioLoadResultHandler) } override fun loadAndStream(event: CompoundCommandEvent, radioStation: RadioStationDto) { val musicManager = findMusicManager(event) switchAudioTrackScheduler(event, musicManager, AudioSourceType.STREAM) musicManager.audioScheduler.setCompoundEvent(event) musicManager.actions.radioStationDto = radioStation // set radio station and block default queue // check primary stream url, if itn't working, swich to proxy stream url val client = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .uri(URI.create(radioStation.streamUrl)) .method(HttpMethod.HEAD.name(), HttpRequest.BodyPublishers.noBody()) .build() val response = client.send(request, HttpResponse.BodyHandlers.discarding()) // determinate stream url base availibility val streamUrl = if (response.statusCode() == 200) { radioStation.streamUrl } else { radioStation.proxyStreamUrl } event.guild?.audioManager?.isSelfDeafened = true val streamLoadResultHandler = StreamLoadResultImpl( musicManager, botConfiguration, event, radioStation ) audioPlayerManager.loadItem(streamUrl, streamLoadResultHandler) } override fun pauseTrack(event: CompoundCommandEvent) { val musicManager = findMusicManagerWithPermissions(event) musicManager.audioPlayer.isPaused = true jdaLog.info(event, "Audio player is stopped") } override fun resumePausedTrack(event: CompoundCommandEvent) { val musicManager = findMusicManager(event) val pausedTrack = musicManager.actions.getPausedTrackInfo() if (event.checkIfInvokerIsNotSenderOrAdmin(pausedTrack)) { throw AudioPlayerException.InvokerIsNotTrackSenderOrAdminException(event) } musicManager.audioPlayer.isPaused = false jdaLog.info(event, "Audio player is resumed") } override fun skipTrack(event: CompoundCommandEvent): ExtendedAudioTrackInfo? { val musicManager = findMusicManagerWithPermissions(event) val skippedTrack = currentPlayingTrack(event) if (musicManager.queue.isEmpty()) { musicManager.audioPlayer.stopTrack() } else { musicManager.actions.nextTrack() } jdaLog.info(event, "Current playing track ${skippedTrack?.title} was skipped") return skippedTrack } override fun shuffleQueue(event: CompoundCommandEvent) { val musicManager = findMusicManager(event) (musicManager.queue as MutableList<*>).shuffle() jdaLog.info(event, "Current queue tracks was shuffled") } override fun setTrackRepeat(event: CompoundCommandEvent, repeats: Int) { val musicManager = findMusicManagerWithPermissions(event) musicManager.actions.updateCountOfRepeats(repeats) val currentPlayingTrack = currentPlayingTrack(event)?.title val logInfo: String = if (repeats == 0) { "Repeating of current playing track $currentPlayingTrack was removed" } else { "Repeating of current playing track $currentPlayingTrack will be repeating $repeats times" } jdaLog.info(event, logInfo) } override fun toggleInfiniteLoopTrack(event: CompoundCommandEvent): Boolean { val musicManager = findMusicManagerWithPermissions(event) val isRepeating = musicManager.actions.toggleInfiniteRepeating() jdaLog.info( event, "Current infinite playing was turn ${Formatter.boolStr(isRepeating)} " + "for track: ${currentPlayingTrack(event)?.title}" ) return isRepeating } override fun toggleInfiniteLoopPlaylist(event: CompoundCommandEvent): Boolean { val musicManager = findMusicManager(event) if (musicManager.queue.isEmpty()) { throw AudioPlayerException.TrackQueueIsEmptyException(event) } val isTurnOn = musicManager.actions.toggleInfinitePlaylistRepeating() jdaLog.info(event, "Current playlist was turn ${Formatter.boolStr(isTurnOn)} for infinite repeating") return isTurnOn } override fun setPlayerVolume(event: CompoundCommandEvent, volume: Int) { val musicManager = findMusicManager(event) musicManager.audioPlayer.volume = volume jdaLog.info(event, "Audio player volume was set to $volume volume units") } override fun skipToTrackPos(event: CompoundCommandEvent, position: Int): AudioTrack { val musicManager = findMusicManager(event) if (musicManager.queue.isEmpty()) { throw AudioPlayerException.TrackQueueIsEmptyException(event) } musicManager.actions.skipToPosition(position) val currentPlaying = musicManager.audioPlayer.playingTrack jdaLog.info( event, "$position tracks in queue was skipped and started playing track ${currentPlaying.info.title}" ) return currentPlaying } override fun removeTracksFromMember(event: CompoundCommandEvent, memberId: String): MemberRemovedTracksInfo { val memberWithRemovableTracks = BotUtils.checkIfMemberInGuildExist(event, memberId) val musicManager = findMusicManager(event) if (musicManager.actions.checkIfMemberAddAnyTracksToQueue(memberWithRemovableTracks)) { throw UserException.UserNotAddedTracksToQueueException(event) } val removedTracks = musicManager.actions.removeAllTracksFromMember(memberWithRemovableTracks) jdaLog.info( event, "Following tracks was removed $removedTracks added by " + "member: ${memberWithRemovableTracks.user.name}" ) return MemberRemovedTracksInfo( member = memberWithRemovableTracks, removedTracks, ) } override fun moveTrackToPos(event: CompoundCommandEvent, position: TrackPosition): AudioTrack { val musicManager = findMusicManager(event) val actions = musicManager.actions if (musicManager.queue.isEmpty()) { throw AudioPlayerException.TrackQueueIsEmptyException(event) } else if (position.checkBounds(actions)) { throw AudioPlayerException.TrackPositionOutOfBoundsException(event, musicManager.queue.size) } else if (position.isSamePosition()) { throw AudioPlayerException.TrackPositionsIsTheSameException(event) } val movedTrack = musicManager.actions.moveToPosition(position) jdaLog.info( event, "Audio track: ${movedTrack.info.title} was moved from ${position.previous} " + "to ${position.selected} position in queue" ) return movedTrack } override fun clearQueue(event: CompoundCommandEvent): Int { val musicManager = findMusicManager(event) val countOfTracksInQueue = musicManager.queue.size musicManager.actions.trackQueue.clear() jdaLog.info(event, "Queue was cleared. Removed $countOfTracksInQueue audio tracks from queue") return countOfTracksInQueue } override fun currentPlayingTrack(event: CompoundCommandEvent): ExtendedAudioTrackInfo? { val musicManager = findMusicManager(event) if (musicManager.audioPlayer.playingTrack != null) { return ExtendedAudioTrackInfo(musicManager.audioPlayer.playingTrack) } return null } override fun moveToMemberCurrentVoiceChannel(event: CompoundCommandEvent): VoiceChannel { val voiceChannelWithMember = event.guild?.voiceChannels ?.find { it.members.contains(event.member) } ?: throw UserException.UserOnVoiceChannelNotFoundException(event) if (voiceChannelWithMember.members.contains(event.botMember)) { throw UserException.UserIsAlreadyWithBotException(event) } event.guild.moveVoiceMember(event.botMember!!, voiceChannelWithMember).complete() jdaLog.info(event, "Bot was successfully moved to channel ${voiceChannelWithMember.name}") return voiceChannelWithMember } override fun findMusicManager(event: CompoundCommandEvent): MusicManager = musicManagers.getOrPut(event.guildId) { val musicManager = MusicManager(botConfiguration, event, audioPlayerManager, lockedGuilds) event.guild?.audioManager?.sendingHandler = musicManager.audioPlayerSendHandler musicManagers[event.guildId] = musicManager return musicManager } override fun findMusicManager(guildId: String): MusicManager? = musicManagers[guildId] private fun findMusicManagerWithPermissions(event: CompoundCommandEvent): MusicManager { val musicManager = findMusicManager(event) val playingTrack = musicManager.audioPlayer.playingTrack if (playingTrack == null) { throw AudioPlayerException.TrackIsNotPlayingException(event) } else if (event.checkIfInvokerIsNotSenderOrAdmin(ExtendedAudioTrackInfo(playingTrack))) { throw AudioPlayerException.InvokerIsNotTrackSenderOrAdminException(event) } return musicManager } private fun switchAudioTrackScheduler( event: CompoundCommandEvent, musicManager: MusicManager, audioSourceType: AudioSourceType ) { musicManager.audioScheduler.setAudioScheduler(audioSourceType) jdaLog.info(event, "Changing audio scheduler instance to ${audioSourceType.name} type") } }
2
Kotlin
0
2
d177ef4ba3b65c87581afff5be8832bcef43012c
10,359
jwizard-core
Apache License 2.0
pulsar-proxy/src/main/kotlin/ai/platon/pulsar/proxy/server/ProxyHandles.kt
kflyddn
248,429,389
true
{"Text": 48, "Maven POM": 28, "SQL": 4, "Markdown": 5, "Ignore List": 4, "XML": 77, "Kotlin": 175, "Java": 1215, "JSON": 5, "Java Properties": 9, "HTML": 94, "INI": 2, "Java Server Pages": 22, "CSS": 1, "JavaScript": 8, "JAR Manifest": 1, "Shell": 19, "robots.txt": 1, "Rich Text Format": 1}
package ai.platon.pulsar.proxy.server import ai.platon.pulsar.common.proxy.ProxyEntry import ai.platon.pulsar.common.proxy.ProxyType import ai.platon.pulsar.proxy.common.ProtoUtil import io.netty.bootstrap.Bootstrap import io.netty.channel.* import io.netty.channel.socket.nio.NioSocketChannel import io.netty.handler.codec.http.* import io.netty.handler.proxy.HttpProxyHandler import io.netty.handler.proxy.ProxyHandler import io.netty.handler.proxy.Socks4ProxyHandler import io.netty.handler.proxy.Socks5ProxyHandler import io.netty.resolver.NoopAddressResolverGroup import io.netty.util.ReferenceCountUtil import java.net.InetSocketAddress import java.net.URL import java.util.* open class HttpProxyExceptionHandle { open fun beforeCatch(clientChannel: Channel, cause: Throwable) { throw Exception(cause) } open fun afterCatch(clientChannel: Channel, proxyChannel: Channel, cause: Throwable) { throw Exception(cause) } } /** * HTTP 代理,转发解码后的 HTTP 报文 */ open class HttpProxyInitializer( private val clientChannel: Channel, private val requestProto: ProtoUtil.RequestProto, private val proxyHandler: ProxyHandler? ) : ChannelInitializer<Channel>() { override fun initChannel(ch: Channel) { if (proxyHandler != null) { ch.pipeline().addLast(proxyHandler) } ch.pipeline().addLast("httpCodec", HttpClientCodec()) ch.pipeline().addLast("proxyClientHandle", HttpProxyClientHandle(clientChannel)) } } open class HttpProxyClientHandle(private val clientChannel: Channel) : ChannelInboundHandlerAdapter() { private val serverHandle get() = clientChannel.pipeline().get(HttpProxyServerHandle::class.java) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { //客户端channel已关闭则不转发了 if (!clientChannel.isOpen) { ReferenceCountUtil.release(msg) return } when (msg) { is HttpResponse -> serverHandle.interceptPipeline.afterResponse(clientChannel, ctx.channel(), msg) is HttpContent -> serverHandle.interceptPipeline.afterResponse(clientChannel, ctx.channel(), msg) else -> clientChannel.writeAndFlush(msg) } } override fun channelUnregistered(ctx: ChannelHandlerContext) { ctx.channel().close() clientChannel.close() } override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) { ctx.channel().close() clientChannel.close() serverHandle.exceptionHandle.afterCatch(clientChannel, ctx.channel(), cause) } } open class HttpProxyServerHandle( val serverConfig: HttpProxyServerConfig, private val interceptInitializer: HttpProxyInterceptInitializer, private val proxyEntry: ProxyEntry?, val exceptionHandle: HttpProxyExceptionHandle ) : ChannelInboundHandlerAdapter() { private var channelFuture: ChannelFuture? = null private lateinit var host: String private var port: Int = 0 private var status = 0 private var requestList = mutableListOf<Any>() private var isConnected: Boolean = false lateinit var interceptPipeline: HttpProxyInterceptPipeline private set override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { if (msg is HttpRequest) { // 第一次建立连接取host和端口号和处理代理握手 if (status == 0) { val requestProto = ProtoUtil.getRequestProto(msg) if (requestProto == null) { // bad request ctx.channel().close() return } status = 1 this.host = requestProto.host this.port = requestProto.port if ("CONNECT".equals(msg.method().name(), ignoreCase = true)) {//建立代理握手 status = 2 val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpProxyServer.SUCCESS) ctx.writeAndFlush(response) ctx.channel().pipeline().remove("httpCodec") //fix issue #42 ReferenceCountUtil.release(msg) return } } interceptPipeline = buildPipeline() interceptPipeline.requestProto = ProtoUtil.RequestProto(host, port) //fix issue #27 if (msg.uri().indexOf("/") != 0) { val url = URL(msg.uri()) msg.uri = url.file } interceptPipeline.beforeRequest(ctx.channel(), msg) } else if (msg is HttpContent) { if (status != 2) { interceptPipeline.beforeRequest(ctx.channel(), msg) } else { ReferenceCountUtil.release(msg) status = 1 } } else { // ssl和websocket的握手处理 handleProxyData(ctx.channel(), msg, false) } } override fun channelUnregistered(ctx: ChannelHandlerContext) { channelFuture?.channel()?.close() ctx.channel().close() } override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) { channelFuture?.channel()?.close() ctx.channel().close() exceptionHandle.beforeCatch(ctx.channel(), cause) } private fun handleProxyData(channel: Channel, msg: Any, isHttp: Boolean) { if (channelFuture == null) { // connection异常 还有HttpContent进来,不转发 if (isHttp && msg !is HttpRequest) { return } // TODO: choose a external proxy from proxy pool here val proxyHandler = if (proxyEntry == null) null else ProxyHandleFactory.build(proxyEntry) /* 添加SSL client hello的Server Name Indication extension(SNI扩展) 有些服务器对于client hello不带SNI扩展时会直接返回Received fatal alert: handshake_failure(握手错误) 例如:https://cdn.mdn.mozilla.net/static/img/favicon32.7f3da72dcea1.png */ val requestProto = ProtoUtil.RequestProto(host, port) val channelInitializer = if (isHttp) HttpProxyInitializer(channel, requestProto, proxyHandler) else TunnelProxyInitializer(channel, proxyHandler) val bootstrap = Bootstrap() bootstrap.group(serverConfig.proxyLoopGroup) // 注册线程池 .channel(NioSocketChannel::class.java) // 使用NioSocketChannel来作为连接用的channel类 .handler(channelInitializer) if (proxyEntry != null) { // 代理服务器解析DNS和连接 bootstrap.resolver(NoopAddressResolverGroup.INSTANCE) } requestList = LinkedList() channelFuture = bootstrap.connect(host, port) // System.out.println("Connected to " + host + ":" + port); channelFuture?.addListener({ future: ChannelFuture -> if (future.isSuccess) { future.channel().writeAndFlush(msg) synchronized(requestList) { requestList.forEach { obj -> future.channel().writeAndFlush(obj) } requestList.clear() isConnected = true } } else { requestList.forEach { obj -> ReferenceCountUtil.release(obj) } requestList.clear() future.channel().close() channel.close() } } as ChannelFutureListener) } else { synchronized(requestList) { if (isConnected) { channelFuture!!.channel().writeAndFlush(msg) } else { requestList.add(msg) } } } } private fun buildPipeline(): HttpProxyInterceptPipeline { val proxyIntercept = object: HttpProxyIntercept() { override fun beforeRequest(clientChannel: Channel, httpRequest: HttpRequest, pipeline: HttpProxyInterceptPipeline) { handleProxyData(clientChannel, httpRequest, true) } override fun beforeRequest(clientChannel: Channel, httpContent: HttpContent, pipeline: HttpProxyInterceptPipeline) { handleProxyData(clientChannel, httpContent, true) } override fun afterResponse(clientChannel: Channel, proxyChannel: Channel, httpResponse: HttpResponse, pipeline: HttpProxyInterceptPipeline) { clientChannel.writeAndFlush(httpResponse) if (HttpHeaderValues.WEBSOCKET.toString() == httpResponse.headers().get(HttpHeaderNames.UPGRADE)) { // websocket转发原始报文 proxyChannel.pipeline().remove("httpCodec") clientChannel.pipeline().remove("httpCodec") } } override fun afterResponse(clientChannel: Channel, proxyChannel: Channel, httpContent: HttpContent, pipeline: HttpProxyInterceptPipeline) { clientChannel.writeAndFlush(httpContent) } } val interceptPipeline = HttpProxyInterceptPipeline(proxyIntercept) interceptInitializer.init(interceptPipeline) return interceptPipeline } } /** * http代理隧道,转发原始报文 */ open class TunnelProxyInitializer( private val clientChannel: Channel, private val proxyHandler: ProxyHandler? ) : ChannelInitializer<Channel>() { override fun initChannel(ch: Channel) { if (proxyHandler != null) { ch.pipeline().addLast(proxyHandler) } ch.pipeline().addLast(object : ChannelInboundHandlerAdapter() { override fun channelRead(ctx0: ChannelHandlerContext, msg0: Any) { clientChannel.writeAndFlush(msg0) } override fun channelUnregistered(ctx0: ChannelHandlerContext) { ctx0.channel().close() clientChannel.close() } override fun exceptionCaught(ctx0: ChannelHandlerContext, cause: Throwable) { ctx0.channel().close() clientChannel.close() val exceptionHandle = (clientChannel.pipeline() .get("serverHandle") as HttpProxyServerHandle).exceptionHandle exceptionHandle.afterCatch(clientChannel, ctx0.channel(), cause) } }) } } object ProxyHandleFactory { fun build(config: ProxyEntry): ProxyHandler { val proxyHandler: ProxyHandler val isAuth = config.user != null && config.pwd != null val inetSocketAddress = InetSocketAddress(config.host, config.port) when (config.proxyType) { ProxyType.HTTP -> if (isAuth) { proxyHandler = HttpProxyHandler(inetSocketAddress, config.user, config.pwd) } else { proxyHandler = HttpProxyHandler(inetSocketAddress) } ProxyType.SOCKS4 -> proxyHandler = Socks4ProxyHandler(inetSocketAddress) ProxyType.SOCKS5 -> if (isAuth) { proxyHandler = Socks5ProxyHandler(inetSocketAddress, config.user, config.pwd) } else { proxyHandler = Socks5ProxyHandler(inetSocketAddress) } } return proxyHandler } }
0
null
0
0
728a9c6dbe852edd686c55b234608abe7e9fb419
11,518
pulsar
Apache License 2.0
minchat-rest/src/main/kotlin/io/minchat/rest/service/CacheService.kt
MinChat-official
604,238,971
false
{"Kotlin": 394469}
// // THIS CLASS IS GENERATED BY THE generateCacheSerivce gradle task! // DO NOT MODIFY BY HAND! // package io.minchat.rest.service import io.minchat.common.entity.* import io.minchat.rest.MinchatRestClient import io.minchat.rest.entity.* /** * Allows fetching MinChat entities using a caching strategy. */ class CacheService( baseUrl: String, val minchatClient: MinchatRestClient ) : AbstractRestService(baseUrl, minchatClient.httpClient) { /** Up to how many entities of each type can be cached. */ var maxCacheSize = 100 val messageCache = mutableMapOf<Long, Message?>() val userCache = mutableMapOf<Long, User?>() val channelCache = mutableMapOf<Long, Channel?>() val channelgroupCache = mutableMapOf<Long, ChannelGroup?>() /** Gets a Message from messageCache. If [restFallback] is true, attempts to fetch the Message if it's absent in the cache. */ suspend fun getRawMessage(id: Long, restFallback: Boolean = true): Message? { val data = messageCache[id] if (data == null) { if (!restFallback) return null return minchatClient.getMessage(id).data.also { set(it) } } else { return data } } /** Gets a MinchatMessage from messageCache. If [restFallback] is true, attempts to fetch the MinchatMessage if it's absent in the cache. */ suspend fun getMessage(id: Long, restFallback: Boolean = true): MinchatMessage? = getRawMessage(id, restFallback)?.withClient(minchatClient) /** Gets a User from userCache. If [restFallback] is true, attempts to fetch the User if it's absent in the cache. */ suspend fun getRawUser(id: Long, restFallback: Boolean = true): User? { val data = userCache[id] if (data == null) { if (!restFallback) return null return minchatClient.getUser(id).data.also { set(it) } } else { return data } } /** Gets a MinchatUser from userCache. If [restFallback] is true, attempts to fetch the MinchatUser if it's absent in the cache. */ suspend fun getUser(id: Long, restFallback: Boolean = true): MinchatUser? = getRawUser(id, restFallback)?.withClient(minchatClient) /** Gets a Channel from channelCache. If [restFallback] is true, attempts to fetch the Channel if it's absent in the cache. */ suspend fun getRawChannel(id: Long, restFallback: Boolean = true): Channel? { val data = channelCache[id] if (data == null) { if (!restFallback) return null return minchatClient.getChannel(id).data.also { set(it) } } else { return data } } /** Gets a MinchatChannel from channelCache. If [restFallback] is true, attempts to fetch the MinchatChannel if it's absent in the cache. */ suspend fun getChannel(id: Long, restFallback: Boolean = true): MinchatChannel? = getRawChannel(id, restFallback)?.withClient(minchatClient) /** Gets a ChannelGroup from channelgroupCache. If [restFallback] is true, attempts to fetch the ChannelGroup if it's absent in the cache. */ suspend fun getRawChannelGroup(id: Long, restFallback: Boolean = true): ChannelGroup? { val data = channelgroupCache[id] if (data == null) { if (!restFallback) return null return minchatClient.getChannelGroup(id).data.also { set(it) } } else { return data } } /** Gets a MinchatChannelGroup from channelgroupCache. If [restFallback] is true, attempts to fetch the MinchatChannelGroup if it's absent in the cache. */ suspend fun getChannelGroup(id: Long, restFallback: Boolean = true): MinchatChannelGroup? = getRawChannelGroup(id, restFallback)?.withClient(minchatClient) /** Adds the Message to the messageCache, potentially overriding the previous version. */ fun set(entity: Message) { messageCache[entity.id] = entity } /** Adds the MinchatMessage to the messageCache, potentially overriding the previous version. */ fun set(entity: MinchatMessage) { messageCache[entity.id] = entity.data } /** Adds the User to the userCache, potentially overriding the previous version. */ fun set(entity: User) { userCache[entity.id] = entity } /** Adds the MinchatUser to the userCache, potentially overriding the previous version. */ fun set(entity: MinchatUser) { userCache[entity.id] = entity.data } /** Adds the Channel to the channelCache, potentially overriding the previous version. */ fun set(entity: Channel) { channelCache[entity.id] = entity } /** Adds the MinchatChannel to the channelCache, potentially overriding the previous version. */ fun set(entity: MinchatChannel) { channelCache[entity.id] = entity.data } /** Adds the ChannelGroup to the channelgroupCache, potentially overriding the previous version. */ fun set(entity: ChannelGroup) { channelgroupCache[entity.id] = entity } /** Adds the MinchatChannelGroup to the channelgroupCache, potentially overriding the previous version. */ fun set(entity: MinchatChannelGroup) { channelgroupCache[entity.id] = entity.data } }
0
Kotlin
0
3
8f70585146311efe9fc49e4e3b93eb8becb92cba
4,873
MinChat
Apache License 2.0
feature/main/src/main/java/com/t8rin/imagetoolboxlite/feature/main/presentation/components/settings/DragHandleWidthSettingItem.kt
T8RIN
767,600,774
false
{"Kotlin": 3806441}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.feature.settings.presentation.components import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.DragHandle import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Shape import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import ru.tech.imageresizershrinker.core.resources.R import ru.tech.imageresizershrinker.core.settings.presentation.LocalSettingsState import ru.tech.imageresizershrinker.core.ui.widget.controls.EnhancedSliderItem import ru.tech.imageresizershrinker.core.ui.widget.modifier.ContainerShapeDefaults import kotlin.math.roundToInt @Composable fun DragHandleWidthSettingItem( onValueChange: (Int) -> Unit, shape: Shape = ContainerShapeDefaults.centerShape, modifier: Modifier = Modifier .padding(horizontal = 8.dp) ) { val settingsState = LocalSettingsState.current var value by remember { mutableFloatStateOf(settingsState.dragHandleWidth.value) } EnhancedSliderItem( modifier = modifier, shape = shape, valueSuffix = " Dp", value = value, title = stringResource(R.string.drag_handle_width), icon = Icons.Rounded.DragHandle, onValueChange = { value = it.roundToInt().toFloat() onValueChange(it.roundToInt()) }, internalStateTransformation = { it.roundToInt() }, valueRange = 0f..128f ) }
5
Kotlin
90
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
2,480
ImageToolboxLite
Apache License 2.0
domene/src/main/kotlin/no/nav/tiltakspenger/meldekort/domene/Meldekortperiode.kt
navikt
487,246,438
false
{"Kotlin": 783873, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.meldekort.domene import arrow.core.NonEmptyList import no.nav.tiltakspenger.libs.periodisering.Periode import no.nav.tiltakspenger.libs.tiltak.TiltakstypeSomGirRett import java.time.DayOfWeek import java.time.LocalDate /** * saksbehandler/beslutter Dette er fremdeles til avklaring, men inntil videre aksepterer vi at saksbehandler og beslutter er like. * @property tiltakstype I MVP støtter vi kun ett tiltak, men på sikt kan vi ikke garantere at det er én til én mellom meldekortperiode og tiltakstype. */ data class Meldekortperiode( val verdi: NonEmptyList<Meldekortdag>, ) : List<Meldekortdag> by verdi { val fraOgMed: LocalDate = verdi.first().dato val tilOgMed: LocalDate = verdi.last().dato val periode: Periode = Periode(fraOgMed, tilOgMed) val tiltakstype: TiltakstypeSomGirRett = verdi.filterIsInstance<Meldekortdag.Tiltaksdag>().first().tiltakstype val meldekortId = verdi.first().meldekortId init { require(verdi.size == 14) { "En meldekortperiode må være 14 dager, men var ${verdi.size}" } require(verdi.map { it.dato }.toSet().size == verdi.size) { "Datoer må være unike" } require(verdi.first().dato.dayOfWeek == DayOfWeek.MONDAY) { "Utbetalingsperioden må starte på en mandag" } require(verdi.last().dato.dayOfWeek == DayOfWeek.SUNDAY) { "Utbetalingsperioden må slutte på en sønad" } verdi.forEachIndexed { index, dag -> require(verdi.first().dato.plusDays(index.toLong()) == dag.dato) { "Datoene må være sammenhengende og sortert, men var ${verdi.map { it.dato }}" } } require(verdi.filterIsInstance<Meldekortdag.Tiltaksdag>().size <= 5 * 2) { // TODO jah: Dette bør være en mer felles konstant. Kan også skrive en mer spesifikk sjekk per uke. "Det kan maks være 5*2 tiltaksdager i en meldekortperiode, men var ${verdi.filterIsInstance<Meldekortdag.Tiltaksdag>().size}" } require(verdi.filterIsInstance<Meldekortdag.Tiltaksdag>().all { it.tiltakstype == tiltakstype }) { "Alle tiltaksdager må ha samme tiltakstype" } require(verdi.all { it.meldekortId == meldekortId }) { "Alle dager må tilhøre samme meldekort, men var: ${verdi.map { it.meldekortId }}" } } }
10
Kotlin
0
1
63b6702ba616e70e219dbc37f19707f7a60ef7d5
2,311
tiltakspenger-vedtak
MIT License
sample/hack/app/main.kt
SubstanceMobile
87,648,548
false
{"Kotlin": 45823}
fun main(args: Array<String>) { // TODO: Replace with reflection demo.GtkDemoApp(args) }
0
Kotlin
0
0
e2b61dcb2c744a21f9f95eb6972480a554e9fea3
90
SDK
Apache License 2.0
kamp-view/src/test/kotlin/ch/leadrian/samp/kamp/view/base/TextViewTest.kt
Double-O-Seven
142,487,686
false
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
package ch.leadrian.samp.kamp.view.base import ch.leadrian.samp.kamp.core.api.constants.TextDrawCodes import ch.leadrian.samp.kamp.core.api.data.Colors import ch.leadrian.samp.kamp.core.api.entity.Player import ch.leadrian.samp.kamp.core.api.service.PlayerTextDrawService import ch.leadrian.samp.kamp.core.api.text.TextFormatter import ch.leadrian.samp.kamp.core.api.text.TextKey import ch.leadrian.samp.kamp.core.api.text.TextProvider import ch.leadrian.samp.kamp.view.ViewContext import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.util.Locale internal class TextViewTest { private lateinit var textView: TextView private val player = mockk<Player>() private val viewContext = mockk<ViewContext>() private val textProvider = mockk<TextProvider>() private val textFormatter = mockk<TextFormatter>() private val playerTextDrawService = mockk<PlayerTextDrawService>() @BeforeEach fun setUp() { textView = TextView(player, viewContext, textProvider, textFormatter, playerTextDrawService) } @Nested inner class ColorTests { @Test fun shouldBeInitializedWithWhite() { val color = textView.color assertThat(color) .isEqualTo(Colors.WHITE) } @Test fun shouldSetColor() { textView.color = Colors.PINK assertThat(textView.color) .isEqualTo(Colors.PINK) } @Test fun shouldSupplyColor() { textView.color { Colors.PINK } assertThat(textView.color) .isEqualTo(Colors.PINK) } } @Nested inner class BackgroundColorTests { @Test fun shouldBeInitializedWithBlack() { val backgroundColor = textView.backgroundColor assertThat(backgroundColor) .isEqualTo(Colors.BLACK) } @Test fun shouldSetBackgroundColor() { textView.backgroundColor = Colors.PINK assertThat(textView.backgroundColor) .isEqualTo(Colors.PINK) } @Test fun shouldSupplyBackgroundColor() { textView.backgroundColor { Colors.PINK } assertThat(textView.backgroundColor) .isEqualTo(Colors.PINK) } } @Nested inner class TextTests { private val locale = Locale.GERMANY @BeforeEach fun setUp() { every { player.locale } returns locale } @Test fun shouldBeInitializedWithWhite() { val text = textView.text assertThat(text) .isEqualTo(TextDrawCodes.EMPTY_TEXT) } @Test fun shouldSetText() { textView.text = "Hello there" assertThat(textView.text) .isEqualTo("Hello there") } @Test fun shouldSupplyText() { textView.text { locale -> "Hello there in $locale" } assertThat(textView.text) .isEqualTo("Hello there in de_DE") } @Test fun shouldSetTextToFormattedString() { every { textFormatter.format(locale, "Hi {0}, {1}", "there", 1234) } returns "Hi there, 1234" textView.setText("Hi {0}, {1}", "there", 1234) assertThat(textView.text) .isEqualTo("Hi there, 1234") } @Test fun shouldSetTextToProvidedText() { val textKey = TextKey("view.test") every { textProvider.getText(locale, textKey) } returns "Hi there" textView.setText(textKey) assertThat(textView.text) .isEqualTo("Hi there") } @Test fun shouldSetTextToFormattedProvidedText() { val textKey = TextKey("view.test") every { textProvider.getText(locale, textKey) } returns "Hi {0}, {1}" every { textFormatter.format(locale, "Hi {0}, {1}", "there", 1234) } returns "Hi there, 1234" textView.setText(textKey, "there", 1234) assertThat(textView.text) .isEqualTo("Hi there, 1234") } @Test fun shouldReplaceBlankTextWithEmptyTextDraw() { textView.text = " \n " val text = textView.text assertThat(text) .isEqualTo("_") } @Test fun shouldTrimToMaximumTextDrawTextLength() { textView.text = "x".repeat(2000) val text = textView.text assertThat(text) .isEqualToIgnoringCase("x".repeat(1023)) } @Test fun givenTextTransformerItShouldTransformText() { textView.textTransformer = TextTransformers.toUpperCase() textView.text = "Hi there" val text = textView.text assertThat(text) .isEqualTo("HI THERE") } } }
1
Kotlin
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
5,173
kamp
Apache License 2.0
app/src/main/java/com/anip/swamphacks/SponsorActivity.kt
swamphacks
112,042,979
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Kotlin": 25, "XML": 53, "Java": 7}
package com.anip.swamphacks import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.MenuItem import com.anip.swamphacks.adapter.RepresentativeAdapter import com.anip.swamphacks.helper.DatabaseHelper import com.anip.swamphacks.model.Reps import com.anip.swamphacks.model.Sponsor import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_sponsor.* import org.jetbrains.anko.db.classParser import org.jetbrains.anko.db.parseSingle import org.jetbrains.anko.db.select /** * Created by anip on 14/01/18. */ class SponsorActivity : AppCompatActivity() { lateinit var db : DatabaseHelper private var reps : RepresentativeAdapter? = null private var list : List<Reps>? = null lateinit var sponsor : Sponsor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sponsor) db = DatabaseHelper.Instance(this) // list = mutableListOf<Reps>() val name = intent.getStringExtra("name") db.use { sponsor = select("Sponsors").columns("name", "tier", "description", "link", "location", "logo").whereArgs("name = {name}", "name" to name).limit(1).exec { parseSingle(classParser()) } list = select("Reps").columns("name", "image","title").whereArgs("sponsor = {sponsor}", "sponsor" to sponsor.name).parseList(classParser()) println("reps size" + list) } supportActionBar!!.setDisplayHomeAsUpEnabled(true) title = name Picasso.with(this).load(sponsor.logoLink).into(logoLink) spName.text = sponsor.name // Log.i("logo",sponsor.logoLink) location.text = sponsor.location about.text = sponsor.description reps = RepresentativeAdapter(this, list!!) peoples.adapter = reps } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item!!.itemId){ android.R.id.home -> { onBackPressed() } } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
0
00be451eb7e8186021d49fa6fe2cf0920a75d216
2,169
2018-SwampHacks-Android
Apache License 2.0
net/craftventure/database/repository/WarpRepository.kt
Craftventure
770,049,457
false
{"Kotlin": 3656616, "Java": 684034}
package net.craftventure.database.repository import net.craftventure.database.generated.cvdata.Cvdata import net.craftventure.database.generated.cvdata.tables.daos.WarpDao import net.craftventure.database.generated.cvdata.tables.pojos.Warp import net.craftventure.database.generated.cvdata.tables.records.WarpRecord import org.jooq.Configuration class WarpRepository( configuration: Configuration ) : BaseIdRepository<WarpRecord, Warp, String>( WarpDao(configuration), shouldCache = true ) { fun findByName(name: String) = withDsl { dsl -> (dao as WarpDao).fetchOneById(name) } fun findCachedByName(name: String) = cachedItems.firstOrNull { it.id == name } fun deleteByNameSilent(name: String) = withDslIgnoreErrors(false) { dsl -> dsl.deleteFrom(table) .where(Cvdata.CVDATA.WARP.ID.eq(name)) .execute() == 1 } }
0
Kotlin
1
21
015687ff6687160835deacda57121480f542531b
888
open-plugin-parts
MIT License
api/type/type-builders/src/main/kotlin/org/rsmod/api/type/builders/obj/ObjBuilderResolver.kt
rsmod
293,875,986
false
{"Kotlin": 1817705}
package org.rsmod.api.type.builders.obj import jakarta.inject.Inject import kotlin.collections.get import org.rsmod.api.type.builders.TypeBuilder import org.rsmod.api.type.builders.resolver.TypeBuilderResolver import org.rsmod.api.type.builders.resolver.TypeBuilderResult import org.rsmod.api.type.builders.resolver.TypeBuilderResult.CachePackRequired import org.rsmod.api.type.builders.resolver.TypeBuilderResult.FullSuccess import org.rsmod.api.type.builders.resolver.TypeBuilderResult.NameNotFound import org.rsmod.api.type.builders.resolver.err import org.rsmod.api.type.builders.resolver.ok import org.rsmod.api.type.builders.resolver.update import org.rsmod.api.type.symbols.name.NameMapping import org.rsmod.game.type.TypeResolver import org.rsmod.game.type.obj.ObjTypeBuilder import org.rsmod.game.type.obj.ObjTypeList import org.rsmod.game.type.obj.UnpackedObjType public class ObjBuilderResolver @Inject constructor(private val types: ObjTypeList, private val nameMapping: NameMapping) : TypeBuilderResolver<ObjTypeBuilder, UnpackedObjType> { private val names: Map<String, Int> get() = nameMapping.objs override fun resolve( builders: TypeBuilder<ObjTypeBuilder, UnpackedObjType> ): List<TypeBuilderResult> = builders.cache.map { it.resolve() } private fun UnpackedObjType.resolve(): TypeBuilderResult { val internalId = names[internalNameGet] ?: return err(NameNotFound(internalNameGet)) val cacheType = types[internalId] TypeResolver[this] = internalId return if (cacheType != this) { update(CachePackRequired) } else { ok(FullSuccess) } } }
0
Kotlin
64
95
3ba446ed70bcde0870ef431e1a8527efc6837d6c
1,673
rsmod
ISC License
src/test/kotlin/io/github/projectmapk/jackson/module/kogera/_ported/test/github/Github42.kt
ProjectMapK
488,347,906
false
null
package io.github.projectmapk.jackson.module.kogera.zPorted.test.github import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.JsonMappingException import io.github.projectmapk.jackson.module.kogera.jacksonObjectMapper import io.github.projectmapk.jackson.module.kogera.readValue import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class TestGithub42_FailOnNullForPrimitives { data class OptionalIntRequiredBoolean(val optInt: Int = -1, val reqBool: Boolean) val mapper = jacksonObjectMapper().enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) @Test fun `optional primitive parameter defaulted if not in json when FAIL_ON_NULL_FOR_PRIMITIVES is true`() { val actualObj: OptionalIntRequiredBoolean = mapper.readValue( """ { "reqBool": false } """ ) assertEquals(OptionalIntRequiredBoolean(reqBool = false), actualObj) } @Test fun `Exception thrown if required primitive parameter not in json when FAIL_ON_NULL_FOR_PRIMITIVES is true`() { assertThrows<JsonMappingException> { mapper.readValue<OptionalIntRequiredBoolean>("""{"optInt": 2}""") } } @Test fun `optional parameter has json value if provided when FAIL_ON_NULL_FOR_PRIMITIVES is true`() { val actualObj: OptionalIntRequiredBoolean = mapper.readValue( """ { "optInt": 3, "reqBool": true } """ ) assertEquals(OptionalIntRequiredBoolean(3, true), actualObj) } }
8
Kotlin
3
89
7d9dbcd2fcdbc48631c01b51a919fe03ac6bb47e
1,676
jackson-module-kogera
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/CloudUploadTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/CloudUploadTwoTone") @file:JsNonModule package mui.icons.material @JsName("default") external val CloudUploadTwoTone: SvgIconComponent
12
null
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
218
kotlin-wrappers
Apache License 2.0
circuitx/effects/src/commonTest/kotlin/com/slack/circuitx/effects/ImpressionEffectTest.kt
slackhq
523,011,227
false
null
// Copyright (C) 2022 Slack Technologies, LLC // SPDX-License-Identifier: Apache-2.0 package com.slack.circuitx.effects import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import app.cash.molecule.RecompositionMode import app.cash.molecule.moleculeFlow import app.cash.turbine.test import com.slack.circuit.retained.CanRetainChecker import com.slack.circuit.retained.LocalCanRetainChecker import com.slack.circuit.retained.LocalRetainedStateRegistry import com.slack.circuit.retained.RetainedStateRegistry import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest /** Expected unit tests for [ImpressionEffect] and [LaunchedImpressionEffect]. */ expect class ImpressionEffectTest : ImpressionEffectTestShared { @Test override fun recreateImpressionEffect() @Test override fun inputChangeImpressionEffect() @Test override fun recreateLaunchedImpressionEffect() @Test override fun inputChangeLaunchedImpressionEffect() } /** Shared unit tests for [ImpressionEffect] and [LaunchedImpressionEffect]. */ internal interface ImpressionEffectTestShared { @Test fun recreateImpressionEffect() @Test fun inputChangeImpressionEffect() @Test fun recreateLaunchedImpressionEffect() @Test fun inputChangeLaunchedImpressionEffect() } /** Shared implementation of unit tests for [ImpressionEffect] and [LaunchedImpressionEffect]. */ @OptIn( ExperimentalCoroutinesApi::class // For advanceUntilIdle() ) @Ignore // Only run the actual uses of this. internal class ImpressionEffectTestSharedImpl : ImpressionEffectTestShared { private val registry = RetainedStateRegistry() private val composed = MutableStateFlow(true) override fun recreateImpressionEffect() { runTest { var count = 0 moleculeFlow(RecompositionMode.Immediate) { setRetainedContent { ImpressionEffect { count++ } } } .test { // Verify the impression block was called once assertEquals(1, count) // Simulate retained leaving and joining the composition recreate() // Verify the impression block wasn't called again assertEquals(1, count) cancelAndIgnoreRemainingEvents() } } } override fun inputChangeImpressionEffect() { runTest { val inputs = MutableStateFlow("init") var count = 0 moleculeFlow(RecompositionMode.Immediate) { setRetainedContent { val input by inputs.collectAsState() ImpressionEffect(input) { count++ } } } .test { // Verify the impression block was called once assertEquals(1, count) // Change the input inputs.value = "new" advanceUntilIdle() // Verify the impression block was called again assertEquals(2, count) cancelAndIgnoreRemainingEvents() } } } override fun recreateLaunchedImpressionEffect() { runTest { var count = 0 moleculeFlow(RecompositionMode.Immediate) { setRetainedContent { LaunchedImpressionEffect { delay(1) count++ } } } .test { // Advance over the delay and execute advanceTimeBy(2) // Verify the impression block was called once assertEquals(1, count) // Simulate retained leaving and joining the composition recreate() // Advance over the delay and execute advanceTimeBy(2) // Verify the impression block wasn't called again assertEquals(1, count) cancelAndIgnoreRemainingEvents() } } } override fun inputChangeLaunchedImpressionEffect() { runTest { val inputs = MutableStateFlow("init") var count = 0 moleculeFlow(RecompositionMode.Immediate) { setRetainedContent { val input by inputs.collectAsState() LaunchedImpressionEffect(input) { delay(1) count++ } } } .test { // Advance over the delay and execute advanceTimeBy(2) // Verify the impression block was called once assertEquals(1, count) // Change the input inputs.value = "new" // Advance over the delay and execute advanceTimeBy(2) // Verify the impression block was called again assertEquals(2, count) cancelAndIgnoreRemainingEvents() } } } /** Simulating a screen with this. */ @Composable private fun setRetainedContent(content: @Composable () -> Unit = {}) { CompositionLocalProvider( LocalRetainedStateRegistry provides registry, LocalCanRetainChecker provides CanRetainChecker.Always, ) { val isCompose by composed.collectAsState(initial = true) if (isCompose) { content() } } } /** Simulate a retained leaving and joining of the composition. */ private fun recreate() { composed.value = false registry.saveAll() composed.value = true } }
30
null
72
1,472
14900fea0d5075f0197b47791befdb422e700e8e
5,521
circuit
Apache License 2.0
samples/r2dbc-sample/src/main/kotlin/me/yaman/can/database/r2dbcsample/repository/CityRepository.kt
canyaman
420,810,098
false
{"Kotlin": 18620}
package me.yaman.can.database.r2dbcsample.repository import me.yaman.can.database.r2dbcsample.entity.City import org.springframework.data.repository.reactive.ReactiveCrudRepository import org.springframework.stereotype.Repository import reactor.core.publisher.Mono @Repository interface CityRepository: ReactiveCrudRepository<City, Long> { fun findByName(name: String): Mono<City?> }
1
Kotlin
2
8
d0abfbe04223e80863cb83ccb1a0df3c3efb8ccb
389
spring-boot-webflux-h2-console
MIT License
sdk/src/commonMain/kotlin/io/timemates/sdk/files/types/value/FileId.kt
timemates
575,534,072
false
null
package io.timemates.sdk.files.types.value import io.timemates.sdk.common.constructor.CreationFailure import io.timemates.sdk.common.constructor.Factory @JvmInline public value class FileId private constructor(public val string: String) { public companion object : Factory<FileId, String>() { override fun create(input: String): Result<FileId> { return when { input.isBlank() -> Result.failure(CreationFailure.ofBlank()) else -> Result.success(FileId(input)) } } } }
2
Kotlin
0
9
ede0c538935ec8f2c452d7cfb4d6747a1a1c81c7
548
sdk
MIT License
src/main/kotlin/com/martmists/ynet/block/ConnectorBlock.kt
Flamarine
387,081,749
false
{"Kotlin": 59094}
package com.martmists.ynet.block import com.martmists.ynet.YNetMod import com.martmists.ynet.network.Network import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.block.ConnectingBlock import net.minecraft.entity.LivingEntity import net.minecraft.item.ItemPlacementContext import net.minecraft.item.ItemStack import net.minecraft.state.StateManager import net.minecraft.state.property.BooleanProperty import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Direction import net.minecraft.world.BlockView import net.minecraft.world.World import net.minecraft.world.WorldAccess import java.util.* class ConnectorBlock(settings: Settings?) : ConnectingBlock(0.1875f, settings) { companion object { private val NORTH_CABLE = BooleanProperty.of("north_cable") private val EAST_CABLE = BooleanProperty.of("east_cable") private val SOUTH_CABLE = BooleanProperty.of("south_cable") private val WEST_CABLE = BooleanProperty.of("west_cable") private val UP_CABLE = BooleanProperty.of("up_cable") private val DOWN_CABLE = BooleanProperty.of("down_cable") private val CABLE_FACING_PROPERTIES: MutableMap<Direction, BooleanProperty> = EnumMap(Direction::class.java) init { CABLE_FACING_PROPERTIES[Direction.NORTH] = NORTH_CABLE CABLE_FACING_PROPERTIES[Direction.EAST] = EAST_CABLE CABLE_FACING_PROPERTIES[Direction.SOUTH] = SOUTH_CABLE CABLE_FACING_PROPERTIES[Direction.WEST] = WEST_CABLE CABLE_FACING_PROPERTIES[Direction.UP] = UP_CABLE CABLE_FACING_PROPERTIES[Direction.DOWN] = DOWN_CABLE } } override fun appendProperties(builder: StateManager.Builder<Block, BlockState>) { builder.add(NORTH, EAST, SOUTH, WEST, UP, DOWN, NORTH_CABLE, EAST_CABLE, SOUTH_CABLE, WEST_CABLE, UP_CABLE, DOWN_CABLE) } override fun getPlacementState(ctx: ItemPlacementContext): BlockState { return withConnectionProperties(ctx.world, ctx.blockPos) } override fun neighborUpdate(state: BlockState, world: World, pos: BlockPos, block: Block, fromPos: BlockPos, notify: Boolean) { super.neighborUpdate(state, world, pos, block, fromPos, notify) val x = withConnectionProperties(world, pos) if (state != x) { world.setBlockState(pos, x) } } override fun getStateForNeighborUpdate(state: BlockState, facing: Direction, neighborState: BlockState, world: WorldAccess, pos: BlockPos, neighborPos: BlockPos): BlockState { return if (!state.canPlaceAt(world, pos)) { world.blockTickScheduler.schedule(pos, this, 1) super.getStateForNeighborUpdate(state, facing, neighborState, world, pos, neighborPos) } else { state.with(FACING_PROPERTIES[facing], YNetMod.shouldConnect(world as World, neighborPos)) .with(CABLE_FACING_PROPERTIES[facing], YNetMod.shouldConnectCable(world, neighborPos)) } } fun withConnectionProperties(world: BlockView, pos: BlockPos): BlockState { return defaultState .with(DOWN, YNetMod.shouldConnect(world as World, pos.down())) .with(UP, YNetMod.shouldConnect(world, pos.up())) .with(NORTH, YNetMod.shouldConnect(world, pos.north())) .with(EAST, YNetMod.shouldConnect(world, pos.east())) .with(SOUTH, YNetMod.shouldConnect(world, pos.south())) .with(WEST, YNetMod.shouldConnect(world, pos.west())) .with(DOWN_CABLE, YNetMod.shouldConnectCable(world, pos.down())) .with(UP_CABLE, YNetMod.shouldConnectCable(world, pos.up())) .with(NORTH_CABLE, YNetMod.shouldConnectCable(world, pos.north())) .with(EAST_CABLE, YNetMod.shouldConnectCable(world, pos.east())) .with(SOUTH_CABLE, YNetMod.shouldConnectCable(world, pos.south())) .with(WEST_CABLE, YNetMod.shouldConnectCable(world, pos.west())) } override fun onBroken(world: WorldAccess, pos: BlockPos, state: BlockState) { Network.removeConnector(pos) } override fun onPlaced(world: World, pos: BlockPos, state: BlockState, placer: LivingEntity?, itemStack: ItemStack) { Network.addConnector(world, pos) val x = withConnectionProperties(world, pos) if (state != x) { world.setBlockState(pos, x) } } init { defaultState = getStateManager().defaultState .with(NORTH, false) .with(EAST, false) .with(SOUTH, false) .with(WEST, false) .with(UP, false) .with(DOWN, false) .with(NORTH_CABLE, false) .with(EAST_CABLE, false) .with(SOUTH_CABLE, false) .with(WEST_CABLE, false) .with(UP_CABLE, false) .with(DOWN_CABLE, false) } }
0
Kotlin
0
0
4ecbd5b80a223c2b50a809da35d1f55f172d8626
5,012
YNet
MIT License
src/main/kotlin/eliminationTreiberStack/EliminationArray.kt
tepa46
763,784,345
false
{"Kotlin": 10126}
package eliminationTreiberStack import kotlin.random.Random const val EXCHANGE_ATTEMPTS = 10 class EliminationArray<T>(private val capacity: Int) { private val exchanger = Array(capacity) { _ -> Exchanger<T>(EXCHANGE_ATTEMPTS) } fun visit(value: T?): Result<T?> { val slot = Random.nextInt(capacity) return exchanger[slot].exchange(value) } }
0
Kotlin
0
0
079f4f68ec3dcbe982c3924d152356c711095d34
376
parallel-programming
MIT License
neopop/src/main/java/club/cred/neopop/popButton/PopDrawable.kt
CRED-CLUB
498,671,676
false
{"Kotlin": 135999}
/* * * * Copyright 2022 Dreamplug Technologies Private Limited * * 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 club.cred.neopop.popButton import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.Rect import android.graphics.RectF import android.graphics.drawable.Drawable import android.util.Size import androidx.core.graphics.withClip import club.cred.neopop.common.NeoButtonDrawableInteractor import club.cred.neopop.common.ShimmerAnimationHelper import club.cred.neopop.common.createFillPaint import club.cred.neopop.common.drawStroke import club.cred.neopop.common.translateWith import club.cred.neopop.popButton.NeoPopGeometry.Companion.DEFAULT_STROKE_WIDTH import kotlin.math.roundToInt import kotlin.math.sqrt class PopDrawable( data: PopFrameLayoutStyle = PopFrameLayoutStyle() ) : Drawable(), NeoButtonDrawableInteractor { var popStyleData: PopFrameLayoutStyle = data set(value) { field = value topShadowPaint.color = popStyleData.topSurfaceColor leftShadowPaint.color = popStyleData.leftSurfaceColor bottomShadowPaint.color = popStyleData.bottomSurfaceColor rightShadowPaint.color = popStyleData.rightSurfaceColor centerCardPaint.color = popStyleData.centerSurfaceColor shimmerColor.color = popStyleData.shimmerColor shimmerAnimationHelper.repeatDelay = popStyleData.shimmerRepeatDelay shimmerAnimationHelper.startDelay = popStyleData.shimmerStartDelay invalidateSelf() } internal val isShimmerAnimating: Boolean get() = shimmerAnimationHelper.isShimmerAnimating private val topShadowPaint = createFillPaint(popStyleData.topSurfaceColor) private val leftShadowPaint = createFillPaint(popStyleData.leftSurfaceColor) private val bottomShadowPaint = createFillPaint(popStyleData.bottomSurfaceColor) private val rightShadowPaint = createFillPaint(popStyleData.rightSurfaceColor) private val centerCardPaint = createFillPaint(popStyleData.centerSurfaceColor) private val shimmerColor = createFillPaint(popStyleData.shimmerColor).apply { isAntiAlias = true } private fun createStrokePaint(strokeColor: Int): Paint = Paint().apply { color = strokeColor strokeWidth = DEFAULT_STROKE_WIDTH } private lateinit var neoPopGeometry: NeoPopGeometry private val shimmerAnimationHelper by lazy { ShimmerAnimationHelper( popStyleData.shimmerDuration, this, ).apply { repeatDelay = popStyleData.shimmerRepeatDelay startDelay = popStyleData.shimmerStartDelay } } private var isDrawableEnabled = false set(value) { if (field != value) { field = value shimmerAnimationHelper.isDrawableEnabled = value } } private var dx = 0f private var dy = 0f private var pressFraction = 0f private var shimmerDx = 0f private var showShimmer = false override fun onAnimate(dx: Float, dy: Float) { this.dx = dx this.dy = dy } override fun onStrokeWidthAnimate(strokeWidthValue: Float) { this.pressFraction = strokeWidthValue } override fun onShimmerAnimation(animatedValue: Float, animatedPercentage: Float) { shimmerDx = animatedValue invalidateSelf() } override fun onBoundsChange(bounds: Rect?) { super.onBoundsChange(bounds) if (bounds == null) return neoPopGeometry = NeoPopGeometry( size = Size(bounds.width(), bounds.height()), totalDepth = popStyleData.depth.roundToInt().toFloat(), clipRight = !popStyleData.isRightSurfaceVisible, clipBottom = !popStyleData.isBottomSurfaceVisible, viewBoundRect = bounds, isBottomSheet = popStyleData.isBottomSheetSurface, shimmerWidth = popStyleData.shimmerWidth, drawFullWidth = popStyleData.drawFullWidth, drawFullHeight = popStyleData.drawFullHeight ) if (popStyleData.hasShimmer) { shimmerAnimationHelper.width = (bounds.width() + neoPopGeometry.shimmerMovePathAdjustment.roundToInt()) } } override fun draw(canvas: Canvas) { if (!::neoPopGeometry.isInitialized) { return } canvas.clipPop { if (popStyleData.isBottomSheetSurface || dx > 0 || dy > 0) { if (popStyleData.isLeftSurfaceVisible) { drawPath(neoPopGeometry.startShadow.fullOutline, leftShadowPaint) } if (popStyleData.isTopSurfaceVisible) { drawPath(neoPopGeometry.topShadow.fullOutline, topShadowPaint) } } translateWith(dx, dy) { if (popStyleData.isRightSurfaceVisible) { drawPath(neoPopGeometry.endShadow.fullOutline, rightShadowPaint) } if (popStyleData.isBottomSurfaceVisible && !popStyleData.isBottomSheetSurface) { drawPath( neoPopGeometry.bottomShadow.fullOutline, bottomShadowPaint ) } drawPath(neoPopGeometry.mainSurface.fullOutline, centerCardPaint) if (popStyleData.hasShimmer && showShimmer) { withClip(neoPopGeometry.mainSurface.fullOutline) { drawShimmer(this) } } drawEdges(this) } if (popStyleData.isStrokedButton) { drawConstantEdges(this) } } } private fun drawConstantEdges(canvas: Canvas) { popStyleData.surfaceStrokeColors?.rightSurfaceStrokeColors?.rightColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke5, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.bottomSurfaceStrokeColors?.bottomColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke6, createStrokePaint(it)) } } private fun drawShimmer(canvas: Canvas) { canvas.translateWith(shimmerDx, 0f) { canvas.drawPath(neoPopGeometry.shimmerPath.fullOutline, shimmerColor) canvas.drawPath(neoPopGeometry.thinShimmer.fullOutline, shimmerColor) } } fun startShimmer() { if (popStyleData.hasShimmer) { showShimmer = true shimmerAnimationHelper.startShimmer() } } fun stopShimmer(stopImmediate: Boolean = false, onEnd: (() -> Unit)? = null) { if (popStyleData.hasShimmer) { shimmerAnimationHelper.stopShimmer(stopImmediate) { showShimmer = false onEnd?.invoke() } } } private fun drawEdges(canvas: Canvas) { val slantedLineStrokeWidth = (DEFAULT_STROKE_WIDTH * (1 - pressFraction)) + (pressFraction * DEFAULT_STROKE_WIDTH / SQRT_2) val slantedLineStrokeWidthSqrt = slantedLineStrokeWidth / (SQRT_2 * 2) popStyleData.surfaceStrokeColors?.centerSurfaceStrokeColors?.bottomColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke1, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.centerSurfaceStrokeColors?.rightColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke2, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.centerSurfaceStrokeColors?.topColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke3, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.rightSurfaceStrokeColors?.topColor?.let { if (it != Int.MIN_VALUE) canvas.drawLine( neoPopGeometry.endShadow.leftTop.x - slantedLineStrokeWidthSqrt, neoPopGeometry.endShadow.leftTop.y + slantedLineStrokeWidthSqrt, neoPopGeometry.endShadow.rightTop.x - slantedLineStrokeWidthSqrt, neoPopGeometry.endShadow.rightTop.y + slantedLineStrokeWidthSqrt, Paint().apply { color = it strokeWidth = slantedLineStrokeWidth } ) } popStyleData.surfaceStrokeColors?.rightSurfaceStrokeColors?.rightColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke5, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.bottomSurfaceStrokeColors?.bottomColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke6, createStrokePaint(it)) } popStyleData.surfaceStrokeColors?.bottomSurfaceStrokeColors?.leftColor?.let { if (it != Int.MIN_VALUE) canvas.drawLine( neoPopGeometry.bottomShadow.leftBottom.x + slantedLineStrokeWidthSqrt, neoPopGeometry.bottomShadow.leftBottom.y - slantedLineStrokeWidthSqrt, neoPopGeometry.bottomShadow.leftTop.x + slantedLineStrokeWidthSqrt, neoPopGeometry.bottomShadow.leftTop.y - slantedLineStrokeWidthSqrt, Paint().apply { color = it strokeWidth = slantedLineStrokeWidth } ) } popStyleData.surfaceStrokeColors?.centerSurfaceStrokeColors?.leftColor?.let { if (it != Int.MIN_VALUE) canvas.drawStroke(neoPopGeometry.stroke8, createStrokePaint(it)) } } override fun onStateChange(state: IntArray?): Boolean { isDrawableEnabled = !( state?.contains(-android.R.attr.state_enabled) == true || state?.contains(android.R.attr.state_enabled) == false ) return super.onStateChange(state) } override fun isStateful(): Boolean { return true } private inline fun Canvas.clipPop(crossinline block: Canvas.() -> Unit) { if (neoPopGeometry.clipPath != null) { translateWith( neoPopGeometry.viewBoundRect.left.toFloat(), neoPopGeometry.viewBoundRect.top.toFloat() ) { clipPath(neoPopGeometry.clipPath!!) block() } } else { clipRect(RectF(neoPopGeometry.viewBoundRect)) translateWith( neoPopGeometry.viewBoundRect.left.toFloat(), neoPopGeometry.viewBoundRect.top.toFloat() ) { block() } } } override fun setAlpha(alpha: Int) { } override fun setColorFilter(colorFilter: ColorFilter?) { } override fun getOpacity(): Int = PixelFormat.TRANSLUCENT companion object { val SQRT_2 = sqrt(2f) } }
5
Kotlin
33
275
67e62066f6152f83d3e429da1e0de9501e817a24
11,855
neopop-android
Apache License 2.0
compiler/testData/diagnostics/tests/annotations/withUseSiteTarget/prohibitUseSiteGetTargetAnnotationsOn.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL // LANGUAGE: +ProhibitUseSiteGetTargetAnnotations annotation class Ann <!REPEATED_ANNOTATION!>@get:Ann<!> <!REPEATED_ANNOTATION!>@set:Ann<!> @Ann var mutableProperty: Int = 42 <!INAPPLICABLE_TARGET_ON_PROPERTY!>@get:Ann<!> get <!INAPPLICABLE_TARGET_ON_PROPERTY!>@set:Ann<!> set <!REPEATED_ANNOTATION!>@get:Ann<!> <!REPEATED_ANNOTATION!>@set:Ann<!> @Ann var mutableProperty_AnnWithoutTarget: Int = 42 @Ann get @Ann set <!REPEATED_ANNOTATION!>@get:Ann<!> @Ann val immutableProperty: Int = 42 <!INAPPLICABLE_TARGET_ON_PROPERTY!>@get:Ann<!> get <!REPEATED_ANNOTATION!>@get:Ann<!> @Ann val immutableProperty_AnnWithoutTarget: Int = 42 @Ann get
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
684
kotlin
Apache License 2.0
projects/core/src/main/kotlin/queue-jvm.kt
mplatvoet
28,311,735
false
null
/* * Copyright (c) 2015 Mark Platvoet<mplatvoet@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * THE SOFTWARE. */ package nl.komponents.kovenant import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicInteger class NonBlockingWorkQueue<V : Any>() : BlockingSupportWorkQueue<V>() { private val queue = ConcurrentLinkedQueue<V>() override fun tryPoll(): V? = queue.poll() override fun tryOffer(elem: V): Boolean = queue.offer(elem) override fun size(): Int = queue.size override fun isEmpty(): Boolean = queue.isEmpty() override fun isNotEmpty(): Boolean = !isEmpty() override fun remove(elem: Any?): Boolean = queue.remove(elem) } abstract class BlockingSupportWorkQueue<V : Any>() : WorkQueue<V> { private val waitingThreads = AtomicInteger(0) //yes I could also use a ReentrantLock with a Condition but //introduces quite a lot of overhead and the semantics //are just the same private val mutex = Object() abstract fun tryPoll(): V? abstract fun tryOffer(elem: V): Boolean override fun offer(elem: V): Boolean { val added = tryOffer(elem) if (added && waitingThreads.get() > 0) { synchronized(mutex) { //maybe there aren't any threads waiting or //there isn't anything in the queue anymore //just notify, we've got this far mutex.notifyAll() } } return added } override fun poll(block: Boolean, timeoutMs: Long): V? { if (!block) return tryPoll() val elem = tryPoll() if (elem != null) return elem waitingThreads.incrementAndGet() try { return if (timeoutMs > -1L) { blockingPoll(timeoutMs) } else { blockingPoll() } } finally { waitingThreads.decrementAndGet() } } private fun blockingPoll(): V? { synchronized(mutex) { while (true) { val retry = tryPoll() if (retry != null) return retry mutex.wait() } } throw KovenantException("unreachable") } private fun blockingPoll(timeoutMs: Long): V? { val deadline = System.currentTimeMillis() + timeoutMs synchronized(mutex) { while (true) { val retry = tryPoll() if (retry != null || System.currentTimeMillis() >= deadline) return retry mutex.wait(timeoutMs) } } throw KovenantException("unreachable") } }
10
null
31
659
36ff896ed8ea80edbf28706a0f50b6bac3777d78
3,602
kovenant
MIT License
zircon.jvm/src/main/kotlin/org/hexworks/zircon/api/Modifiers.kt
objectprogr
158,966,930
true
{"Kotlin": 1031505, "Java": 16867, "CSS": 1525}
package org.hexworks.zircon.api import org.hexworks.zircon.api.builder.modifier.BorderBuilder import org.hexworks.zircon.api.modifier.Border import org.hexworks.zircon.api.modifier.Glow import org.hexworks.zircon.api.modifier.Modifier import org.hexworks.zircon.api.modifier.SimpleModifiers.* import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic /** * Represents the built-in modifiers supported by zircon. */ object Modifiers { @JvmStatic fun underline(): Modifier = Underline @JvmStatic fun blink(): Modifier = Blink @JvmStatic fun crossedOut(): Modifier = CrossedOut @JvmStatic fun verticalFlip(): Modifier = VerticalFlip @JvmStatic fun horizontalFlip(): Modifier = HorizontalFlip @JvmStatic fun hidden(): Modifier = Hidden @JvmStatic @JvmOverloads fun glow(radius: Float = 5.0f): Modifier = Glow(radius) /** * Shorthand for the default border which is: * - a simple border * - on all sides (top, right, bottom, left) * @see BorderBuilder if you want to create custom borders */ @JvmStatic fun border(): Border = BorderBuilder.newBuilder().build() }
0
Kotlin
0
0
ba53ee6442988ee0f047c43636dfd711f374093b
1,168
zircon
MIT License
src/main/kotlin/io/github/hc1839/crul/math/stat/fitting/LossStatistic.kt
hc1839
724,383,874
false
{"Kotlin": 541316}
package io.github.hc1839.crul.math.stat.fitting import org.apache.commons.math3.stat.descriptive.UnivariateStatistic /** * Statistic of the values of a loss function. */ interface LossStatistic : UnivariateStatistic { /** * Loss function. * * @param predicted * Predicted value. * * @param observed * Observed value. * * @return * Value of the cost. */ fun lossFunction(predicted: Double, observed: Double): Double /** * Evaluates the statistic of the loss function over paired predicted and * observed values. * * @param predObsValues * Non-empty list of pairs of predicted and observed values. * * @return * Value of the statistic applied to the loss function over * `predObsValues`. */ fun evaluatePredObsValues( predObsValues: List<Pair<Double, Double>> ): Double { if (predObsValues.isEmpty()) { throw IllegalArgumentException( "List of pairs of predicted and observed values is empty." ) } return evaluate( predObsValues.map { (pred, obs) -> lossFunction(pred, obs) }.toDoubleArray() ) } /** * Evaluates the statistic of an array of values of the loss function. * * @param values * Non-empty array of values of the loss function. * * @return * Value of the statistic applied to `values`. */ override fun evaluate(values: DoubleArray): Double { if (values.isEmpty()) { throw IllegalArgumentException( "Array of values of the loss function is empty." ) } return evaluate(values, 0, values.count()) } /** * Evaluates the statistic over specified elements of an array of values * of the loss function. * * @param values * Non-empty array of values of the loss function. * * @param begin * Index of the first element to include. * * @param length * Number of elements to include. * * @return * Value of the statistic applied to the included elements of * `values`. */ abstract override fun evaluate( values: DoubleArray, begin: Int, length: Int ): Double }
0
Kotlin
0
0
736b3c8377ca2f2f4a4e86fde6312e50b7ea2505
2,435
crul
Apache License 2.0
misk-crypto/src/main/kotlin/misk/crypto/pgp/internal/PgpEncrypterProvider.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.crypto.pgp.internal import com.google.inject.Provider import misk.crypto.KeyAlias import misk.crypto.KeyReader import misk.crypto.PgpEncrypterManager import misk.crypto.pgp.PgpEncrypter import misk.crypto.pgp.RealPgpEncrypter import org.bouncycastle.openpgp.PGPPublicKey import org.bouncycastle.openpgp.PGPPublicKeyRingCollection import org.bouncycastle.openpgp.PGPUtil import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator import java.io.BufferedInputStream import jakarta.inject.Inject class PgpEncrypterProvider( private val alias: KeyAlias ) : Provider<PgpEncrypter>, KeyReader() { @Inject private lateinit var pgpEncrypterManager: PgpEncrypterManager override fun get(): PgpEncrypter { val key = getRawKey(alias) val keyIn = BufferedInputStream(key.encrypted_key!!.value.byteInputStream()) val pgpPub = PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn), JcaKeyFingerprintCalculator()) // While there may be several subkeys we want specifically the subkey for encryption. var encryptionKey: PGPPublicKey? = null pgpPub.keyRings.next().publicKeys.forEach { if (it.isEncryptionKey) { encryptionKey = it } } if (encryptionKey == null) { error("no public key suitable for encryption was found") } return RealPgpEncrypter(encryptionKey!!).also { pgpEncrypterManager[key.key_name] = it } } }
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
1,430
misk
Apache License 2.0
app/src/main/java/com/boringdroid/systemui/utils/IconPackHelper.kt
openfde
777,502,927
false
{"Kotlin": 302347, "Java": 116706, "C++": 8520, "CMake": 1647, "AIDL": 1167}
package com.boringdroid.systemui.utils import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.SharedPreferences import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.content.res.Resources import android.content.res.XmlResourceParser import android.graphics.drawable.Drawable import android.text.TextUtils import android.widget.Toast import androidx.core.content.res.ResourcesCompat import androidx.preference.PreferenceManager import com.boringdroid.systemui.Log import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory import java.io.IOException import java.io.InputStream import java.lang.reflect.Field import java.util.Locale class IconPackHelper { // Holds package/class -> drawable private var mIconPackResources: Map<String, String?>? private var mContext: Context? = null private var mLoadedIconPackName: String? = null private var mLoadedIconPackResource: Resources? = null var mIconUpon: Drawable? = null var mIconMask: Drawable? = null private val mIconBackList: MutableList<Drawable> private val mIconBackStrings: MutableList<String> var mIconScale = 0f private var mCurrentIconPack: String? = "" private var mLoading = false init { mIconPackResources = HashMap() mIconBackList = ArrayList() mIconBackStrings = ArrayList() } private fun setContext(context: Context?) { mContext = context } private fun getDrawableForName(name: String): Drawable? { if (isIconPackLoaded) { val item = mIconPackResources!![name] if (!TextUtils.isEmpty(item)) { val id = getResourceIdForDrawable(item) if (id != 0) { return mLoadedIconPackResource!!.getDrawable(id) } } } return null } private fun getDrawableWithName(name: String): Drawable? { if (isIconPackLoaded) { val id = getResourceIdForDrawable(name) if (id != 0) { return mLoadedIconPackResource!!.getDrawable(id) } } return null } @Throws(XmlPullParserException::class, IOException::class) private fun loadResourcesFromXmlParser( parser: XmlPullParser, iconPackResources: MutableMap<String, String?> ) { while (parser.next() != XmlPullParser.END_DOCUMENT) { if (parser.eventType != XmlPullParser.START_TAG) { continue } val name = parser.name if (name == "item") { var component = parser.getAttributeValue(null, "component") val drawable = parser.getAttributeValue(null, "drawable") // Validate component/drawable exist if (TextUtils.isEmpty(component) || TextUtils.isEmpty(drawable)) { continue } // Validate format/length of component if (!component.startsWith("ComponentInfo{") || !component.endsWith("}") || component.length < 16) { continue } // Sanitize stored value component = component.substring(14, component.length - 1) if (!component.contains("/")) { // Package icon reference iconPackResources[component] = drawable } else { val componentName = ComponentName.unflattenFromString(component) if (componentName != null) { iconPackResources[componentName.packageName] = drawable iconPackResources[component] = drawable } } continue } if (name.equals(ICON_BACK_TAG, ignoreCase = true)) { val icon = parser.getAttributeValue(null, "img") if (icon == null) { for (i in 0 until parser.attributeCount) { mIconBackStrings.add(parser.getAttributeValue(i)) } } continue } if (name.equals(ICON_MASK_TAG, ignoreCase = true) || name.equals( ICON_UPON_TAG, ignoreCase = true ) ) { var icon = parser.getAttributeValue(null, "img") if (icon == null) { if (parser.attributeCount > 0) { icon = parser.getAttributeValue(0) } } iconPackResources[parser.name.lowercase(Locale.getDefault())] = icon continue } if (name.equals(ICON_SCALE_TAG, ignoreCase = true)) { var factor = parser.getAttributeValue(null, "factor") if (factor == null) { if (parser.attributeCount > 0) { factor = parser.getAttributeValue(0) } } if (factor != null) { iconPackResources[parser.name.lowercase(Locale.getDefault())] = factor } } } } private fun loadIconPack() { val packageName = mCurrentIconPack mIconBackList.clear() mIconBackStrings.clear() if (TextUtils.isEmpty(packageName)) { return } mLoading = true mIconPackResources = getIconPackResourcesNew(mContext, packageName) val res: Resources try { res = mContext!!.packageManager.getResourcesForApplication(packageName!!) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() mLoading = false return } mLoadedIconPackResource = res mLoadedIconPackName = packageName mIconMask = getDrawableForName(ICON_MASK_TAG) mIconUpon = getDrawableForName(ICON_UPON_TAG) for (i in mIconBackStrings.indices) { val backIconString = mIconBackStrings[i] val backIcon = getDrawableWithName(backIconString) if (backIcon != null) { mIconBackList.add(backIcon) } } val scale = mIconPackResources!![ICON_SCALE_TAG] if (scale != null) { try { mIconScale = scale.toFloat() } catch (ignored: NumberFormatException) { } } mLoading = false } //new method from trebuchet private fun getIconPackResourcesNew( context: Context?, packageName: String? ): Map<String, String?>? { if (TextUtils.isEmpty(packageName)) { return null } val res: Resources res = try { context!!.packageManager.getResourcesForApplication(packageName!!) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() return null } var parser: XmlPullParser? = null var inputStream: InputStream? = null val iconPackResources: MutableMap<String, String?> = HashMap() try { inputStream = res.assets.open("appfilter.xml") val factory = XmlPullParserFactory.newInstance() parser = factory.newPullParser() parser.setInput(inputStream, "UTF-8") } catch (e: Exception) { // Catch any exception since we want to fall back to parsing the xml/ // resource in all cases val resId = res.getIdentifier("appfilter", "xml", packageName) if (resId != 0) { parser = res.getXml(resId) } } if (parser != null) { try { loadResourcesFromXmlParser(parser, iconPackResources) return iconPackResources } catch (e: XmlPullParserException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { // Cleanup resources if (parser is XmlResourceParser) { parser.close() } if (inputStream != null) { try { inputStream.close() } catch (ignored: IOException) { } } } } // Application uses a different theme format (most likely launcher pro) var arrayId = res.getIdentifier("theme_iconpack", "array", packageName) if (arrayId == 0) { arrayId = res.getIdentifier("icon_pack", "array", packageName) } if (arrayId != 0) { val iconPack = res.getStringArray(arrayId) for (entry1 in iconPack) { if (TextUtils.isEmpty(entry1)) { continue } val icon = entry1.lowercase(Locale.getDefault()) val entry = entry1.replace("_".toRegex(), ".") iconPackResources[entry] = icon val activityIndex = entry.lastIndexOf(".") if (activityIndex <= 0 || activityIndex == entry.length - 1) { continue } val iconPackage = entry.substring(0, activityIndex) if (TextUtils.isEmpty(iconPackage)) { continue } iconPackResources[iconPackage] = icon val iconActivity = entry.substring(activityIndex + 1) if (TextUtils.isEmpty(iconActivity)) { continue } iconPackResources["$iconPackage.$iconActivity"] = icon } } else { loadApplicationResources(context, iconPackResources, packageName) } return iconPackResources } private fun loadApplicationResources( context: Context?, iconPackResources: MutableMap<String, String?>, packageName: String? ) { val drawableItems: Array<Field> drawableItems = try { val appContext = context!!.createPackageContext( packageName, Context.CONTEXT_INCLUDE_CODE or Context.CONTEXT_IGNORE_SECURITY ) Class.forName("$packageName.R\$drawable", true, appContext.classLoader).fields } catch (e: Exception) { return } for (f in drawableItems) { var name = f.name val icon = name.lowercase(Locale.getDefault()) name = name.replace("_".toRegex(), ".") iconPackResources[name] = icon val activityIndex = name.lastIndexOf(".") if (activityIndex <= 0 || activityIndex == name.length - 1) { continue } val iconPackage = name.substring(0, activityIndex) if (TextUtils.isEmpty(iconPackage)) { continue } iconPackResources[iconPackage] = icon val iconActivity = name.substring(activityIndex + 1) if (TextUtils.isEmpty(iconActivity)) { continue } iconPackResources["$iconPackage.$iconActivity"] = icon } } val isIconPackLoaded: Boolean get() = mLoadedIconPackResource != null && mLoadedIconPackName != null && mIconPackResources != null private fun getResourceIdForDrawable(resource: String?): Int { return mLoadedIconPackResource!!.getIdentifier(resource, "drawable", mLoadedIconPackName) } fun getIconPackResources(id: Int, mContext: Context?): Drawable? { return ResourcesCompat.getDrawable(mLoadedIconPackResource!!, id, mContext!!.theme) } fun getResourceIdForActivityIcon(info: ActivityInfo): Int { // TODO since we are loading in background block access until load ready if (!isIconPackLoaded || mLoading) { return 0 } //Try to match icon class by lower case, if not fallback to exact string //Catch added for lower case exceptions var drawable: String? drawable = try { mIconPackResources!![info.packageName.lowercase(Locale.getDefault()) + "." + info.name.lowercase( Locale.getDefault() )] } catch (e: NullPointerException) { mIconPackResources!![info.packageName + "." + info.name] } if (drawable == null) { // Icon pack doesn't have an icon for the activity, fallback to package icon //Catch added for lower case exceptions drawable = try { mIconPackResources!![info.packageName.lowercase(Locale.getDefault())] } catch (e: NullPointerException) { mIconPackResources!![info.packageName] } if (drawable == null) { return 0 } } return getResourceIdForDrawable(drawable) } fun getIconPack(prefs: SharedPreferences?): String { return prefs!!.getString("icon_pack", "").also { mCurrentIconPack = it }!! } private fun init(prefs: SharedPreferences) { mCurrentIconPack = prefs.getString("icon_pack", "") if (!TextUtils.isEmpty(mCurrentIconPack)) { try { loadIconPack() } catch (i: NullPointerException) { Log.d("Icon Pack Error", "Loading Error : $i") //Icon Pack is not supported so wipe the icon pack data prefs.edit().putString("icon_pack", "").apply() Toast.makeText(mContext, "Unsupported Icon Pack", Toast.LENGTH_LONG).show() } } } companion object { private const val ICON_MASK_TAG = "iconmask" private const val ICON_BACK_TAG = "iconback" private const val ICON_UPON_TAG = "iconupon" private const val ICON_SCALE_TAG = "scale" @SuppressLint("StaticFieldLeak") private var sInstance: IconPackHelper? = null fun getInstance(context: Context?): IconPackHelper? { if (sInstance == null) { sInstance = IconPackHelper() sInstance!!.setContext(context) val prefs = PreferenceManager.getDefaultSharedPreferences( context!! ) sInstance!!.init(prefs) } return sInstance } } }
0
Kotlin
0
0
0e0959b2ce3af98bbab2bbdbca509f0f66820e47
14,667
boringdroidsystemui
Apache License 2.0
floating/src/main/java/com/zj/floating/FloatingMenu.kt
zhujiang521
265,420,729
false
null
package com.zj.floating import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.annotation.TargetApi import android.content.Context import android.content.res.ColorStateList import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.view.animation.DecelerateInterpolator import android.view.animation.Interpolator import android.view.animation.OvershootInterpolator import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.eliza.android.tools.R import com.google.android.material.floatingactionbutton.FloatingActionButton /** * * [toggle] 切换菜单的展开收缩状态<br></br> * * [setFloatingDirection] 设置展开方向 * * [setCover] 设置封面 * * 可以通过调用 [addButton] 和 [removeButton] 来动态增减按钮数量。 * */ class FloatingMenu @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : ViewGroup(context, attrs, defStyleAttr, defStyleRes), CoordinatorLayout.AttachedBehavior { private var floatingMusicButton: FloatingButton? = null private var showAnimation: AnimatorSet? = null private var hideAnimation: AnimatorSet? = null private var buttonInterval = 0f private var backgroundTint: ColorStateList? = null private var cover: Drawable? = null var isExpanded = false private var isHided = false private var floatingDirection = 0 @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : this(context, attrs, defStyleAttr, 0) private fun initMenu(context: Context, attrs: AttributeSet?) { val attr = context.obtainStyledAttributes(attrs, R.styleable.FloatingMenu, 0, 0) buttonInterval = attr.getDimension(R.styleable.FloatingMenu_fmm_button_interval, 4f) buttonInterval = dp2px(buttonInterval) cover = attr.getDrawable(R.styleable.FloatingMenu_fmm_cover) backgroundTint = attr.getColorStateList(R.styleable.FloatingMenu_fmm_backgroundTint) floatingDirection = attr.getInteger(R.styleable.FloatingMenu_fmm_floating_direction, 0) attr.recycle() createRootButton(context) addScrollAnimation() } private fun addScrollAnimation() { showAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong()) showAnimation?.play(ObjectAnimator.ofFloat(this, ALPHA, 0f, 1f)) showAnimation?.apply { interpolator = alphaExpandInterpolator addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) visibility = VISIBLE } override fun onAnimationStart(animation: Animator) { super.onAnimationStart(animation) visibility = VISIBLE } }) } hideAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong()) hideAnimation?.play(ObjectAnimator.ofFloat(this, ALPHA, 1f, 0f)) hideAnimation?.apply { interpolator = alphaExpandInterpolator addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) visibility = INVISIBLE } }) } } private fun createRootButton(context: Context) { floatingMusicButton = FloatingButton(context) floatingMusicButton?.apply { setOnClickListener { toggle() } config(backgroundTint) if (cover != null) { setCoverDrawable(cover) } } } override fun onFinishInflate() { super.onFinishInflate() addView(floatingMusicButton, super.generateDefaultLayoutParams()) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { measureChildren(widthMeasureSpec, heightMeasureSpec) when (floatingDirection) { FLOATING_DIRECTION_UP, FLOATING_DIRECTION_DOWN -> onMeasureVerticalDirection() FLOATING_DIRECTION_LEFT, FLOATING_DIRECTION_RIGHT -> onMeasureHorizontalDirection() } } /** * 计算竖向排列时需要的大小 */ private fun onMeasureVerticalDirection() { var width = 0 var height = 0 for (i in 0 until childCount) { val child = getChildAt(i) if (child.visibility == GONE) continue width = child.measuredWidth.coerceAtLeast(width) height += child.measuredHeight } width += SHADOW_OFFSET * 2 height += SHADOW_OFFSET * 2 height += (buttonInterval * (childCount - 1)).toInt() height = adjustShootLength(height) setMeasuredDimension(width, height) } /** * 计算横向排列时需要的大小 */ private fun onMeasureHorizontalDirection() { var width = 0 var height = 0 for (i in 0 until childCount) { val child = getChildAt(i) if (child.visibility == GONE) continue height = child.measuredHeight.coerceAtLeast(height) width += child.measuredWidth } width += SHADOW_OFFSET * 2 height += SHADOW_OFFSET * 2 width += (buttonInterval * (childCount - 1)).toInt() width = adjustShootLength(width) setMeasuredDimension(width, height) } private fun adjustShootLength(length: Int): Int { return length * 12 / 10 } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { when (floatingDirection) { FLOATING_DIRECTION_UP -> onUpDirectionLayout(l, t, r, b) FLOATING_DIRECTION_DOWN -> onDownDirectionLayout(l, r) FLOATING_DIRECTION_LEFT -> onLeftDirectionLayout(l, t, r, b) FLOATING_DIRECTION_RIGHT -> onRightDirectionLayout(t, b) } } /** * 摆放朝上展开方向的子控件位置 */ private fun onUpDirectionLayout(l: Int, t: Int, r: Int, b: Int) { val centerX = (r - l) / 2 var offsetY = b - t - SHADOW_OFFSET for (i in childCount - 1 downTo 0) { val child = getChildAt(i) if (child.visibility == GONE) continue val width = child.measuredWidth val height = child.measuredHeight child.layout(centerX - width / 2, offsetY - height, centerX + width / 2, offsetY) //排除根按钮,添加动画 if (i != childCount - 1) { val collapsedTranslation = (b - t - SHADOW_OFFSET - offsetY).toFloat() val expandedTranslation = 0f child.translationY = if (isExpanded) expandedTranslation else collapsedTranslation child.alpha = if (isExpanded) 1f else 0f val params = child.layoutParams as MenuLayoutParams params.apply { collapseDirAnim.setFloatValues(expandedTranslation, collapsedTranslation) expandDirAnim.setFloatValues(collapsedTranslation, expandedTranslation) collapseDirAnim.setProperty(TRANSLATION_Y) expandDirAnim.setProperty(TRANSLATION_Y) setAnimationsTarget(child) } } offsetY -= (height + buttonInterval).toInt() } } /** * 摆放朝下展开方向的子控件位置 */ private fun onDownDirectionLayout(l: Int, r: Int) { val centerX = (r - l) / 2 var offsetY = SHADOW_OFFSET val rootView = getChildAt(childCount - 1) rootView.layout( centerX - rootView.measuredWidth / 2, offsetY, centerX + rootView.measuredWidth / 2, offsetY + rootView.measuredHeight ) offsetY += (rootView.measuredHeight + buttonInterval).toInt() for (i in 0 until childCount - 1) { val child = getChildAt(i) if (child.visibility == GONE) continue val width = child.measuredWidth val height = child.measuredHeight child.layout(centerX - width / 2, offsetY, centerX + width / 2, offsetY + height) val collapsedTranslation = -offsetY.toFloat() val expandedTranslation = 0f child.translationY = if (isExpanded) expandedTranslation else collapsedTranslation child.alpha = if (isExpanded) 1f else 0f val params = child.layoutParams as MenuLayoutParams params.apply { collapseDirAnim.setFloatValues(expandedTranslation, collapsedTranslation) expandDirAnim.setFloatValues(collapsedTranslation, expandedTranslation) collapseDirAnim.setProperty(TRANSLATION_Y) expandDirAnim.setProperty(TRANSLATION_Y) setAnimationsTarget(child) } offsetY += (height + buttonInterval).toInt() } } /** * 摆放朝左展开方向的子控件位置 */ private fun onLeftDirectionLayout(l: Int, t: Int, r: Int, b: Int) { val centerY = (b - t) / 2 var offsetX = r - l - SHADOW_OFFSET for (i in childCount - 1 downTo 0) { val child = getChildAt(i) if (child.visibility == GONE) continue val width = child.measuredWidth val height = child.measuredHeight child.layout(offsetX - width, centerY - height / 2, offsetX, centerY + height / 2) //排除根按钮,添加动画 if (i != childCount - 1) { val collapsedTranslation = (r - l - SHADOW_OFFSET - offsetX).toFloat() val expandedTranslation = 0f child.translationX = if (isExpanded) expandedTranslation else collapsedTranslation child.alpha = if (isExpanded) 1f else 0f val params = child.layoutParams as MenuLayoutParams params.apply { collapseDirAnim.setFloatValues(expandedTranslation, collapsedTranslation) expandDirAnim.setFloatValues(collapsedTranslation, expandedTranslation) collapseDirAnim.setProperty(TRANSLATION_X) expandDirAnim.setProperty(TRANSLATION_X) setAnimationsTarget(child) } } offsetX -= (width + buttonInterval).toInt() } } /** * 摆放朝右展开方向的子控件位置 */ private fun onRightDirectionLayout(t: Int, b: Int) { val centerY = (b - t) / 2 var offsetX = SHADOW_OFFSET val rootView = getChildAt(childCount - 1) rootView.layout( offsetX, centerY - rootView.measuredHeight / 2, offsetX + rootView.measuredWidth, centerY + rootView.measuredHeight / 2 ) offsetX += (rootView.measuredWidth + buttonInterval).toInt() for (i in 0 until childCount - 1) { val child = getChildAt(i) if (child.visibility == GONE) continue val width = child.measuredWidth val height = child.measuredHeight child.layout(offsetX, centerY - height / 2, offsetX + width, centerY + height / 2) val collapsedTranslation = -offsetX.toFloat() val expandedTranslation = 0f child.translationX = if (isExpanded) expandedTranslation else collapsedTranslation child.alpha = if (isExpanded) 1f else 0f val params = child.layoutParams as MenuLayoutParams params.apply { collapseDirAnim.setFloatValues(expandedTranslation, collapsedTranslation) expandDirAnim.setFloatValues(collapsedTranslation, expandedTranslation) collapseDirAnim.setProperty(TRANSLATION_X) expandDirAnim.setProperty(TRANSLATION_X) setAnimationsTarget(child) } offsetX += (width + buttonInterval).toInt() } } fun setButtonInterval(buttonInterval: Float) { this.buttonInterval = buttonInterval requestLayout() } fun addButton(button: FloatingActionButton?) { addView(button, 0) requestLayout() } fun addButtonAtLast(button: FloatingActionButton?) { addView(button, childCount - 1) requestLayout() } fun removeButton(button: FloatingActionButton?) { removeView(button) requestLayout() } fun setCover(drawable: Drawable?) { floatingMusicButton!!.setCoverDrawable(drawable) } fun setCover(bitmap: Bitmap?) { floatingMusicButton!!.setCover(bitmap) } fun setFloatingDirection(floatingDirection: Int) { this.floatingDirection = floatingDirection postInvalidate() } override fun generateDefaultLayoutParams(): LayoutParams { return MenuLayoutParams(super.generateDefaultLayoutParams()) } override fun generateLayoutParams(attrs: AttributeSet): LayoutParams { return MenuLayoutParams(super.generateLayoutParams(attrs)) } override fun generateLayoutParams(p: LayoutParams): LayoutParams { return MenuLayoutParams(super.generateLayoutParams(p)) } private val mExpandAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong()) private val mCollapseAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong()) private inner class MenuLayoutParams(source: LayoutParams?) : LayoutParams(source) { val expandDirAnim = ObjectAnimator() private val expandAlphaAnim = ObjectAnimator() val collapseDirAnim = ObjectAnimator() private val collapseAlphaAnim = ObjectAnimator() private var animationsSetToPlay = false fun setAnimationsTarget(view: View) { collapseAlphaAnim.target = view collapseDirAnim.target = view expandDirAnim.target = view expandAlphaAnim.target = view // Now that the animations have targets, set them to be played if (!animationsSetToPlay) { addLayerTypeListener(expandDirAnim, view) addLayerTypeListener(collapseDirAnim, view) mCollapseAnimation.play(collapseAlphaAnim) mCollapseAnimation.play(collapseDirAnim) mExpandAnimation.play(expandAlphaAnim) mExpandAnimation.play(expandDirAnim) animationsSetToPlay = true } } private fun addLayerTypeListener(animator: Animator, view: View) { animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { view.setLayerType(LAYER_TYPE_NONE, null) } override fun onAnimationStart(animation: Animator) { view.setLayerType(LAYER_TYPE_HARDWARE, null) } }) } init { expandDirAnim.interpolator = expandInterpolator expandAlphaAnim.interpolator = alphaExpandInterpolator collapseDirAnim.interpolator = collapseInterpolator collapseAlphaAnim.interpolator = collapseInterpolator collapseAlphaAnim.setProperty(ALPHA) collapseAlphaAnim.setFloatValues(1f, 0f) expandAlphaAnim.setProperty(ALPHA) expandAlphaAnim.setFloatValues(0f, 1f) } } private fun collapse() { collapse(false) } fun collapseImmediately() { collapse(true) } private fun collapse(immediately: Boolean) { if (isExpanded) { isExpanded = false mCollapseAnimation.duration = if (immediately) 0 else ANIMATION_DURATION.toLong() mCollapseAnimation.start() mExpandAnimation.cancel() } } fun toggle() { if (isExpanded) { collapse() } else { expand() } } private fun expand() { if (!isExpanded) { isExpanded = true mCollapseAnimation.cancel() mExpandAnimation.start() } } fun hide() { if (!isHided) { isHided = true hideAnimation!!.start() showAnimation!!.cancel() } } fun show() { if (isHided) { isHided = false showAnimation!!.start() hideAnimation!!.cancel() } } private fun dp2px(dp: Float): Float { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics ) } /** * * * 上拉隐藏,下拉显示的动作行为,配合 [FloatingMenu] 使用更佳 * */ class Behavior : CoordinatorLayout.Behavior<FloatingMenu>() { override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingMenu, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { super.onNestedScroll( coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed ) if (dyConsumed > 30 && child.visibility == VISIBLE) { child.hide() } else if (dyConsumed < -30 && child.visibility == INVISIBLE) { child.show() } } override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingMenu, directTargetChild: View, target: View, nestedScrollAxes: Int ): Boolean { return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL } } companion object { const val FLOATING_DIRECTION_UP = 0 const val FLOATING_DIRECTION_LEFT = 1 const val FLOATING_DIRECTION_DOWN = 2 const val FLOATING_DIRECTION_RIGHT = 3 private const val SHADOW_OFFSET = 20 private const val ANIMATION_DURATION = 300 private val expandInterpolator: Interpolator = OvershootInterpolator() private val collapseInterpolator: Interpolator = DecelerateInterpolator(3f) private val alphaExpandInterpolator: Interpolator = DecelerateInterpolator() } init { initMenu(context, attrs) } override fun getBehavior(): CoordinatorLayout.Behavior<*> { return Behavior() } }
6
null
218
977
11111a15f4fa9f43668b4f6356074b531f134baf
18,975
PlayAndroid
MIT License
libtesting-navigation-core-utils/src/main/java/com/mapbox/navigation/testing/utils/http/MockDirectionsRequestHandler.kt
mapbox
87,455,763
false
{"Kotlin": 9692008, "Python": 65081, "Java": 36829, "HTML": 17811, "Makefile": 9840, "Shell": 7129}
package com.mapbox.navigation.instrumentation_tests.utils.http import android.util.Log import com.mapbox.api.directions.v5.models.RouteOptions import com.mapbox.geojson.Point import com.mapbox.navigation.testing.ui.http.BaseMockRequestHandler import com.mapbox.turf.TurfConstants import com.mapbox.turf.TurfMeasurement import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest private const val TAG = "MockDirectionsRequestHandler" /** * Mocks a directions response. * * @param profile the request profile, ex. "driving" * @param jsonResponse the full JSON response * @param expectedCoordinates optionally the expected coordinates * that the handler should match when providing the response */ data class MockDirectionsRequestHandler constructor( val profile: String, val lazyJsonResponse: () -> String, val expectedCoordinates: List<Point>?, val relaxedExpectedCoordinates: Boolean = false, val coordinatesAccuracyInMeters: Double = 30.0, val routeOptionsFilter: (RouteOptions) -> Boolean = { true } ) : BaseMockRequestHandler() { constructor( profile: String, jsonResponse: String, expectedCoordinates: List<Point>?, relaxedExpectedCoordinates: Boolean = false, coordinatesAccuracyInMeters: Double = 30.0, routeOptionsFilter: (RouteOptions) -> Boolean = { true } ) : this( profile, { jsonResponse }, expectedCoordinates, relaxedExpectedCoordinates, coordinatesAccuracyInMeters, routeOptionsFilter ) var jsonResponseModifier: ((String) -> String) = { it } override fun handleInternal(request: RecordedRequest): MockResponse? { val routeOptions = try { val result = RouteOptions.fromUrl(request.requestUrl!!.toUrl()) result.coordinatesList() // checks that coordinates are parsable result } catch (t: Throwable) { null } if (routeOptions != null) { if (relaxedExpectedCoordinates) { return provideMockResponse() } require(expectedCoordinates != null) { "specify expected coordinates if they are not relaxed" } val coordinatesMatchExpectedAccordingToAccuracy = coordinatesWithinRadius( expectedCoordinates, routeOptions.coordinatesList(), coordinatesAccuracyInMeters ) if (coordinatesMatchExpectedAccordingToAccuracy) { if (routeOptionsFilter(routeOptions)) { return provideMockResponse() } else { Log.w(TAG, "mock response is filtered out by route options filters") } } else { Log.w( TAG, "mock response isn't provided because locations doesn't match expected" ) } } return null } private fun provideMockResponse(): MockResponse { Log.d(TAG, "mock response is provided") return MockResponse().setBody(jsonResponseModifier(lazyJsonResponse())) } private fun coordinatesWithinRadius( expected: List<Point>, actual: List<Point>, coordinatesAccuracyInMeters: Double ): Boolean { if (expected.size != actual.size) return false return expected.zip(actual).all { (a, b) -> TurfMeasurement.distance( a, b, TurfConstants.UNIT_METERS ) < coordinatesAccuracyInMeters } } override fun toString(): String { return "MockDirectionsRequestHandler(" + "profile='$profile', " + "expectedCoordinates=$expectedCoordinates, " + "relaxedExpectedCoordinates=$relaxedExpectedCoordinates, " + "lazyJsonResponse='$lazyJsonResponse', " + "coordinatesAccuracyInMeters='$coordinatesAccuracyInMeters'" + ")" } }
508
Kotlin
319
621
ad73c6011348cb9b24b92a369024ca06f48845ab
4,059
mapbox-navigation-android
Apache License 2.0
lib/src/test/kotlin/com/maltaisn/recurpicker/RecurrenceFinderTest.kt
cafewill
239,573,819
true
{"Kotlin": 216978}
/* * Copyright 2019 <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.maltaisn.recurpicker import com.maltaisn.recurpicker.Recurrence.Period import org.junit.Test import kotlin.test.assertEquals internal class RecurrenceFinderTest { // To confirm events with RRule: http://jakubroztocil.github.io/rrule/ private val finder = RecurrenceFinder() @Test(expected = IllegalArgumentException::class) fun wrongAmount() { val r = Recurrence(Period.DAILY) finder.find(r, dateFor("2019-01-01"), 0) } @Test(expected = IllegalArgumentException::class) fun noStartDate() { val r = Recurrence(Period.DAILY) finder.find(r, Recurrence.DATE_NONE, 1) } @Test fun none() { val r = Recurrence.DOES_NOT_REPEAT assertEquals(listOf( dateFor("2019-01-01") ), finder.find(r, dateFor("2019-01-01"), 10)) } @Test fun none_fromDate() { val r1 = Recurrence.DOES_NOT_REPEAT assertEquals(listOf( dateFor("2019-01-01") ), finder.find(r1, dateFor("2019-01-01"), 10, dateFor("2019-01-01"))) val r2 = Recurrence.DOES_NOT_REPEAT assertEquals(emptyList<Long>(), finder.find(r2, dateFor("2019-01-01"), 10, dateFor("2019-01-02"))) } @Test fun none_fromDate_excludeStart() { val r = Recurrence.DOES_NOT_REPEAT assertEquals(emptyList<Long>(), finder.find(r, dateFor("2019-01-01"), 10, dateFor("2019-01-01"), includeStart = false)) } @Test fun daily() { val r = Recurrence(Period.DAILY) assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-02"), dateFor("2019-01-03"), dateFor("2019-01-04"), dateFor("2019-01-05") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun daily_frequency3() { val r = Recurrence(Period.DAILY) { frequency = 3 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-04"), dateFor("2019-01-07"), dateFor("2019-01-10"), dateFor("2019-01-13") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun daily_endDate() { val r = Recurrence(Period.DAILY) { endDate = dateFor("2019-01-03") } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-02"), dateFor("2019-01-03") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun daily_endCount() { val r = Recurrence(Period.DAILY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-02"), dateFor("2019-01-03"), dateFor("2019-01-04"), dateFor("2019-01-05") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun daily_basedOn() { val r = Recurrence(Period.DAILY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-03"), dateFor("2019-01-04"), dateFor("2019-01-05") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-03"), 3, 1000)) } @Test fun daily_basedOn_fromDate() { val r = Recurrence(Period.DAILY) { endCount = 6 } assertEquals(listOf( dateFor("2019-01-05"), dateFor("2019-01-06") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-03"), 3, 1000, dateFor("2019-01-05"))) } @Test fun daily_excludeStart() { val r = Recurrence(Period.DAILY) assertEquals(listOf( dateFor("2019-01-02"), dateFor("2019-01-03") ), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false)) } @Test fun weekly_default() { val r = Recurrence(Period.WEEKLY) assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-08"), dateFor("2019-01-15"), dateFor("2019-01-22"), dateFor("2019-01-29") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun weekly_sun_mon_wed() { val r = Recurrence(Period.WEEKLY) { setDaysOfWeek(Recurrence.SUNDAY, Recurrence.MONDAY, Recurrence.WEDNESDAY) } assertEquals(listOf( dateFor("2019-01-02"), dateFor("2019-01-06"), dateFor("2019-01-07"), dateFor("2019-01-09"), dateFor("2019-01-13") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun weekly_all_days() { val r = Recurrence(Period.WEEKLY) { frequency = 2 setDaysOfWeek(Recurrence.EVERY_DAY_OF_WEEK) } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-02"), dateFor("2019-01-03"), dateFor("2019-01-04"), dateFor("2019-01-05"), dateFor("2019-01-13"), dateFor("2019-01-14"), dateFor("2019-01-15") ), finder.find(r, dateFor("2019-01-01"), 8)) } @Test fun weekly_frequency3() { val r = Recurrence(Period.WEEKLY) { frequency = 3 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-22"), dateFor("2019-02-12"), dateFor("2019-03-05"), dateFor("2019-03-26") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun weekly_endDate() { val r = Recurrence(Period.WEEKLY) { endDate = dateFor("2019-01-15") } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-08"), dateFor("2019-01-15") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun weekly_endCount() { val r = Recurrence(Period.WEEKLY) { endCount = 4 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-01-08"), dateFor("2019-01-15"), dateFor("2019-01-22") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun weekly_basedOn() { val r = Recurrence(Period.WEEKLY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-15"), dateFor("2019-01-22"), dateFor("2019-01-29") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-15"), 3, 1000)) } @Test fun weekly_basedOn_fromDate() { val r = Recurrence(Period.WEEKLY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-22"), dateFor("2019-01-29") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-01-15"), 3, 1000, dateFor("2019-01-22"))) } @Test fun weekly_excludeStart() { val r = Recurrence(Period.WEEKLY) assertEquals(listOf( dateFor("2019-01-08"), dateFor("2019-01-15") ), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false)) } @Test fun weekly_excludeStart_noEventOnStart() { val r = Recurrence(Period.WEEKLY) { setDaysOfWeek(Recurrence.WEDNESDAY, Recurrence.THURSDAY) } assertEquals(listOf( dateFor("2019-01-02"), dateFor("2019-01-03") ), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false)) } @Test fun monthly_sameDay() { val r = Recurrence(Period.MONTHLY) assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-02-01"), dateFor("2019-03-01"), dateFor("2019-04-01"), dateFor("2019-05-01") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun monthly_sameDay_31() { val r = Recurrence(Period.MONTHLY) { frequency = 3 } assertEquals(listOf( dateFor("2019-01-31"), dateFor("2019-07-31"), dateFor("2019-10-31"), dateFor("2020-01-31") ), finder.find(r, dateFor("2019-01-31"), 4)) } @Test fun monthly_sameDay_fromDate() { val r = Recurrence(Period.MONTHLY) assertEquals(listOf( dateFor("2020-06-01"), dateFor("2020-07-01"), dateFor("2020-08-01") ), finder.find(r, dateFor("2019-01-01"), 3, dateFor("2020-05-05"))) } @Test fun monthly_sameWeek_third() { val r = Recurrence(Period.MONTHLY) { setDayOfWeekInMonth(Recurrence.TUESDAY, 3) } assertEquals(listOf( dateFor("2019-01-15"), dateFor("2019-02-19"), dateFor("2019-03-19"), dateFor("2019-04-16"), dateFor("2019-05-21") ), finder.find(r, dateFor("2019-01-15"), 5)) } @Test fun monthly_lastDay() { val r = Recurrence(Period.MONTHLY) { dayInMonth = -1 } assertEquals(listOf( dateFor("2019-01-31"), dateFor("2019-02-28"), dateFor("2019-03-31"), dateFor("2019-04-30"), dateFor("2019-05-31") ), finder.find(r, dateFor("2019-01-15"), 5)) } @Test fun monthly_15toLastDay() { val r = Recurrence(Period.MONTHLY) { dayInMonth = -15 } assertEquals(listOf( dateFor("2019-01-17"), dateFor("2019-02-14"), dateFor("2019-03-17"), dateFor("2019-04-16"), dateFor("2019-05-17") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun monthly_sameWeek_last() { val r = Recurrence(Period.MONTHLY) { setDayOfWeekInMonth(Recurrence.THURSDAY, -1) } assertEquals(listOf( dateFor("2019-01-31"), dateFor("2019-02-28"), dateFor("2019-03-28"), dateFor("2019-04-25"), dateFor("2019-05-30") ), finder.find(r, dateFor("2019-01-31"), 5)) } @Test fun monthly_frequency3() { val r = Recurrence(Period.MONTHLY) { frequency = 3 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-04-01"), dateFor("2019-07-01"), dateFor("2019-10-01"), dateFor("2020-01-01") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun monthly_endDate() { val r = Recurrence(Period.MONTHLY) { endDate = dateFor("2019-03-01") } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-02-01"), dateFor("2019-03-01") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun monthly_endCount() { val r = Recurrence(Period.MONTHLY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2019-02-01"), dateFor("2019-03-01"), dateFor("2019-04-01"), dateFor("2019-05-01") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun monthly_basedOn() { val r = Recurrence(Period.MONTHLY) { endCount = 5 } assertEquals(listOf( dateFor("2019-03-01"), dateFor("2019-04-01"), dateFor("2019-05-01") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-03-01"), 3, 1000)) } @Test fun monthly_basedOn_fromDate() { val r = Recurrence(Period.MONTHLY) { endCount = 6 } assertEquals(listOf( dateFor("2019-05-01"), dateFor("2019-06-01") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2019-03-01"), 3, 1000, dateFor("2019-05-01"))) } @Test fun monthly_excludeStart() { val r = Recurrence(Period.MONTHLY) assertEquals(listOf( dateFor("2019-02-01"), dateFor("2019-03-01") ), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false)) } @Test fun yearly() { val r = Recurrence(Period.YEARLY) assertEquals(listOf( dateFor("2019-03-23"), dateFor("2020-03-23"), dateFor("2021-03-23"), dateFor("2022-03-23"), dateFor("2023-03-23") ), finder.find(r, dateFor("2019-03-23"), 5)) } @Test fun yearly_frequency3() { val r = Recurrence(Period.YEARLY) { frequency = 3 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2022-01-01"), dateFor("2025-01-01"), dateFor("2028-01-01"), dateFor("2031-01-01") ), finder.find(r, dateFor("2019-01-01"), 5)) } @Test fun yearly_endDate() { val r = Recurrence(Period.YEARLY) { endDate = dateFor("2021-01-01") } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2020-01-01"), dateFor("2021-01-01") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun yearly_endCount() { val r = Recurrence(Period.YEARLY) { endCount = 5 } assertEquals(listOf( dateFor("2019-01-01"), dateFor("2020-01-01"), dateFor("2021-01-01"), dateFor("2022-01-01"), dateFor("2023-01-01") ), finder.find(r, dateFor("2019-01-01"), 1000)) } @Test fun yearly_basedOn() { val r = Recurrence(Period.YEARLY) { endCount = 5 } assertEquals(listOf( dateFor("2021-01-01"), dateFor("2022-01-01"), dateFor("2023-01-01") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2021-01-01"), 3, 1000)) } @Test fun yearly_basedOn_fromDate() { val r = Recurrence(Period.YEARLY) { endCount = 5 } assertEquals(listOf( dateFor("2022-01-01"), dateFor("2023-01-01") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2021-01-01"), 3, 1000, dateFor("2022-01-01"))) } @Test fun yearly_excludeStart() { val r = Recurrence(Period.YEARLY) assertEquals(listOf( dateFor("2020-01-01"), dateFor("2021-01-01") ), finder.find(r, dateFor("2019-01-01"), 2, includeStart = false)) } @Test fun yearly_basedOn_excludeStart() { val r = Recurrence(Period.YEARLY) assertEquals(listOf( dateFor("2022-01-01"), dateFor("2023-01-01") ), finder.findBasedOn(r, dateFor("2019-01-01"), dateFor("2021-01-01"), 2, 2, includeStart = false)) } @Test fun yearly_feb29() { val r = Recurrence(Period.YEARLY) assertEquals(listOf( dateFor("2096-02-29"), dateFor("2104-02-29"), dateFor("2108-02-29"), dateFor("2112-02-29") ), finder.find(r, dateFor("2096-02-29"), 4)) } @Test fun findBetween() { val r = Recurrence(Period.DAILY) assertEquals(listOf( dateFor("2019-01-27"), dateFor("2019-01-28"), dateFor("2019-01-29") ), finder.findBetween(r, dateFor("2019-01-01"), dateFor("2019-01-27"), dateFor("2019-01-30"))) } @Test fun findBetween_endCount() { val r = Recurrence(Period.DAILY) { endCount = 7 } assertEquals(listOf( dateFor("2019-01-04"), dateFor("2019-01-05"), dateFor("2019-01-06"), dateFor("2019-01-07") ), finder.findBetween(r, dateFor("2019-01-01"), dateFor("2019-01-04"), dateFor("2019-01-10"))) } }
0
null
0
0
8780cd543fae6de821d00e9958ae79796438f316
17,259
recurpickerlib
Apache License 2.0
app/src/main/java/com/irvan/movieku/database/dao/GenreDao.kt
asaldaftar
346,210,563
false
null
package com.irvan.movieku.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.irvan.movieku.mvvm.models.GenreModel @Dao interface GenreDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertGenre(genreModel: GenreModel) @Query("UPDATE genre SET name = :name WHERE id = :id") fun updateGenre(id: String, name: String) @Query("SELECT * FROM genre ORDER BY name ASC") fun getGenre(): LiveData<MutableList<GenreModel>> @Query("SELECT * FROM genre WHERE name LIKE '%' || :name || '%' LIMIT 3") fun getGenre(name: String): LiveData<MutableList<GenreModel>> @Query("SELECT * FROM genre WHERE id = :id") fun getGenreById(id: String): GenreModel }
0
Kotlin
0
0
2044238396e9283afd7c802c0a30f849bfd51ef5
822
MovieKu
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/DiceAlt.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.DiceAlt: ImageVector get() { if (_diceAlt != null) { return _diceAlt!! } _diceAlt = Builder(name = "DiceAlt", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.5f, 9.0f) horizontalLineToRelative(-8.0f) arcTo(3.5f, 3.5f, 0.0f, false, false, 9.0f, 12.5f) lineTo(9.0f, 24.0f) lineTo(24.0f, 24.0f) lineTo(24.0f, 12.5f) arcTo(3.5f, 3.5f, 0.0f, false, false, 20.5f, 9.0f) close() moveTo(21.0f, 21.0f) lineTo(12.0f, 21.0f) lineTo(12.0f, 12.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f) horizontalLineToRelative(8.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f) close() moveTo(16.0f, 14.5f) arcTo(1.5f, 1.5f, 0.0f, true, true, 14.5f, 13.0f) arcTo(1.5f, 1.5f, 0.0f, false, true, 16.0f, 14.5f) close() moveTo(8.0f, 10.0f) arcTo(1.5f, 1.5f, 0.0f, true, true, 6.5f, 8.5f) arcTo(1.5f, 1.5f, 0.0f, false, true, 8.0f, 10.0f) close() moveTo(10.0f, 8.0f) arcToRelative(1.5f, 1.5f, 0.0f, true, true, 1.5f, -1.5f) arcTo(1.5f, 1.5f, 0.0f, false, true, 10.0f, 8.0f) close() moveTo(20.0f, 18.5f) arcTo(1.5f, 1.5f, 0.0f, true, true, 18.5f, 17.0f) arcTo(1.5f, 1.5f, 0.0f, false, true, 20.0f, 18.5f) close() moveTo(3.147f, 10.217f) lineTo(7.0f, 14.07f) verticalLineToRelative(4.243f) lineTo(1.025f, 12.338f) arcToRelative(3.5f, 3.5f, 0.0f, false, true, 0.0f, -4.95f) lineTo(7.389f, 1.024f) arcTo(3.476f, 3.476f, 0.0f, false, true, 9.863f, 0.0f) horizontalLineToRelative(0.0f) arcToRelative(3.48f, 3.48f, 0.0f, false, true, 2.475f, 1.024f) lineTo(18.314f, 7.0f) lineTo(14.072f, 7.0f) lineTo(10.218f, 3.146f) arcToRelative(0.512f, 0.512f, 0.0f, false, false, -0.707f, 0.0f) lineTo(3.146f, 9.51f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 0.707f) close() } } .build() return _diceAlt!! } private var _diceAlt: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,467
icons
MIT License
Mobile/Demos/TicTacToe/android/app/src/main/java/palbp/laboratory/demos/tictactoe/game/play/adapters/MatchFirebase.kt
palbp
463,200,783
false
{"Kotlin": 793883, "C": 16710, "Assembly": 891, "Dockerfile": 610, "Swift": 594, "Makefile": 383}
package palbp.laboratory.demos.tictactoe.game.play.adapters import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ListenerRegistration import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await import palbp.laboratory.demos.tictactoe.game.lobby.domain.Challenge import palbp.laboratory.demos.tictactoe.game.lobby.domain.PlayerInfo import palbp.laboratory.demos.tictactoe.game.play.domain.* class MatchFirebase(private val db: FirebaseFirestore) : Match { private var onGoingGame: Pair<Game, String>? = null private fun subscribeGameStateUpdated( localPlayerMarker: Marker, gameId: String, flow: ProducerScope<GameEvent> ) = db.collection(ONGOING) .document(gameId) .addSnapshotListener { snapshot, error -> when { error != null -> flow.close(error) snapshot != null -> { snapshot.toMatchStateOrNull()?.let { val game = Game( localPlayerMarker = localPlayerMarker, forfeitedBy = it.second, board = it.first ) val gameEvent = when { onGoingGame == null -> GameStarted(game) game.forfeitedBy != null -> GameEnded(game, game.forfeitedBy.other) else -> MoveMade(game) } onGoingGame = Pair(game, gameId) flow.trySend(gameEvent) } } } } private suspend fun publishGame(game: Game, gameId: String) { db.collection(ONGOING) .document(gameId) .set(game.board.toDocumentContent()) .await() } private suspend fun updateGame(game: Game, gameId: String) { db.collection(ONGOING) .document(gameId) .update(game.board.toDocumentContent()) .await() } override fun start(localPlayer: PlayerInfo, challenge: Challenge): Flow<GameEvent> { check(onGoingGame == null) return callbackFlow { val newGame = Game( localPlayerMarker = getLocalPlayerMarker(localPlayer, challenge), board = Board() ) val gameId = challenge.challenger.id.toString() var gameSubscription: ListenerRegistration? = null try { if (localPlayer == challenge.challenged) publishGame(newGame, gameId) gameSubscription = subscribeGameStateUpdated( localPlayerMarker = newGame.localPlayerMarker, gameId = gameId, flow = this ) } catch (e: Throwable) { close(e) } awaitClose { gameSubscription?.remove() } } } override suspend fun makeMove(at: Coordinate) { onGoingGame = checkNotNull(onGoingGame).also { val game = it.copy(first = it.first.makeMove(at)) updateGame(game.first, game.second) } } override suspend fun forfeit() { onGoingGame = checkNotNull(onGoingGame).also { db.collection(ONGOING) .document(it.second) .update(FORFEIT_FIELD, it.first.localPlayerMarker) .await() } } override suspend fun end() { onGoingGame = checkNotNull(onGoingGame).let { db.collection(ONGOING) .document(it.second) .delete() .await() null } } } /** * Names of the fields used in the document representations. */ const val ONGOING = "ongoing" const val TURN_FIELD = "turn" const val BOARD_FIELD = "board" const val FORFEIT_FIELD = "forfeit" /** * [Board] extension function used to convert an instance to a map of key-value * pairs containing the object's properties */ fun Board.toDocumentContent() = mapOf( TURN_FIELD to turn.name, BOARD_FIELD to toMovesList().joinToString(separator = "") { when (it) { Marker.CROSS -> "X" Marker.CIRCLE -> "O" null -> "-" } } ) /** * Extension function to convert documents stored in the Firestore DB * into the corresponding match state. */ fun DocumentSnapshot.toMatchStateOrNull(): Pair<Board, Marker?>? = data?.let { val moves = it[BOARD_FIELD] as String val turn = Marker.valueOf(it[TURN_FIELD] as String) val forfeit = it[FORFEIT_FIELD] as String? Pair( first = Board.fromMovesList(turn, moves.toMovesList()), second = if (forfeit != null) Marker.valueOf(forfeit) else null ) } /** * Converts this string to a list of moves in the board */ fun String.toMovesList(): List<Marker?> = map { when (it) { 'X' -> Marker.CROSS 'O' -> Marker.CIRCLE else -> null } }
1
Kotlin
0
5
9067753258a6a71bcd79cd59401edd58df66db71
5,417
laboratory
MIT License
app/src/main/java/ir/esmaeili/stopcar/models/dao/CarsDao.kt
BasetEsmaeili
250,985,369
false
null
package ir.esmaeili.stopcar.models.dao import androidx.room.* import io.reactivex.Flowable import ir.esmaeili.stopcar.models.Car @Dao interface CarsDao { @Insert fun insert(car: Car) @Query("SELECT * FROM cars") fun getCars(): Flowable<List<Car>> @Query("SELECT COUNT(car_id) FROM cars") fun getCarCount(): Flowable<Long> @Query("DELETE FROM cars WHERE car_id=:carID") fun deleteCar(carID: Long) @Query("DELETE FROM cars") fun deleteAll() }
1
Kotlin
3
8
8287613ca3afb090f52e9bed02671a0375d1c3d9
487
StopCar-Redesigned
Apache License 2.0
dcache/src/main/java/dora/cache/data/fetcher/IListFlowDataFetcher.kt
dora4
378,306,065
false
null
package dora.cache.data.fetcher import dora.cache.data.page.IDataPager import dora.http.DoraListCallback import kotlinx.coroutines.flow.StateFlow /** * 从[kotlinx.coroutines.flow.StateFlow]数据载体中直接读取内存数据的集合数据抓取器。 */ interface IListFlowDataFetcher<M> { /** * 清空flow data的数据。 */ fun clearListData() /** * 抓取数据的回调。 */ fun listCallback(): DoraListCallback<M> /** * 开始抓取数据。 */ fun fetchListData(description: String? = "", listener: OnLoadStateListener? = OnLoadStateListenerImpl()): StateFlow<MutableList<M>> /** * 获取livedata。 */ fun getListFlowData() : StateFlow<MutableList<M>> /** * 获取flow data的分页器。 */ fun obtainPager(): IDataPager<M> }
2
null
3
28
4afa8bc6195b17a3af790c286966a38ae114d7f1
740
dcache-android
MIT License
src/main/java/com/cumulocity/client/model/ApplicationSettings.kt
SoftwareAG
525,378,320
false
{"Kotlin": 769226}
// Copyright (c) 2014-2023 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. // Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. package com.cumulocity.client.model import com.google.gson.Gson class ApplicationSettings { /** * The name of the setting. */ var key: String? = null /** * The value schema determines the values that the microservice can process. */ var valueSchema: ValueSchema? = null /** * The default value. */ var defaultValue: String? = null /** * Indicates if the value is editable. */ var editable: Boolean? = null /** * Indicated wether this setting is inherited. */ var inheritFromOwner: Boolean? = null /** * The value schema determines the values that the microservice can process. */ class ValueSchema { /** * The value schema type. */ var type: String? = null override fun toString(): String { return Gson().toJson(this).toString() } } override fun toString(): String { return Gson().toJson(this).toString() } }
2
Kotlin
1
3
4c09a39aced1c5fb0677eb2a099a2dcda466f4d4
1,207
cumulocity-clients-kotlin
Apache License 2.0
src/jvmMain/kotlin/dev/zacsweers/Platform.kt
ZacSweers
288,008,412
false
null
package dev.zacsweers import androidx.compose.runtime.Composable import com.mikepenz.markdown.compose.LocalMarkdownColors import com.mikepenz.markdown.compose.LocalMarkdownTypography import com.mikepenz.markdown.compose.Markdown import com.tickaroo.tikxml.converter.htmlescape.StringEscapeUtils import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig import io.ktor.client.engine.okhttp.OkHttp import java.time.format.DateTimeFormatter import java.util.concurrent.TimeUnit import kotlinx.datetime.Instant import kotlinx.datetime.toKotlinInstant import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = HttpClient(OkHttp) { config(this) engine { config { retryOnConnectionFailure(true) connectTimeout(0, TimeUnit.SECONDS) } } } /** * A String TypeConverter that escapes and unescapes HTML characters directly from string. This one * uses apache 3 StringEscapeUtils borrowed from tikxml. */ actual object HtmlEscapeStringSerializer : KSerializer<String> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("EscapedString", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): String { return StringEscapeUtils.unescapeHtml4(decoder.decodeString()) } override fun serialize(encoder: Encoder, value: String) { encoder.encodeString(StringEscapeUtils.escapeHtml4(value)) } }
6
null
1
15
b5598b9af60512b2b9fbcb3fb0d5b4863ca62cc8
1,714
ZacSweers
Apache License 2.0
app-tv/src/main/kotlin/app/ss/tv/presentation/player/VideoPlayerActivity.kt
Adventech
65,243,816
false
{"Kotlin": 1669895, "Java": 17228, "CSS": 9010, "JavaScript": 7718, "HTML": 2229, "Shell": 544}
/* * Copyright (c) 2023. Adventech <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.tv.presentation.player import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.setContent import androidx.lifecycle.lifecycleScope import app.ss.models.media.SSVideo import app.ss.tv.presentation.player.service.TvVideoService import app.ss.tv.presentation.theme.SSTvTheme import com.slack.circuit.backstack.rememberSaveableBackStack import com.slack.circuit.foundation.Circuit import com.slack.circuit.foundation.CircuitCompositionLocals import com.slack.circuit.foundation.NavigableCircuitContent import com.slack.circuit.foundation.rememberCircuitNavigator import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.delay import kotlinx.coroutines.launch import ss.libraries.media.api.SSMediaPlayer import javax.inject.Inject @AndroidEntryPoint class VideoPlayerActivity : ComponentActivity() { @Inject lateinit var circuit: Circuit @Inject lateinit var mediaPlayer: SSMediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val video = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(ARG_VIDEO, SSVideo::class.java) ?: return } else { @Suppress("DEPRECATION") intent.getParcelableExtra(ARG_VIDEO) ?: return } mediaPlayer.connect(TvVideoService::class.java) setContent { CircuitCompositionLocals(circuit = circuit) { SSTvTheme { val backstack = rememberSaveableBackStack { push(VideoPlayerScreen(video)) } BackHandler(onBack = { finishAfterTransition() }) val navigator = rememberCircuitNavigator(backstack) NavigableCircuitContent(navigator, backstack) } } } } override fun onPause() { super.onPause() lifecycleScope.launch { delay(PAUSE_DELAY) mediaPlayer.onPause() } } override fun onResume() { super.onResume() mediaPlayer.onResume() } companion object { private const val ARG_VIDEO = "extra:video" private const val PAUSE_DELAY = 3000L fun launchIntent( context: Context, video: SSVideo, ): Intent = Intent(context, VideoPlayerActivity::class.java).apply { putExtra(ARG_VIDEO, video) } } }
7
Kotlin
49
171
2cc105ea76c7fdf979b0b6ee1098f413c1aa009d
3,736
sabbath-school-android
MIT License
src/commonTest/kotlin/testfixture.kt
jillesvangurp
271,782,317
false
null
import search.Document import search.DocumentIndex import search.TextFieldIndex import kotlin.random.Random data class SampleObject( val title: String, val description: String, val id: String = Random.nextLong(0, Long.MAX_VALUE).toString() ) { fun toDoc() = Document( id, mapOf( "title" to listOf(title), "description" to listOf(description) ) ) } fun testIndex(): DocumentIndex { val documentIndex = DocumentIndex( mutableMapOf( "title" to TextFieldIndex(), "description" to TextFieldIndex() ) ) listOf( SampleObject( id = "lorem", title = "Lorem ipsum", description = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """.trimIndent() ), SampleObject( id = "hamlet", title = "Hamlet", description = """A famous play by Shakespeare that contains a nice edge case for search engines "To Be, Or Not To Be" consisting of stop words.""" ), SampleObject( id="ktjsearch", title = "Ktjsearch", description = "Ktjsearch is an alternative to both solr and elasticsearch that does not use lucene." ), SampleObject( id="solr", title = "Apache Solr & Lucene", description = "An alternative to Elasticsearch that lives in the same OSS project as Apache Lucene, which is used by both but not by ktjsearch." ), SampleObject( id="es", title = "Elasticsearch, you know for search", description = "Elasticsearch is something you should consider using instead of Ktjsearch. Unless you need offline search of course." ) ).map(SampleObject::toDoc).forEach(documentIndex::index) return documentIndex }
0
Kotlin
1
3
6f576df774fc9967be8ae3e58746da7d3480ad9a
2,297
ktjsearch
MIT License
app/src/main/java/dev/tcode/thinmp/view/cell/ShortcutCellView.kt
tcode-dev
392,735,283
false
{"Kotlin": 248408}
package dev.tcode.thinmp.view.cell import android.net.Uri import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.tcode.thinmp.constant.StyleConstant import dev.tcode.thinmp.repository.realm.ItemType import dev.tcode.thinmp.view.image.ImageView import dev.tcode.thinmp.view.text.PrimaryTextView import dev.tcode.thinmp.view.text.SecondaryTextView @Composable fun ShortcutCellView( primaryText: String, secondaryText: String, uri: Uri, type: ItemType, modifier: Modifier = Modifier ) { BoxWithConstraints { val size = with(LocalDensity.current) { constraints.maxWidth.toDp() } Column(modifier = modifier) { Box { if (type === ItemType.ARTIST) { ImageView( uri = uri, contentScale = ContentScale.FillWidth, modifier = Modifier .size(size) .clip(CircleShape) ) } else { ImageView( uri = uri, modifier = Modifier .width(size) .height(size) .clip(RoundedCornerShape(StyleConstant.IMAGE_CORNER_SIZE.dp)) ) } } Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxWidth() .padding(top = StyleConstant.PADDING_TINY.dp) ) { PrimaryTextView(primaryText) } Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth() ) { SecondaryTextView(secondaryText) } } } }
0
Kotlin
0
7
ecd7a7585788d0d4355dbfa596aa56f27dec0087
2,356
ThinMP_Android_Kotlin
MIT License
src/main/kotlin/de/bund/digitalservice/useid/widget/WidgetController.kt
digitalservicebund
475,364,510
false
null
package de.bund.digitalservice.useid.widget import de.bund.digitalservice.useid.config.REQUEST_ATTR_CSP_NONCE import de.bund.digitalservice.useid.tenant.REQUEST_ATTR_TENANT import de.bund.digitalservice.useid.tenant.Tenant import de.bund.digitalservice.useid.tracking.matomo.MatomoEvent import io.micrometer.core.annotation.Timed import org.springframework.context.ApplicationEventPublisher import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestAttribute import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.servlet.ModelAndView import ua_parser.Client import ua_parser.Parser import java.net.URLEncoder import kotlin.text.Charsets.UTF_8 internal const val WIDGET_PAGE = "widget" internal const val INCOMPATIBLE_PAGE = "incompatible" const val FALLBACK_PAGE = "eID-Client" const val WIDGET_START_IDENT_BTN_CLICKED = "start-ident-button-clicked" /* Documentation about the link syntax can be found in Technical Guideline TR-03124-1 – eID-Client, Part 1: Specifications Version 1.4 8. October 2021, Chapter 2.2 Full eID-Client Note: Replaced the prefix eid:// with bundesident:// to make sure only the BundesIdent app is opened */ private const val eIdClientBaseUrl = "bundesident://127.0.0.1:24727/eID-Client" @Controller @Timed class WidgetController( private val widgetTracking: WidgetTracking, private val applicationEventPublisher: ApplicationEventPublisher, ) { @PostMapping("/$WIDGET_START_IDENT_BTN_CLICKED") fun handleStartIdentButtonClicked( @RequestParam(required = false, name = "hash") sessionHash: String?, @RequestAttribute(required = false, name = REQUEST_ATTR_TENANT) tenant: Tenant?, @RequestHeader(name = HttpHeaders.USER_AGENT, required = false) userAgent: String?, ): ResponseEntity<String> { publishMatomoEvent( widgetTracking.actions.buttonPressed, widgetTracking.names.startIdent, sessionHash, userAgent, tenant?.id, ) return ResponseEntity.status(HttpStatus.OK).body("") } @GetMapping("/$WIDGET_PAGE") fun getWidgetPage( model: Model, @RequestHeader(name = HttpHeaders.USER_AGENT, required = false) userAgent: String?, @RequestParam hostname: String, @RequestParam(required = false, name = "hash") sessionHash: String?, @RequestAttribute(name = REQUEST_ATTR_TENANT) tenant: Tenant, @RequestAttribute(name = REQUEST_ATTR_CSP_NONCE) cspNonce: String, ): ModelAndView { publishMatomoEvent( widgetTracking.actions.loaded, widgetTracking.names.widget, sessionHash, userAgent, tenant.id, ) if (isIncompatibleOSVersion(userAgent)) { return handleRequestWithIncompatibleOSVersion(sessionHash, userAgent, tenant) } val modelAndView = ModelAndView(WIDGET_PAGE) modelAndView.addObject("tenantId" to tenant.id) modelAndView.addObject("cspNonce" to cspNonce) return modelAndView } @GetMapping("/$FALLBACK_PAGE") fun getUniversalLinkFallbackPage( model: Model, @RequestParam tcTokenURL: String, @RequestParam(required = false, name = "hash") sessionHash: String?, @RequestAttribute(required = false, name = REQUEST_ATTR_TENANT) tenant: Tenant?, @RequestAttribute(name = REQUEST_ATTR_CSP_NONCE) cspNonce: String, @RequestHeader(name = HttpHeaders.USER_AGENT, required = false) userAgent: String?, ): ModelAndView { publishMatomoEvent( widgetTracking.actions.loaded, widgetTracking.names.fallback, sessionHash, userAgent, tenant?.id, ) val modelAttributes = mapOf( "eidClientURL" to "$eIdClientBaseUrl?tcTokenURL=${URLEncoder.encode(tcTokenURL, UTF_8)}", "isFallback" to true, "additionalClass" to "fallback", "tenantId" to tenant?.id, "cspNonce" to cspNonce, ) val modelAndView = ModelAndView(WIDGET_PAGE) modelAndView.addAllObjects(modelAttributes) return modelAndView } private fun publishMatomoEvent( action: String, name: String, sessionId: String?, userAgent: String?, tenantId: String?, ) { val matomoEvent = MatomoEvent(this, widgetTracking.categories.widget, action, name, sessionId, userAgent, tenantId) applicationEventPublisher.publishEvent(matomoEvent) } private fun isIncompatibleOSVersion(userAgent: String?): Boolean { return try { val parsedUserAgent = Parser().parse(userAgent) val incompatibleIOSVersion = hasIncompatibleMajorVersion(parsedUserAgent, "iOS", 15) val incompatibleAndroidVersion = hasIncompatibleMajorVersion(parsedUserAgent, "Android", 9) incompatibleIOSVersion || incompatibleAndroidVersion } catch (exception: Exception) { false } } private fun hasIncompatibleMajorVersion(parsedUserAgent: Client, osFamily: String, supportedMajorVersion: Int): Boolean { return parsedUserAgent.os.family == osFamily && !parsedUserAgent.os.major.isNullOrEmpty() && Integer.parseInt(parsedUserAgent.os.major) < supportedMajorVersion } private fun handleRequestWithIncompatibleOSVersion(sessionHash: String?, userAgent: String?, tenant: Tenant): ModelAndView { publishMatomoEvent( widgetTracking.actions.loaded, widgetTracking.names.incompatible, sessionHash, userAgent, tenant.id, ) val modelAndView = ModelAndView(INCOMPATIBLE_PAGE) modelAndView.addObject("tenantId" to tenant.id) return modelAndView } }
4
Kotlin
1
6
af592ec6c839a4b4aa9912973028efe4a774fc6f
6,274
useid-backend-service
MIT License
app/src/main/java/com/yancy/imageutils/test/Test01.kt
Reign9201
220,896,678
false
null
package com.yancy.imageutils.test /** * 说明: * @author Yancy * @date 2019/11/11 */ fun main(){ ""?.apply { print(999) } }
3
C++
13
56
5774f112a0e79560ed8e0a022bc7dca44d25117e
142
ImageUtils
Apache License 2.0
app/src/main/java/liou/rayyuan/ebooksearchtaiwan/utils/FragmentArgumentsDelegate.kt
YuanLiou
111,275,765
false
{"Kotlin": 199712, "Shell": 1384}
package liou.rayyuan.ebooksearchtaiwan.utils import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class FragmentArgumentsDelegate<T : Any> : ReadWriteProperty<Fragment, T> { var value: T? = null @Suppress("UNCHECKED_CAST") // Uncheck argument.get casting override fun getValue(thisRef: Fragment, property: KProperty<*>): T { if (value == null) { val argument = thisRef.arguments ?: throw IllegalStateException("Cannot read property ${property.name} if no argument have been set.") value = argument.get(property.name) as T } return value ?: throw IllegalStateException("Property ${property.name} could not be read.") } override fun setValue( thisRef: Fragment, property: KProperty<*>, value: T ) { if (thisRef.arguments == null) { thisRef.arguments = Bundle() } val argument = thisRef.arguments!! val key = property.name argument.putAll(bundleOf(key to value)) } }
1
Kotlin
4
40
d767ad0d5b778b14fc68809e265bec5633b2aaed
1,157
TaiwanEbookSearch
MIT License
adaptive-kotlin-plugin/testData/box/base/delegated/basic.kt
spxbhuhb
788,711,010
false
{"Kotlin": 1058159, "CSS": 47382, "Java": 18012, "HTML": 2759, "JavaScript": 896}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package stuff import hu.simplexion.adaptive.base.* import hu.simplexion.adaptive.base.registry.* import hu.simplexion.adaptive.base.testing.* @Delegated fun Adaptive.text() { manualImplementation() } class AdaptiveText<BT>( adapter: AdaptiveAdapter<BT>, parent: AdaptiveFragment<BT>?, index: Int ) : AdaptiveFragment<BT>(adapter, parent, index, 0) { override fun genBuild(parent: AdaptiveFragment<BT>, declarationIndex: Int): AdaptiveFragment<BT>? = null override fun genPatchDescendant(fragment: AdaptiveFragment<BT>) = Unit override fun genPatchInternal() = Unit } fun box() : String { val adapter = AdaptiveTestAdapter() adapter.fragmentImplRegistry += AdaptiveFragmentImplRegistryEntry("stuff.AdaptiveText") { a, p, i -> AdaptiveText(a, p, i) } adaptive(adapter) { text() } return adapter.assert(listOf( TraceEvent("<root>", 2, "before-Create", ""), TraceEvent("<root>", 2, "before-Patch-External", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "after-Patch-External", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "before-Patch-Internal", "createMask: 0xffffffff thisMask: 0xffffffff state: []"), TraceEvent("<root>", 2, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: []"), TraceEvent("AdaptiveText", 3, "before-Create", ""), TraceEvent("AdaptiveText", 3, "before-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: []"), TraceEvent("AdaptiveText", 3, "after-Patch-External", "createMask: 0x00000000 thisMask: 0xffffffff state: []"), TraceEvent("AdaptiveText", 3, "before-Patch-Internal", "createMask: 0x00000000 thisMask: 0xffffffff state: []"), TraceEvent("AdaptiveText", 3, "after-Patch-Internal", "createMask: 0x00000000 thisMask: 0x00000000 state: []"), TraceEvent("AdaptiveText", 3, "after-Create", ""), TraceEvent("<root>", 2, "after-Create", ""), TraceEvent("<root>", 2, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveText", 3, "before-Mount", "bridge: 1"), TraceEvent("AdaptiveText", 3, "after-Mount", "bridge: 1"), TraceEvent("<root>", 2, "after-Mount", "bridge: 1") )) }
1
Kotlin
0
0
75ec9b0c6a9f89359a08ce992affab493475ca4c
2,442
adaptive
Apache License 2.0
app/src/main/java/com/faldez/shachi/data/model/PostTag.kt
faldez
457,580,136
false
null
package com.faldez.shachi.data.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Fts4 import androidx.room.FtsOptions @Fts4(tokenizer = FtsOptions.TOKENIZER_UNICODE61, tokenizerArgs = ["tokenchars='"]) @Entity(tableName = "post_tag") data class PostTag( @ColumnInfo(name = "post_id") val postId: Int, @ColumnInfo(name = "server_id") val serverId: Int, val tags: String, )
8
Java
1
20
6491f53f06ae2aeb6cd786fb9f4fe7cb21958540
422
shachi
Apache License 2.0
core/src/main/kotlin/GitInfo.kt
4ds23d
742,029,131
false
{"Kotlin": 16997, "Shell": 1133}
package org.example import org.example.commands.* import org.example.commands.BranchFilter import org.example.commands.FindBranchesToMerge import org.example.commands.FindUnmergeCommits import org.example.commands.MergeCommand import org.example.ticket.JiraTicketParser class GitInfo(private val settings: GitSettings) { fun hasUncommitedChanges(): Boolean { val command = StatusCommand(settings.path) return command.hasUncommitedChanges() } fun pullBranch(branch: Branch) { OsCommand("git pull origin ${branch}", settings.path).executeOrThrow() } fun findWorkingTickets(from: Branch? = null): List<Ticket> { val command = FindUnmergeCommits(settings.path) return command.commitMessages(settings.releaseBranch, from ?: settings.developBranch) .map { it.messageLog } .flatMap { JiraTicketParser().findTickets(it) } .distinct() } fun findWorkingCommits(from: Branch? = null): List<Commit> { val command = FindUnmergeCommits(settings.path) return command.commitMessages(settings.releaseBranch, from ?: settings.developBranch) .map { Commit(it.messageLog) } } fun findUnmergeBranches(): List<UnmergeBranch> { val command = FindBranchesToMerge(settings.path) val unmergeBranchToRelease = command.execute(settings.releaseBranch) .filter { BranchFilter.HOTFIX .or(BranchFilter.RELEASE) .test(it) } .map { UnmergeBranch(settings.releaseBranch, Branch(it)) } val unmergeBranchToDevelop = command.execute(settings.developBranch) .filter { BranchFilter.HOTFIX .or(BranchFilter.RELEASE) .or { b -> b.equals(settings.releaseBranch) } .test(it) } .map { UnmergeBranch(settings.developBranch, Branch(it)) } return unmergeBranchToRelease + unmergeBranchToDevelop } fun mergeBranches(branches: List<UnmergeBranch>): List<Branch> { val mergedBranches = branches.map { MergeCommand(settings.path).execute(it) it.target } MergeCommand(settings.path).execute( UnmergeBranch( settings.developBranch, settings.releaseBranch ) ) return mergedBranches + settings.developBranch } } data class Commit(val name: String) { override fun toString(): String = name } data class Ticket(val name: String) { override fun toString(): String = name } data class Branch(val name: String) { override fun toString(): String = name } data class UnmergeBranch(val target: Branch, val from: Branch)
0
Kotlin
0
0
964ee9c88892f4b36d72524c40229e604e8cdf20
2,792
git-release
MIT License
app/src/main/java/com/mvk/galleryobvious/ui/detail/utils/FullScreenClickListener.kt
MVK059
362,666,215
false
null
package com.mvk.galleryobvious.ui.detail.utils /** * Interface to handle navigation to full screen */ interface FullScreenClickListener { /** * Handles full screen button click * * @param viewPagerPosition View pager position of the full screen image */ fun onClick(viewPagerPosition: Int) }
0
Kotlin
0
0
55fa85cfdf9df59ce269d6e4fb9f7fd6ac7f0faa
323
Gallery-Obvious
MIT License
Yum-Client/app/src/main/java/com/anbui/yum/presentation/recipe/component/HeaderItem.kt
AnBuiii
608,489,464
false
null
package com.anbui.yum.presentation.recipe.component import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Share import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun HeaderItem() { Box( modifier = Modifier .fillMaxWidth(), ) { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() .padding(top = 32.dp, start = 24.dp, end = 24.dp), ) { FilledIconButton( onClick = { /*TODO*/ }, shape = CircleShape, ) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "") } FilledIconButton( onClick = { /*TODO*/ }, shape = CircleShape, ) { Icon(imageVector = Icons.Default.Share, contentDescription = "") } } } }
0
Kotlin
0
3
94a9344aeb57403214315191304b81d15d584863
1,292
Yum
MIT License
src/main/java/org/eln2/serverage/aws/Lambda.kt
age-series
436,843,388
false
{"Kotlin": 46365}
package org.eln2.serverage.aws import org.eln2.serverage.LOGGER import software.amazon.awssdk.auth.credentials.AwsBasicCredentials import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider import software.amazon.awssdk.core.SdkBytes import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.lambda.LambdaClient import software.amazon.awssdk.services.lambda.model.* import java.util.* const val SERVER_AGE_PREFIX = "ServerAge_" /** * Lambda - a way to run AWS Lambda's. * * Security notes: * Since the lambda is not run on the server, there is no chance of code execution of the players code on the server. * To prevent the mod from doing malicious things in a person's AWS account (such as deleting all of their lambdas), we * have prefixed all the Lambda names with "ServerAge_". We present these names without that prefix in the game, but * if you actually log into your AWS console, you will see the names in that manner. * * The mod is intended to allow each user to bring their own AWS account, but it should be noted that a malicious server * administrator could take over all the accounts, given that the mod does need to also be able to operate in AWS * lambda - thus the limited control that the IAM roles should have. Examples are provided at the bottom of this file, * but use them at your own risk! * * We are also considering a mode where the server administrator can trust their users with their own account and * provide blanket AWS Lambda usage to any user, but do note that there's not much preventing users from running each * other's lambdas in that situation, since this code doesn't currently protect outside a UserParameters context. This * could probably become a configuration option in the future. * * @param userParams User parameters to get user's context. */ @Suppress("MemberVisibilityCanBePrivate", "unused") class Lambda(private val userParams: UserParameters) { /** * isRunnable - determines if Lambda is ready to run the lambda * * @return True if the lambda can be run (is in Active state) */ fun isRunnable(lambdaInstance: LambdaInstance): Boolean { return getLambdaState(lambdaInstance) == State.ACTIVE.name } /** * getLambdaState - gets the current state of the lambda * * @return One of Pending, Inactive, Active, or Failed - only Active lambdas can be run. Blank if error. */ fun getLambdaState(lambdaInstance: LambdaInstance): String { val hasValidArn = lambdaInstance.functionArn.isNotBlank() // only actually query for the function if we think we have an ARN. if (!hasValidArn) return "" return try { val functionState = userParams.lambdaClient.getFunction( GetFunctionRequest.builder().functionName(lambdaInstance.functionArn).build() ).configuration().state() functionState.name } catch (e: Exception) { LOGGER.error("Unable to get lambda state in AWS account ${userParams.getAwsAccountNumber()}") e.printStackTrace() "" } } /** * createPythonLambda - Creates a basic Python AWS Lambda * * Note: Lambda takes ~1 second to actually prepare the lambda for run, so immediately calling invoke probably fails * * @param lambdaName Name of the lambda (note that "ServerAge_" is prepended to the actual lambda name) * @param code A string containing the Python code you want to put in the lambda (function "lambda_handler" is called with event string and Lambda context) */ fun createPythonLambda(lambdaName: String, code: String): LambdaInstance? { return createLambda(lambdaName, listOf(LambdaFile("main.py", code.toByteArray())), "main.lambda_handler", Runtime.PYTHON3_9) } /** * createLambda - Creates an AWS Lambda * * Note: Lambda takes ~1 second to actually prepare the lambda for run, so immediately calling invoke probably fails * * TODO: Allow users to bring a VPC. * * @param lambdaName Name of the lambda (note that "ServerAge_" is prepended to the actual lambda name) * @param files A list of [LambdaFile]s that build up the filesystem. * @param handler Lambda Entry Point (try "main.lambda_handler" for a function "lambda_handler" in main.py) * @param language The runtime to use * @param memorySize Memory size of Lambda (in MiB) (default: 128MiB) * @param timeout How long to wait before timing out (default: 10s) */ fun createLambda(lambdaName: String, files: List<LambdaFile>, handler: String, language: Runtime, memorySize: Int = 128, timeout: Int = 10): LambdaInstance? { val realFunctionName = "$SERVER_AGE_PREFIX$lambdaName" val allAccountLambdas = userParams.lambdaClient.listFunctions().functions() if (!allAccountLambdas.none { it.functionName() == realFunctionName }) { LOGGER.info("Already have function called $realFunctionName in AWS account ${userParams.getAwsAccountNumber()}") return LambdaInstance(lambdaName, allAccountLambdas.first { it.functionName() == realFunctionName }.functionArn()) } return try { val lambdaArn = userParams.lambdaClient.createFunction( CreateFunctionRequest.builder() .architectures(Architecture.X86_64) .code(FunctionCode.builder() .zipFile(SdkBytes.fromByteArray(buildFilesystem(files))) .build()) .description("Automated Lambda from Server Age") .functionName(realFunctionName) .memorySize(memorySize) .role(userParams.lambdaRoleArn) .timeout(timeout) .handler(handler) .runtime(language) .build() ).functionArn() LambdaInstance(realFunctionName, lambdaArn) } catch (e: Exception) { LOGGER.error("Unable to create Lambda $lambdaName in AWS account ${userParams.getAwsAccountNumber()}") e.printStackTrace() null } } /** * deleteLambda - Deletes the lambda */ fun deleteLambda(lambdaInstance: LambdaInstance) { try { userParams.lambdaClient.deleteFunction( DeleteFunctionRequest.builder().functionName(lambdaInstance.functionArn).build() ) } catch (e: Exception) { LOGGER.error("Unable to delete Lambda $lambdaInstance in AWS account ${userParams.getAwsAccountNumber()}") e.printStackTrace() } } /** * runLambda * * @param event A string with event data that is passed to the lambda (typically json) * @return LambdaOutput - some fields may be blank (-1 for status code if exception caught) */ fun runLambda(lambdaInstance: LambdaInstance, event: String): LambdaOutput { return try { val resp = userParams.lambdaClient.invoke( InvokeRequest.builder() .functionName(lambdaInstance.functionArn) .payload(SdkBytes.fromUtf8String(event)) .build() ) LambdaOutput( resp.statusCode(), resp.executedVersion()?: "", resp.functionError()?: "", resp.logResult()?: "", resp.payload().asUtf8String()?: "" ) } catch (e: Exception) { LOGGER.error("Unable to run lambda $lambdaInstance in AWS account ${userParams.getAwsAccountNumber()}") e.printStackTrace() LambdaOutput(-1, "", "", "", "") } } fun listLambdas(): List<LambdaInstance> { return try { userParams.lambdaClient .listFunctions() .functions() .filter { it.functionName().startsWith(SERVER_AGE_PREFIX) } .map { LambdaInstance(it.functionName().substring(SERVER_AGE_PREFIX.length), it.functionArn()) } } catch (e: Exception) { LOGGER.error("Unable to list Lambdas in AWS account ${userParams.getAwsAccountNumber()}") e.printStackTrace() listOf() } } } /** * LambdaInstance * * @param functionName Name of the function (not the real name, the user provided name in-game) * @param functionArn the function's ARN */ data class LambdaInstance(val functionName: String, val functionArn: String) /** * Lambda Output - output from an AWS Lambda Invoke * * @param statusCode HTTP response code (typically 200) * @param executedVersion typically $LATEST * @param functionError If present, indicates an error and provides detail * @param logResult Last 4KB of execution log * @param payload The output from the function, if any. */ data class LambdaOutput( val statusCode: Int, val executedVersion: String, val functionError: String, val logResult: String, val payload: String ) /** * SERVER_REGION - sets the server's region. You can override this by setting SERVER_AWS_REGION as an env variable. * * By default, we use us-east-1 */ val SERVER_REGION: String = run { val region = System.getenv("SERVER_AWS_REGION") if (region.isNullOrBlank()) {"us-east-1"} else {region} } /** * UserParameters - Stores data about a particular Minecraft user's account. * * @param minecraftPlayerUUID The UUID of the player * @param accessKeyId the AWS Access Key ID * @param secretKey the AWS Secret Key */ data class UserParameters( val minecraftPlayerUUID: UUID, val accessKeyId: String, val secretKey: String, val lambdaRoleArn: String ) { /** * lambdaClient - the Lambda client that we can use for communicating with Lambda */ val lambdaClient: LambdaClient = LambdaClient.builder() .region(Region.of(SERVER_REGION)) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKeyId, secretKey))) .build() fun getAwsAccountNumber(): String { return try { lambdaRoleArn.split(":")[5] } catch (e: Exception) { "" } } } // Test function fun main() { val pythonCode = """ import json def lambda_handler(event, context): print("Hello from Lambda") print(json.dumps(event)) """ val accessKey = System.getenv("access_key") val secretKey = System.getenv("secret_key") val lambdaRoleArn = System.getenv("lambda_role") val up = UserParameters(minecraftPlayerUUID = UUID.randomUUID(), accessKeyId = accessKey, secretKey = secretKey, lambdaRoleArn) val lp = Lambda(up) val lambda = lp.createPythonLambda("test_lambda", pythonCode) ?: return val startTime = System.nanoTime() var stopTime: Long = 0 var tries = 1 var done = false while (tries <= 10 && !done) { if (lp.isRunnable(lambda)) { stopTime = System.nanoTime() try { LOGGER.info(lp.isRunnable(lambda)) val resp = lp.runLambda(lambda, "{\"Hello\": \"world\"}") LOGGER.info(resp) done = true } catch (e: ResourceConflictException) { println("Could not run lambda: $e") } } else { LOGGER.warn("Lambda ${lambda.functionName} is not runnable") } tries += 1 if (!done) Thread.sleep(100) } val timeMs = (stopTime - startTime) / 1_000_000 println("Time taken: $timeMs ms") val startTime2 = System.nanoTime() LOGGER.info(lp.runLambda(lambda, "")) val stopTime2 = System.nanoTime() val timeMs2 = (stopTime2 - startTime2) / 1_000_000 println("Time taken to start/complete lambda: $timeMs2 ms") lp.deleteLambda(lambda) } /* Here's a sample IAM policy that I've been using. These could be cleaned up a bit more but generally work. It shouldn't have excessive permissions (although I could be wrong). In all policies below, I've replaced my AWS account number with an `x`. CreateFunction - used to create the function InvokeFunction - used to run the function GetFunction - used to get list of functions (to prevent re-uploading) DeleteFunction - used to delete a function PassRole - permission required by CreateFunction to create the function { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "lambda:CreateFunction", "iam:PassRole", "lambda:InvokeFunction", "lambda:GetFunction", "lambda:DeleteFunction" ], "Resource": [ "arn:aws:iam::x:role/server_age_lambda_role", "arn:aws:lambda:*:x:function:ServerAge_*" ] }, { "Sid": "VisualEditor1", "Effect": "Allow", "Action": "lambda:ListFunctions", "Resource": "*" } ] } Here's a sample IAM Role for the lambda role: Ideally, it allows the lambda to log to CloudWatch { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "arn:aws:logs:us-east-1:x:*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:us-east-1:x:log-group:/aws/lambda/*" ] } ] } */ // because the resource has a comment start in it... lol. And here's the trust relationship for that role { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } */
9
Kotlin
4
4
a931be8affe989f683dc4aa75268fa98448461d0
14,070
ServerAge
MIT License
chapter-11/src/main/kotlin/password_generator/Digits.kt
erdemserhat
849,476,424
false
{"Kotlin": 64488, "Java": 629}
package com.erdemserhat.passwnote.password_generator enum class Digits(val content: String) { NUMERICAL("0123456789"), UPPER_CHARACTERISTIC("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), LOWER_CHARACTERISTIC("abcdefghijklmnopqrstuvwxyz"), SPECIAL_CHARACTERISTIC("!#\$%&'()*+,-./:;<=>?@[]^_`{|}~") }
0
Kotlin
0
0
8feaef58796d650e2f6c9dc659ec022c93fe86ab
301
Kotlin-Essentials-Notes
MIT License
src/main/kotlin/uk/gov/gdx/datashare/services/PrisonerApiService.kt
alphagov
549,031,617
false
null
package uk.gov.gdx.datashare.services import com.amazonaws.xray.spring.aop.XRayEnabled import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientResponseException import uk.gov.gdx.datashare.config.NoDataFoundException import uk.gov.gdx.datashare.models.PrisonerRecord @Service @XRayEnabled @ConditionalOnProperty(name = ["api.base.prisoner-event.enabled"], havingValue = "true") class PrisonerApiService( private val prisonerSearchApiWebClient: WebClient, ) { fun findPrisonerById(id: String): PrisonerRecord? { try { val prisonerRecord = prisonerSearchApiWebClient.get() .uri("/prisoner/{id}", id) .retrieve() .bodyToMono(PrisonerRecord::class.java) return prisonerRecord.block() } catch (e: WebClientResponseException) { throw if (e.statusCode.equals(HttpStatus.NOT_FOUND)) { NoDataFoundException(id) } else { e } } } }
2
Kotlin
0
9
999d55ced90e778afe0d7ab0ddbc2ae9201b6c82
1,153
gdx-data-share-poc
MIT License
main/src/test/java/com/work/theIsle/JvmName.kt
Tiannuo
498,562,269
false
{"Kotlin": 218272, "Java": 43175}
@file:JvmName("Hero") package com.work.theIsle /** * @Author TIKOU * @Date 2022/8/15-12:54 * @Email <EMAIL> & <EMAIL> * @Description */ fun testName() { }
0
Kotlin
2
4
bf02c12830d80c6bcf7441c50c3f685d322fdf53
161
AndroidWork
Apache License 2.0
app/src/main/java/com/example/mazena/quicknotes/editNote/EditNoteContract.kt
supermzn
118,970,376
false
null
package com.example.mazena.quicknotes.editNote import com.example.mazena.quicknotes.data.Note interface EditNoteContract { interface View { fun displayNote(note: Note) } interface Presenter { fun loadNote(id: Int) fun saveNote(updatedTitle: String, updatedDescription: String) } }
0
Kotlin
0
0
4e415856305047760a98dbee7530ac8bc84a87ae
326
quick-notes
MIT License
domain/src/main/java/com/anytypeio/anytype/domain/launch/GetDefaultObjectType.kt
anyproto
647,371,233
false
null
package com.anytypeio.anytype.domain.launch import com.anytypeio.anytype.core_models.DVFilter import com.anytypeio.anytype.core_models.DVFilterCondition import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.NO_VALUE import com.anytypeio.anytype.core_models.ObjectType import com.anytypeio.anytype.core_models.ObjectTypeUniqueKeys import com.anytypeio.anytype.core_models.ObjectWrapper import com.anytypeio.anytype.core_models.Relations import com.anytypeio.anytype.core_models.ext.mapToObjectWrapperType import com.anytypeio.anytype.core_models.primitives.SpaceId import com.anytypeio.anytype.core_models.primitives.TypeId import com.anytypeio.anytype.core_models.primitives.TypeKey import com.anytypeio.anytype.domain.base.AppCoroutineDispatchers import com.anytypeio.anytype.domain.base.ResultInteractor import com.anytypeio.anytype.domain.block.repo.BlockRepository import com.anytypeio.anytype.domain.config.ConfigStorage import com.anytypeio.anytype.domain.config.UserSettingsRepository import com.anytypeio.anytype.domain.workspace.SpaceManager import javax.inject.Inject class GetDefaultObjectType @Inject constructor( private val userSettingsRepository: UserSettingsRepository, private val blockRepository: BlockRepository, private val spaceManager: SpaceManager, private val configStorage: ConfigStorage, dispatchers: AppCoroutineDispatchers ) : ResultInteractor<Unit, GetDefaultObjectType.Response>(dispatchers.io) { override suspend fun doWork(params: Unit): Response { val space = SpaceId(spaceManager.get()) val defaultType = userSettingsRepository.getDefaultObjectType(space) if (defaultType != null) { val item = searchObjectByIdAndSpaceId( type = defaultType, space = space ) return if (item != null) { val key = TypeKey(item.uniqueKey) val id = TypeId(item.id) Response( type = key, name = item.name, id = id, defaultTemplate = item.defaultTemplateId ) } else { fetchDefaultType() } } else { return fetchDefaultType() } } private suspend fun fetchDefaultType(): Response { val structs = blockRepository.searchObjects( limit = 1, fulltext = NO_VALUE, filters = buildList { add( DVFilter( relation = Relations.UNIQUE_KEY, condition = DVFilterCondition.EQUAL, value = ObjectTypeUniqueKeys.NOTE ) ) val space = spaceManager.get().ifEmpty { // Fallback to default space. configStorage.getOrNull()?.space } if (!space.isNullOrEmpty()) { add( DVFilter( relation = Relations.SPACE_ID, condition = DVFilterCondition.EQUAL, value = space ) ) } }, offset = 0, sorts = emptyList(), keys = listOf( Relations.ID, Relations.NAME, Relations.UNIQUE_KEY, Relations.SPACE_ID, Relations.DEFAULT_TEMPLATE_ID ) ) val objType = structs.firstOrNull()?.mapToObjectWrapperType() if (objType != null) { val key = TypeKey(objType.uniqueKey) val id = TypeId(objType.id) return Response( type = key, name = objType.name, id = id, defaultTemplate = objType.defaultTemplateId ) } else { throw IllegalStateException("Default type not found") } } private suspend fun searchObjectByIdAndSpaceId( type: TypeId, space: SpaceId ): ObjectWrapper.Type? { val structs = blockRepository.searchObjects( limit = 1, fulltext = NO_VALUE, filters = buildList { addAll(filterObjectTypeLibrary(space)) add( DVFilter( relation = Relations.ID, condition = DVFilterCondition.EQUAL, value = type.id ) ) }, offset = 0, sorts = emptyList(), keys = listOf( Relations.ID, Relations.NAME, Relations.UNIQUE_KEY, Relations.SPACE_ID, Relations.DEFAULT_TEMPLATE_ID ) ) return structs.firstOrNull()?.mapToObjectWrapperType() } private fun filterObjectTypeLibrary(space: SpaceId) = listOf( DVFilter( relation = Relations.LAYOUT, condition = DVFilterCondition.EQUAL, value = ObjectType.Layout.OBJECT_TYPE.code.toDouble() ), DVFilter( relation = Relations.IS_ARCHIVED, condition = DVFilterCondition.NOT_EQUAL, value = true ), DVFilter( relation = Relations.IS_DELETED, condition = DVFilterCondition.NOT_EQUAL, value = true ), DVFilter( relation = Relations.IS_HIDDEN, condition = DVFilterCondition.NOT_EQUAL, value = true ), DVFilter( relation = Relations.SPACE_ID, condition = DVFilterCondition.EQUAL, value = space.id ) ) /** * TODO provide space to params */ data class Response( val id: TypeId, val type: TypeKey, val name: String?, val defaultTemplate: Id? ) }
45
null
43
517
b0bc38dad1f7719dabae9f7b642142df3856bad7
6,072
anytype-kotlin
RSA Message-Digest License
src/main/kotlin/com/aeolus/AeolusServiceApplication.kt
team-aeolus
668,382,094
false
null
package com.aeolus import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableScheduling @SpringBootApplication @EnableScheduling class AeolusServiceApplication fun main(args: Array<String>) { runApplication<AeolusServiceApplication>(*args) } inline fun <reified T> logger(): Logger { return LoggerFactory.getLogger(T::class.java) }
0
Kotlin
0
0
be9bca77f166baa339962c6f3264beb164f91dfb
504
aeolus-service
MIT License
app/src/main/java/se/insektionen/songbook/ui/SongbookListAdapter.kt
wsv-accidis
48,762,012
false
null
package se.insektionen.songbook.ui import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.Filter import android.widget.Filterable import android.widget.TextView import androidx.core.content.getSystemService import se.insektionen.songbook.R import se.insektionen.songbook.model.Song import java.util.Locale /** * List adapter for the list of songs in a songbook. */ class SongbookListAdapter( context: Context, initialList: List<Song> ) : BaseAdapter(), Filterable { private val filter: Filter = SongbookListFilter() private var filteredList: List<Song> = initialList private val inflater: LayoutInflater = context.getSystemService()!! private val list: List<Song> = initialList override fun getCount(): Int = filteredList.size override fun getFilter(): Filter = filter override fun getItem(position: Int): Any = filteredList[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view: View = convertView ?: inflater.inflate(R.layout.list_item_song, parent, false) val song = filteredList[position] view.findViewById<TextView>(R.id.song_list_primary).apply { text = song.name } view.findViewById<TextView>(R.id.song_list_secondary) .apply { text = formatFirstLineOfSong(song.firstLineOfSong()) } view.findViewById<TextView>(R.id.song_list_tertiary).apply { text = song.category } return view } private fun formatFirstLineOfSong(line: String): String { var result = line TRIM_START.forEach { if (result.startsWith(it)) { result = result.substring(it.length) } } TRIM_END.forEach { if (result.endsWith(it)) { result = result.substring(0, result.length - it.length) } } return result.trim() + ELLIPSIS } private inner class SongbookListFilter : Filter() { override fun performFiltering(constraint: CharSequence): FilterResults { val resultList = if (constraint.isNotEmpty()) { /* * The query is of the format {textFilter}?category={categoryFilter} * Both parts are optional. */ val query = constraint.toString() val categoryFilter: String val textFilter: String if (query.contains(CATEGORY_QUERY)) { val idx = query.indexOf(CATEGORY_QUERY) categoryFilter = query.substring(idx + CATEGORY_QUERY.length) textFilter = query.substring(0, idx) } else { categoryFilter = "" textFilter = query } list.filter { filter(it, textFilter, categoryFilter) } } else { list } return FilterResults().also { it.values = resultList it.count = resultList.size } } @Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence, results: FilterResults) { filteredList = results.values as List<Song> if (results.count > 0) { notifyDataSetChanged() } else { notifyDataSetInvalidated() } } private fun filter(song: Song, textFilter: String, categoryFilter: String): Boolean { if (categoryFilter.isNotEmpty() && song.category != categoryFilter) { // Drop any song that does not match the selected category return false } if (textFilter.isEmpty()) { // Accept any song if the text filter is empty return true } // Otherwise, apply the text filter return textFilter.isNotEmpty() && song.matches(textFilter.lowercase(Locale.getDefault())) } } companion object { const val CATEGORY_QUERY = "?category=" private const val ELLIPSIS = "..." private val TRIM_END = arrayOf(".", ",", "!", "?") private val TRIM_START = arrayOf("*", "//:") } }
1
Kotlin
6
5
1af881525ae108795d3e31fac99ce3ba91613b0c
4,512
in-sangbok
Apache License 2.0
spesialist-selve/src/main/kotlin/no/nav/helse/modell/kommando/OppdaterSnapshotUtenÅLagreWarningsCommand.kt
navikt
244,907,980
false
null
package no.nav.helse.modell.kommando import no.nav.helse.modell.SnapshotDao import no.nav.helse.modell.vedtak.snapshot.SpeilSnapshotRestClient import org.slf4j.LoggerFactory internal class OppdaterSnapshotUtenÅLagreWarningsCommand( private val speilSnapshotRestClient: SpeilSnapshotRestClient, private val snapshotDao: SnapshotDao, private val fødselsnummer: String ) : Command { private companion object { private val log = LoggerFactory.getLogger(OppdaterSnapshotUtenÅLagreWarningsCommand::class.java) } override fun execute(context: CommandContext): Boolean { return oppdaterSnapshot() } private fun oppdaterSnapshot(): Boolean { val snapshot = speilSnapshotRestClient.hentSpeilSpapshot(fødselsnummer) snapshotDao.lagre(fødselsnummer, snapshot) log.info("Oppdaterte snapshot på person: ${fødselsnummer.substring(0, 4)}*******") return true } }
2
Kotlin
0
0
e221266ef6c7edfd3335717925094aea11385c60
936
helse-spesialist
MIT License