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
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/compilationImpl/factory/KotlinCompilerOptionsFactories.kt
JetBrains
3,432,266
false
null
/* * 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.gradle.plugin.mpp.compilationImpl.factory import org.jetbrains.kotlin.gradle.dsl.* import org.jetbrains.kotlin.gradle.plugin.* import org.jetbrains.kotlin.gradle.plugin.mpp.baseModuleName import org.jetbrains.kotlin.gradle.plugin.mpp.moduleNameForCompilation import org.jetbrains.kotlin.gradle.targets.native.NativeCompilerOptions import org.jetbrains.kotlin.gradle.utils.KotlinJsCompilerOptionsDefault import org.jetbrains.kotlin.gradle.utils.KotlinJvmCompilerOptionsDefault import org.jetbrains.kotlin.gradle.utils.KotlinMultiplatformCommonCompilerOptionsDefault import org.jetbrains.kotlin.gradle.utils.klibModuleName internal object KotlinMultiplatformCommonCompilerOptionsFactory : KotlinCompilationImplFactory.KotlinCompilerOptionsFactory { override fun create(target: KotlinTarget, compilationName: String): KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options { @Suppress("TYPEALIAS_EXPANSION_DEPRECATION") val compilerOptions = object : DeprecatedHasCompilerOptions<KotlinMultiplatformCommonCompilerOptions> { override val options: KotlinMultiplatformCommonCompilerOptions = target.project.objects .KotlinMultiplatformCommonCompilerOptionsDefault(target.project) } @Suppress("DEPRECATION") val kotlinOptions = object : KotlinCommonOptions { override val options: KotlinCommonCompilerOptions get() = compilerOptions.options } return KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options(compilerOptions, kotlinOptions) } } internal object KotlinNativeCompilerOptionsFactory : KotlinCompilationImplFactory.KotlinCompilerOptionsFactory { override fun create(target: KotlinTarget, compilationName: String): KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options { val compilerOptions = NativeCompilerOptions(target.project) compilerOptions.options.moduleName.convention( target.project.klibModuleName( moduleNameForCompilation( compilationName, target.project.baseModuleName() ) ) ) @Suppress("DEPRECATION") val kotlinOptions = object : KotlinCommonOptions { override val options get() = compilerOptions.options } return KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options(compilerOptions, kotlinOptions) } } internal object KotlinJsCompilerOptionsFactory : KotlinCompilationImplFactory.KotlinCompilerOptionsFactory { override fun create(target: KotlinTarget, compilationName: String): KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options { @Suppress("TYPEALIAS_EXPANSION_DEPRECATION") val compilerOptions = object : DeprecatedHasCompilerOptions<KotlinJsCompilerOptions> { override val options: KotlinJsCompilerOptions = target.project.objects .KotlinJsCompilerOptionsDefault(target.project) } @Suppress("DEPRECATION") val kotlinOptions = object : KotlinJsOptions { override val options: KotlinJsCompilerOptions get() = compilerOptions.options } return KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options(compilerOptions, kotlinOptions) } } internal object KotlinJvmCompilerOptionsFactory : KotlinCompilationImplFactory.KotlinCompilerOptionsFactory { override fun create(target: KotlinTarget, compilationName: String): KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options { @Suppress("TYPEALIAS_EXPANSION_DEPRECATION") val compilerOptions = object : DeprecatedHasCompilerOptions<KotlinJvmCompilerOptions> { override val options: KotlinJvmCompilerOptions = target.project.objects .KotlinJvmCompilerOptionsDefault(target.project) } @Suppress("DEPRECATION") val kotlinOptions = object : KotlinJvmOptions { override val options: KotlinJvmCompilerOptions get() = compilerOptions.options } return KotlinCompilationImplFactory.KotlinCompilerOptionsFactory.Options(compilerOptions, kotlinOptions) } }
182
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
4,476
kotlin
Apache License 2.0
src/main/kotlin/com/github/chicoferreira/stockchecker/parser/impl/PCDIGAWebsiteParser.kt
chicoferreira
316,788,197
false
null
package com.github.chicoferreira.stockchecker.parser.impl import com.github.chicoferreira.stockchecker.StockCheckResult import com.github.chicoferreira.stockchecker.parser.WebsiteParser import com.github.chicoferreira.stockchecker.parser.property.ProductProperties import com.github.chicoferreira.stockchecker.util.Price import org.jsoup.nodes.Document class PCDIGAWebsiteParser : WebsiteParser { override fun parse(document: Document): StockCheckResult { val productName = document.select("meta[property=og:title]").first().attr("content") val price = document.select("meta[property=product:price:amount]").first().attr("content").toBigDecimal() val priceCurrency = document.select("meta[property=product:price:currency]").first().attr("content") val stockColumn = document.select(".col-lg-3.bg-white") val available = stockColumn.select(".product.alert.stock").isEmpty() && stockColumn.select(".product-add-form").isNotEmpty() val availableShops = LinkedHashMap<String, Boolean>() for (element in stockColumn.select(".store-stock-location")) { val availableShop = element.select(".icon-checkmark").isNotEmpty() availableShops[element.text()] = availableShop } val properties = mutableListOf(ProductProperties.PRODUCT_NAME.ofValue(productName), ProductProperties.AVAILABILITY.ofValue(available), ProductProperties.PRICE.ofValue(Price(price, priceCurrency))) if (available) properties += ProductProperties.SHOP_AVAILABILITY.ofValue(availableShops) return StockCheckResult(properties) } }
7
null
2
5
b735ba7b59dad55e2397c1e3a1f2fd3c605af498
1,721
stock-checker
MIT License
app/src/main/java/com/fransisco/catalogmoviekotlin/data/network/ApiHelper.kt
siscofran999
161,125,489
false
null
package com.fransisco.catalogmoviekotlin.data.network import com.fransisco.catalogmoviekotlin.data.model.MovieResponse import io.reactivex.Single interface ApiHelper { fun getMovieNowPlayingApiCall(): Single<MovieResponse> fun getMovieUpcomingApiCall(): Single<MovieResponse> }
0
Kotlin
0
1
29d9962e8bc0dab5dec56de8fc1944e21a7da5fe
289
movie
Apache License 2.0
editor/src/main/com/mbrlabs/mundus/editor/tools/Tool.kt
JamesTKhan
455,272,467
false
null
/* * Copyright (c) 2016. See AUTHORS file. * * 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.mbrlabs.mundus.editor.tools import com.badlogic.gdx.InputAdapter import com.badlogic.gdx.graphics.g3d.ModelBatch import com.badlogic.gdx.graphics.g3d.Shader import com.badlogic.gdx.scenes.scene2d.utils.Drawable import com.badlogic.gdx.utils.Disposable import com.mbrlabs.mundus.editor.core.project.ProjectManager import com.mbrlabs.mundus.editor.history.CommandHistory import com.mbrlabs.mundus.editor.shader.Shaders /** * @author Marcus Brummer * @version 25-12-2015 */ abstract class Tool(protected var projectManager: ProjectManager, protected var batch: ModelBatch, protected var history: CommandHistory) : InputAdapter(), Disposable { protected var shader: Shader init { shader = Shaders.wireframeShader } abstract val name: String abstract val icon: Drawable abstract val iconFont: String abstract fun render() abstract fun act() abstract fun onActivated() abstract fun onDisabled() }
7
Java
40
94
d196adb1853561aa80f68c57bcaf2a24948aa2b7
1,589
Mundus
Apache License 2.0
subprojects/gradle/qapps/src/main/kotlin/com/avito/plugin/QAppsUploadAction.kt
ussernamenikita
344,157,673
true
{"Kotlin": 2360982, "Python": 14063, "Shell": 13206, "Dockerfile": 7097, "Makefile": 35}
package com.avito.plugin import com.avito.http.RetryInterceptor import com.avito.utils.logging.CILogger import com.google.gson.GsonBuilder import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.logging.HttpLoggingInterceptor import org.funktionale.tries.Try import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.util.concurrent.TimeUnit internal class QAppsUploadAction( private val apk: File, private val comment: String, private val host: String, private val branch: String, private val versionName: String, private val versionCode: String, private val packageName: String, private val releaseChain: Boolean, private val logger: CILogger ) { fun upload(): Try<Unit> = Try { val response = uploadRequest().execute() if (!response.isSuccessful) { val error = response.errorBody()?.string() ?: "unknown error" error("Can't upload apk to qapps: $error") } } private fun uploadRequest(): Call<Void> { logger.info( "qapps upload: " + "apk=${apk.path}, " + "branch=$branch, " + "version_name=$versionName, " + "version_code=$versionCode, " + "package_name=$packageName, " + "release_chain=$releaseChain, " + "comment=$comment" ) return apiClient.upload( comment = MultipartBody.Part.createFormData("comment", comment), branch = MultipartBody.Part.createFormData("branch", branch), version_name = MultipartBody.Part.createFormData("version_name", versionName), version_code = MultipartBody.Part.createFormData("version_code", versionCode), package_name = MultipartBody.Part.createFormData("package_name", packageName), release_chain = MultipartBody.Part.createFormData("release_chain", releaseChain.toString()), apk = MultipartBody.Part.createFormData( "app", apk.name, RequestBody.create(null, apk) ) ) } private val apiClient by lazy { Retrofit.Builder() .baseUrl(host) .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) .client(httpClient()) .validateEagerly(true) .build() .create(QAppsUploadApi::class.java) } private fun httpClient() = OkHttpClient.Builder() .connectTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES) .readTimeout(1, TimeUnit.MINUTES) .addInterceptor( RetryInterceptor( retries = 3, allowedMethods = listOf("POST", "GET"), logger = { message, error -> logger.info(message, error) } ) ) .addInterceptor(HttpLoggingInterceptor { message -> logger.info(message) }.apply { level = HttpLoggingInterceptor.Level.BASIC }) .build() }
0
Kotlin
1
0
b0513404cc36196fb87ddadd1894b9015beac952
3,196
avito-android
MIT License
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/arbitraries.kt
sw-samuraj
234,562,169
true
{"Kotlin": 1832333, "JavaScript": 457, "HTML": 423, "Java": 153, "Shell": 125}
package io.kotest.property.arbitrary import io.kotest.property.Arbitrary import io.kotest.property.map import kotlin.random.Random /** * Returns an [Arbitrary] whose value is generated from the given function. */ inline fun <T> Arbitrary.Companion.create( iterations: Int, crossinline fn: () -> T ): Arbitrary<T> = object : Arbitrary<T> { override fun edgecases(): Iterable<T> = emptyList() override fun samples(random: Random): Sequence<PropertyInput<T>> = generateSequence { PropertyInput(fn()) }.take(iterations) } /** * Returns an [Arbitrary] where each random value is a Byte. * The edge cases are [[Byte.MIN_VALUE], [Byte.MAX_VALUE], 0] */ fun Arbitrary.Companion.byte(iterations: Int) = int(iterations).map { it.ushr(Int.SIZE_BITS - Byte.SIZE_BITS).toByte() }
0
null
0
0
068148734769f534223be89673639f46e8430ab4
808
kotlintest
Apache License 2.0
src/main/kotlin/day13/Day13.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day13 import groupByBlanks import mapGroups import runDay fun main() { fun part1(input: List<String>) = input.groupByBlanks() .mapGroups { it.toPacket() } .mapIndexed { index, packets -> (index + 1) to packets.first().compareTo(packets.last()) }.filter { (_, comparison) -> comparison <= 0 } .sumOf { (index) -> index } fun part2(input: List<String>) = input.groupByBlanks() .mapGroups { it.toPacket() } .flatten() .let { it + listOf( "[[2]]".toPacket(), "[[6]]".toPacket(), ) } .sorted() .mapIndexed { index, it -> index to it.toString() } .filter { (_, it) -> it in listOf( "[[2]]", "[[6]]", ) }.map { (index) -> index + 1} .fold(1) { acc, next -> acc * next } (object {}).runDay( part1 = ::part1, part1Check = 13, part2 = ::part2, part2Check = 140, ) } fun String.toPacket(): PacketData { val stack = ArrayDeque<MutableList<PacketData>>() var current = mutableListOf<PacketData>() var num = "" for (char in this) { when (char) { '[' -> { stack.addFirst(current) current = mutableListOf() } ']' -> { if (num.isNotBlank()) { current.add(IntData(num.toInt())) num = "" } val next = ListData(current) current = stack.removeFirst() current.add(next) } ',' -> { if (num.isNotBlank()) { current.add(IntData(num.toInt())) num = "" } } else -> num += char } } return current.first() } sealed interface PacketData : Comparable<PacketData> { override operator fun compareTo(other: PacketData): Int } @JvmInline value class ListData(val data: List<PacketData>) : PacketData { constructor(vararg values: PacketData) : this(values.toList()) override operator fun compareTo(other: PacketData): Int = when (other) { is IntData -> this.compareTo(ListData(other)) is ListData -> this.data.zip(other.data) .fold(0) { _, (left, right) -> val comparison = left.compareTo(right) if (comparison != 0) return comparison 0 }.let { comparison -> when (comparison) { 0 -> this.data.size.compareTo(other.data.size) else -> comparison } } } override fun toString(): String = data.joinToString( prefix = "[", postfix = "]", separator = ",", ) } @JvmInline value class IntData(val data: Int) : PacketData { override operator fun compareTo(other: PacketData): Int = when (other) { is IntData -> this.data.compareTo(other.data) is ListData -> ListData(this).compareTo(other) } override fun toString(): String = data.toString() }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
3,192
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/dev/aaa1115910/bv/screen/user/FollowScreen.kt
aaa1115910
571,702,700
false
{"Kotlin": 1537138}
package dev.aaa1115910.bv.screen.user import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.tv.material3.Border import androidx.tv.material3.ClickableSurfaceDefaults import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Surface import androidx.tv.material3.Text import coil.compose.AsyncImage import dev.aaa1115910.bv.R import dev.aaa1115910.bv.activities.video.UpInfoActivity import dev.aaa1115910.bv.component.LoadingTip import dev.aaa1115910.bv.ui.theme.BVTheme import dev.aaa1115910.bv.util.requestFocus import dev.aaa1115910.bv.viewmodel.user.FollowViewModel import org.koin.androidx.compose.koinViewModel @Composable fun FollowScreen( modifier: Modifier = Modifier, followViewModel: FollowViewModel = koinViewModel() ) { val context = LocalContext.current val scope = rememberCoroutineScope() val defaultFocusRequester = remember { FocusRequester() } var currentIndex by remember { mutableIntStateOf(0) } val showLargeTitle by remember { derivedStateOf { currentIndex < 3 } } val titleFontSize by animateFloatAsState( targetValue = if (showLargeTitle) 48f else 24f, label = "title font size" ) LaunchedEffect(followViewModel.updating) { if (!followViewModel.updating) { defaultFocusRequester.requestFocus(scope) } } Scaffold( modifier = modifier, topBar = { Box( modifier = Modifier.padding( start = 48.dp, top = 24.dp, bottom = 8.dp, end = 48.dp ) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.user_homepage_follow), fontSize = titleFontSize.sp ) Text( text = stringResource( R.string.load_data_count, followViewModel.followedUsers.size ), color = Color.White.copy(alpha = 0.6f) ) } } } ) { innerPadding -> LazyVerticalGrid( modifier = Modifier.padding(innerPadding), columns = GridCells.Fixed(3), contentPadding = PaddingValues(24.dp), verticalArrangement = Arrangement.spacedBy(18.dp), horizontalArrangement = Arrangement.spacedBy(20.dp) ) { if (!followViewModel.updating) { itemsIndexed(items = followViewModel.followedUsers) { index, up -> val upCardModifier = if (index == 0) Modifier.focusRequester(defaultFocusRequester) else Modifier UpCard( modifier = upCardModifier, face = up.avatar, sign = up.sign, username = up.name, onFocusChange = { if (it) currentIndex = index }, onClick = { UpInfoActivity.actionStart( context = context, mid = up.mid, name = up.name ) } ) } } else { item( span = { GridItemSpan(3) } ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { LoadingTip() } } } } } } @Composable fun UpCard( modifier: Modifier = Modifier, face: String, sign: String, username: String, onFocusChange: (hasFocus: Boolean) -> Unit, onClick: () -> Unit, onLongClick: () -> Unit = {} ) { Surface( modifier = modifier .onFocusChanged { onFocusChange(it.hasFocus) } .size(280.dp, 80.dp), colors = ClickableSurfaceDefaults.colors( containerColor = MaterialTheme.colorScheme.surface, focusedContainerColor = MaterialTheme.colorScheme.surface, pressedContainerColor = MaterialTheme.colorScheme.surface ), shape = ClickableSurfaceDefaults.shape(shape = MaterialTheme.shapes.large), border = ClickableSurfaceDefaults.border( focusedBorder = Border( border = BorderStroke(width = 3.dp, color = Color.White), shape = MaterialTheme.shapes.large ) ), onClick = onClick, onLongClick = onLongClick ) { Row( modifier = Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically ) { androidx.compose.material3.Surface( modifier = Modifier .padding(start = 12.dp, end = 8.dp) .size(48.dp) .clip(CircleShape), color = Color.White ) { AsyncImage( modifier = Modifier .size(48.dp) .clip(CircleShape), model = face, contentDescription = null, contentScale = ContentScale.FillBounds ) } Column { Text( text = username, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis ) Text( text = sign, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } } } @Preview @Composable fun UpCardPreview() { BVTheme { UpCard( face = "", sign = "一只业余做翻译的Klei迷,动态区UP(自称),缺氧官中反馈可私信", username = "username", onFocusChange = {}, onClick = {} ) } }
27
Kotlin
95
999
e93863f4f266485e16e1768fcea6e6b9ad0b276b
8,298
bv
MIT License
engine/src/main/kotlin/kotli/engine/DefaultTemplateContext.kt
kotlitecture
741,006,904
false
null
package kotli.engine import kotli.engine.extensions.path import kotli.engine.model.Feature import kotli.engine.model.Layer import kotli.engine.template.FileRule import kotli.engine.template.FileRules import org.slf4j.LoggerFactory import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList /** * Default execution context. */ class DefaultTemplateContext( override val layer: Layer, override val contextPath: String, private val registry: TemplateRegistry ) : TemplateContext { private val logger = LoggerFactory.getLogger(DefaultTemplateContext::class.java) override val processor: TemplateProcessor = registry.get(layer.processorId)!! private val children = ConcurrentHashMap<String, TemplateContext>() private val features = layer.features.associateBy { it.id } private val applied = ConcurrentHashMap<String, Feature>() private val removed = ConcurrentHashMap<String, Feature>() private val rules = CopyOnWriteArrayList<FileRules>() override fun getRules(): List<FileRules> = rules override fun getFeature(id: String): Feature? = features[id] override fun getChildren(): List<TemplateContext> = children.values.toList() override fun getAppliedFeatures(): List<Feature> = applied.values.toList() override fun getRemovedFeatures(): List<Feature> = removed.values.toList() override fun onApplyRules(contextPath: String, vararg rules: FileRule) { onApplyRules(FileRules(contextPath, rules.toList())) } override fun onApplyRules(rules: FileRules) { this.rules.add(rules) } override fun onApplyFeature(id: String, action: (feature: Feature) -> Unit) { applied.computeIfAbsent(id) { logger.debug("onApplyFeature :: {}", it) val feature = getFeature(id) ?: Feature(id) action(feature) feature } } override fun onRemoveFeature(id: String, action: (feature: Feature) -> Unit) { if (!applied.containsKey(id)) { removed.computeIfAbsent(id) { logger.debug("onRemoveFeature :: {}", it) val feature = getFeature(id) ?: Feature(id) action(feature) feature } } } override fun onAddChild(layer: Layer): TemplateContext? { val name = layer.name if (registry.get(layer.processorId) == null) { logger.warn("found layer with unknown processor id :: {}", layer.processorId) return null } if (children.containsKey(name)) { throw IllegalStateException("multiple children found with the same id $name") } val child = DefaultTemplateContext( contextPath = path(contextPath, layer.name), registry = registry, layer = layer ) children[name] = child return child } }
1
null
0
1
abba606fd4505e3bf1019765a74ccb808738c130
2,921
kotli-engine
MIT License
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/NumberType.kt
2219160052
270,527,875
false
{"Markdown": 3, "Gradle Kotlin DSL": 2, "INI": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Gradle": 2, "Kotlin": 286, "Java Properties": 1, "Proguard": 1, "XML": 745, "Text": 13, "Java": 1, "HTML": 2, "CSS": 3, "JavaScript": 1}
package ch.rmy.android.http_shortcuts.variables.types import android.content.Context import android.text.InputType import ch.rmy.android.http_shortcuts.data.Commons import ch.rmy.android.http_shortcuts.data.models.Variable import ch.rmy.android.http_shortcuts.extensions.mapIf import io.reactivex.Single internal class NumberType : TextType() { override fun resolveValue(context: Context, variable: Variable): Single<String> = Single.create<String> { emitter -> createDialogBuilder(context, variable, emitter) .textInput( prefill = variable.value?.takeIf { variable.rememberValue } ?: "", inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED ) { input -> emitter.onSuccess(input) Commons.setVariableValue(variable.id, input).subscribe() } .showIfPossible() } .mapIf(variable.rememberValue) { flatMap { resolvedValue -> Commons.setVariableValue(variable.id, resolvedValue) .toSingle { resolvedValue } } } }
1
null
1
1
427c4bc35f69d871145c11661839048e6b00eac1
1,248
HTTP-Shortcuts
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/cloudassembly/schema/AssemblyManifest.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.cloudassembly.schema import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.collections.Map import kotlin.jvm.JvmName /** * A manifest which describes the cloud assembly. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.cloudassembly.schema.*; * AssemblyManifest assemblyManifest = AssemblyManifest.builder() * .version("version") * // the properties below are optional * .artifacts(Map.of( * "artifactsKey", ArtifactManifest.builder() * .type(ArtifactType.NONE) * // the properties below are optional * .dependencies(List.of("dependencies")) * .displayName("displayName") * .environment("environment") * .metadata(Map.of( * "metadataKey", List.of(MetadataEntry.builder() * .type("type") * // the properties below are optional * .data("data") * .trace(List.of("trace")) * .build()))) * .properties(AwsCloudFormationStackProperties.builder() * .templateFile("templateFile") * // the properties below are optional * .assumeRoleArn("assumeRoleArn") * .assumeRoleExternalId("assumeRoleExternalId") * .bootstrapStackVersionSsmParameter("bootstrapStackVersionSsmParameter") * .cloudFormationExecutionRoleArn("cloudFormationExecutionRoleArn") * .lookupRole(BootstrapRole.builder() * .arn("arn") * // the properties below are optional * .assumeRoleExternalId("assumeRoleExternalId") * .bootstrapStackVersionSsmParameter("bootstrapStackVersionSsmParameter") * .requiresBootstrapStackVersion(123) * .build()) * .parameters(Map.of( * "parametersKey", "parameters")) * .requiresBootstrapStackVersion(123) * .stackName("stackName") * .stackTemplateAssetObjectUrl("stackTemplateAssetObjectUrl") * .tags(Map.of( * "tagsKey", "tags")) * .terminationProtection(false) * .validateOnSynth(false) * .build()) * .build())) * .missing(List.of(MissingContext.builder() * .key("key") * .props(AmiContextQuery.builder() * .account("account") * .filters(Map.of( * "filtersKey", List.of("filters"))) * .region("region") * // the properties below are optional * .lookupRoleArn("lookupRoleArn") * .owners(List.of("owners")) * .build()) * .provider(ContextProvider.AMI_PROVIDER) * .build())) * .runtime(RuntimeInfo.builder() * .libraries(Map.of( * "librariesKey", "libraries")) * .build()) * .build(); * ``` */ public interface AssemblyManifest { /** * The set of artifacts in this assembly. * * Default: - no artifacts. */ public fun artifacts(): Map<String, ArtifactManifest> = unwrap(this).getArtifacts()?.mapValues{ArtifactManifest.wrap(it.value)} ?: emptyMap() /** * Missing context information. * * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. * * Default: - no missing context. */ public fun missing(): List<MissingContext> = unwrap(this).getMissing()?.map(MissingContext::wrap) ?: emptyList() /** * Runtime information. * * Default: - no info. */ public fun runtime(): RuntimeInfo? = unwrap(this).getRuntime()?.let(RuntimeInfo::wrap) /** * Protocol version. */ public fun version(): String /** * A builder for [AssemblyManifest] */ @CdkDslMarker public interface Builder { /** * @param artifacts The set of artifacts in this assembly. */ public fun artifacts(artifacts: Map<String, ArtifactManifest>) /** * @param missing Missing context information. * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. */ public fun missing(missing: List<MissingContext>) /** * @param missing Missing context information. * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. */ public fun missing(vararg missing: MissingContext) /** * @param runtime Runtime information. */ public fun runtime(runtime: RuntimeInfo) /** * @param runtime Runtime information. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("2fbe00ae4a039ff3c7f57bbb0cdea243308a2334a847904cd126a6e8b6a47d86") public fun runtime(runtime: RuntimeInfo.Builder.() -> Unit) /** * @param version Protocol version. */ public fun version(version: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.cloudassembly.schema.AssemblyManifest.Builder = software.amazon.awscdk.cloudassembly.schema.AssemblyManifest.builder() /** * @param artifacts The set of artifacts in this assembly. */ override fun artifacts(artifacts: Map<String, ArtifactManifest>) { cdkBuilder.artifacts(artifacts.mapValues{ArtifactManifest.unwrap(it.value)}) } /** * @param missing Missing context information. * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. */ override fun missing(missing: List<MissingContext>) { cdkBuilder.missing(missing.map(MissingContext::unwrap)) } /** * @param missing Missing context information. * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. */ override fun missing(vararg missing: MissingContext): Unit = missing(missing.toList()) /** * @param runtime Runtime information. */ override fun runtime(runtime: RuntimeInfo) { cdkBuilder.runtime(runtime.let(RuntimeInfo::unwrap)) } /** * @param runtime Runtime information. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("2fbe00ae4a039ff3c7f57bbb0cdea243308a2334a847904cd126a6e8b6a47d86") override fun runtime(runtime: RuntimeInfo.Builder.() -> Unit): Unit = runtime(RuntimeInfo(runtime)) /** * @param version Protocol version. */ override fun version(version: String) { cdkBuilder.version(version) } public fun build(): software.amazon.awscdk.cloudassembly.schema.AssemblyManifest = cdkBuilder.build() } private class Wrapper( override val cdkObject: software.amazon.awscdk.cloudassembly.schema.AssemblyManifest, ) : CdkObject(cdkObject), AssemblyManifest { /** * The set of artifacts in this assembly. * * Default: - no artifacts. */ override fun artifacts(): Map<String, ArtifactManifest> = unwrap(this).getArtifacts()?.mapValues{ArtifactManifest.wrap(it.value)} ?: emptyMap() /** * Missing context information. * * If this field has values, it means that the * cloud assembly is not complete and should not be deployed. * * Default: - no missing context. */ override fun missing(): List<MissingContext> = unwrap(this).getMissing()?.map(MissingContext::wrap) ?: emptyList() /** * Runtime information. * * Default: - no info. */ override fun runtime(): RuntimeInfo? = unwrap(this).getRuntime()?.let(RuntimeInfo::wrap) /** * Protocol version. */ override fun version(): String = unwrap(this).getVersion() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): AssemblyManifest { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.cloudassembly.schema.AssemblyManifest): AssemblyManifest = Wrapper(cdkObject) internal fun unwrap(wrapped: AssemblyManifest): software.amazon.awscdk.cloudassembly.schema.AssemblyManifest = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.cloudassembly.schema.AssemblyManifest } }
4
Kotlin
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
8,145
kotlin-cdk-wrapper
Apache License 2.0
vck-openid/src/commonTest/kotlin/at/asitplus/wallet/lib/oidc/DummyCredentialDataProvider.kt
a-sit-plus
602,578,639
false
{"Kotlin": 1076316}
package at.asitplus.wallet.lib.oidc import at.asitplus.KmmResult import at.asitplus.catching import at.asitplus.signum.indispensable.CryptoPublicKey import at.asitplus.wallet.eupid.EuPidCredential import at.asitplus.wallet.eupid.EuPidScheme import at.asitplus.wallet.lib.agent.ClaimToBeIssued import at.asitplus.wallet.lib.agent.CredentialToBeIssued import at.asitplus.wallet.lib.agent.IssuerCredentialDataProvider import at.asitplus.wallet.lib.data.AtomicAttribute2023 import at.asitplus.wallet.lib.data.ConstantIndex import at.asitplus.wallet.lib.data.ConstantIndex.AtomicAttribute2023.CLAIM_DATE_OF_BIRTH import at.asitplus.wallet.lib.data.ConstantIndex.AtomicAttribute2023.CLAIM_FAMILY_NAME import at.asitplus.wallet.lib.data.ConstantIndex.AtomicAttribute2023.CLAIM_GIVEN_NAME import at.asitplus.wallet.lib.data.ConstantIndex.AtomicAttribute2023.CLAIM_PORTRAIT import at.asitplus.wallet.lib.iso.IssuerSignedItem import at.asitplus.wallet.mdl.DrivingPrivilege import at.asitplus.wallet.mdl.DrivingPrivilegeCode import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.AGE_OVER_18 import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.BIRTH_DATE import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.DOCUMENT_NUMBER import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.DRIVING_PRIVILEGES import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.EXPIRY_DATE import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.FAMILY_NAME import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.GIVEN_NAME import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.ISSUE_DATE import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.ISSUING_AUTHORITY import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.ISSUING_COUNTRY import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.PORTRAIT import at.asitplus.wallet.mdl.MobileDrivingLicenceDataElements.UN_DISTINGUISHING_SIGN import at.asitplus.wallet.mdl.MobileDrivingLicenceScheme import kotlinx.datetime.Clock import kotlinx.datetime.LocalDate import kotlin.random.Random import kotlin.time.Duration.Companion.minutes class DummyCredentialDataProvider( private val clock: Clock = Clock.System, ) : IssuerCredentialDataProvider { private val defaultLifetime = 1.minutes override fun getCredential( subjectPublicKey: CryptoPublicKey, credentialScheme: ConstantIndex.CredentialScheme, representation: ConstantIndex.CredentialRepresentation, claimNames: Collection<String>? ): KmmResult<CredentialToBeIssued> = catching { val issuance = clock.now() val expiration = issuance + defaultLifetime if (credentialScheme == ConstantIndex.AtomicAttribute2023) { val subjectId = subjectPublicKey.didEncoded val claims = listOfNotNull( optionalClaim(claimNames, CLAIM_GIVEN_NAME, "Susanne"), optionalClaim(claimNames, CLAIM_FAMILY_NAME, "Meier"), optionalClaim(claimNames, CLAIM_DATE_OF_BIRTH, LocalDate.parse("1990-01-01")), optionalClaim(claimNames, CLAIM_PORTRAIT, Random.nextBytes(32)), ) when (representation) { ConstantIndex.CredentialRepresentation.SD_JWT -> CredentialToBeIssued.VcSd( claims = claims, expiration = expiration, ) ConstantIndex.CredentialRepresentation.PLAIN_JWT -> CredentialToBeIssued.VcJwt( subject = AtomicAttribute2023(subjectId, CLAIM_GIVEN_NAME, "Susanne"), expiration = expiration, ) ConstantIndex.CredentialRepresentation.ISO_MDOC -> CredentialToBeIssued.Iso( issuerSignedItems = claims.mapIndexed { index, claim -> issuerSignedItem(claim.name, claim.value, index.toUInt()) }, expiration = expiration, ) } } else if (credentialScheme == MobileDrivingLicenceScheme) { val drivingPrivilege = DrivingPrivilege( vehicleCategoryCode = "B", issueDate = LocalDate.parse("2023-01-01"), expiryDate = LocalDate.parse("2033-01-31"), codes = arrayOf(DrivingPrivilegeCode(code = "B")) ) var digestId = 0U val issuerSignedItems = listOfNotNull( if (claimNames.isNullOrContains(FAMILY_NAME)) issuerSignedItem(FAMILY_NAME, "Mustermann", digestId++) else null, if (claimNames.isNullOrContains(GIVEN_NAME)) issuerSignedItem(GIVEN_NAME, "Max", digestId++) else null, if (claimNames.isNullOrContains(BIRTH_DATE)) issuerSignedItem(BIRTH_DATE, LocalDate.parse("1970-01-01"), digestId++) else null, if (claimNames.isNullOrContains(DOCUMENT_NUMBER)) issuerSignedItem(DOCUMENT_NUMBER, "123456789", digestId++) else null, if (claimNames.isNullOrContains(ISSUE_DATE)) issuerSignedItem(ISSUE_DATE, LocalDate.parse("2023-01-01"), digestId++) else null, if (claimNames.isNullOrContains(EXPIRY_DATE)) issuerSignedItem(EXPIRY_DATE, LocalDate.parse("2033-01-01"), digestId++) else null, if (claimNames.isNullOrContains(ISSUING_COUNTRY)) issuerSignedItem(ISSUING_COUNTRY, "AT", digestId++) else null, if (claimNames.isNullOrContains(ISSUING_AUTHORITY)) issuerSignedItem(ISSUING_AUTHORITY, "AT", digestId++) else null, if (claimNames.isNullOrContains(PORTRAIT)) issuerSignedItem(PORTRAIT, Random.nextBytes(32), digestId++) else null, if (claimNames.isNullOrContains(UN_DISTINGUISHING_SIGN)) issuerSignedItem(UN_DISTINGUISHING_SIGN, "AT", digestId++) else null, if (claimNames.isNullOrContains(DRIVING_PRIVILEGES)) issuerSignedItem(DRIVING_PRIVILEGES, arrayOf(drivingPrivilege), digestId++) else null, if (claimNames.isNullOrContains(AGE_OVER_18)) issuerSignedItem(AGE_OVER_18, true, digestId++) else null, ) CredentialToBeIssued.Iso( issuerSignedItems = issuerSignedItems, expiration = expiration, ) } else if (credentialScheme == EuPidScheme) { val subjectId = subjectPublicKey.didEncoded val familyName = "Musterfrau" val givenName = "Maria" val birthDate = LocalDate.parse("1970-01-01") val issuingCountry = "AT" val nationality = "FR" val claims = listOfNotNull( optionalClaim(claimNames, EuPidScheme.Attributes.FAMILY_NAME, familyName), optionalClaim(claimNames, EuPidScheme.Attributes.GIVEN_NAME, givenName), optionalClaim(claimNames, EuPidScheme.Attributes.BIRTH_DATE, birthDate), optionalClaim(claimNames, EuPidScheme.Attributes.AGE_OVER_18, true), optionalClaim(claimNames, EuPidScheme.Attributes.NATIONALITY, nationality), optionalClaim(claimNames, EuPidScheme.Attributes.ISSUANCE_DATE, issuance), optionalClaim(claimNames, EuPidScheme.Attributes.EXPIRY_DATE, expiration), optionalClaim(claimNames, EuPidScheme.Attributes.ISSUING_COUNTRY, issuingCountry), optionalClaim(claimNames, EuPidScheme.Attributes.ISSUING_AUTHORITY, issuingCountry), ) when (representation) { ConstantIndex.CredentialRepresentation.SD_JWT -> CredentialToBeIssued.VcSd( claims = claims, expiration = expiration ) ConstantIndex.CredentialRepresentation.PLAIN_JWT -> CredentialToBeIssued.VcJwt( EuPidCredential( id = subjectId, familyName = familyName, givenName = givenName, birthDate = birthDate, ageOver18 = true, issuanceDate = issuance, expiryDate = expiration, issuingCountry = issuingCountry, issuingAuthority = issuingCountry, ), expiration, ) ConstantIndex.CredentialRepresentation.ISO_MDOC -> CredentialToBeIssued.Iso( issuerSignedItems = claims.mapIndexed { index, claim -> issuerSignedItem(claim.name, claim.value, index.toUInt()) }, expiration = expiration, ) } } else { throw NotImplementedError() } } private fun Collection<String>?.isNullOrContains(s: String) = this == null || contains(s) private fun optionalClaim(claimNames: Collection<String>?, name: String, value: Any) = if (claimNames.isNullOrContains(name)) ClaimToBeIssued(name, value) else null private fun issuerSignedItem(name: String, value: Any, digestId: UInt) = IssuerSignedItem( digestId = digestId, random = Random.nextBytes(16), elementIdentifier = name, elementValue = value ) }
23
Kotlin
1
22
6f29a2ba84aceda63026afcfc8fd6cc0d8ccbb00
9,559
vck
Apache License 2.0
back/booking-hotel/src/main/kotlin/com/tcc/bookinghotel/domain/usecase/CreateService.kt
marcelop3251
485,967,635
false
null
package com.tcc.bookinghotel.domain.usecase import com.tcc.bookinghotel.domain.entity.Service import com.tcc.bookinghotel.domain.repository.ServiceRepository class CreateService( val serviceRepository: ServiceRepository ) { suspend fun execute(service: Service): Service { return serviceRepository.create(service) } }
0
Kotlin
0
0
9ad938f00caf6f9ff8edde4439d6f5ac0d940f41
340
booking-hotel
Apache License 2.0
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/options/EagerOption.kt
ajalt
128,975,548
false
null
package com.github.ajalt.clikt.parameters.options import com.github.ajalt.clikt.core.* import com.github.ajalt.clikt.parsers.FlagOptionParser import com.github.ajalt.clikt.parsers.OptionParser /** * An [Option] with no values that is [finalize]d before other types of options. * * @param callback This callback is called when the option is encountered on the command line. If * you want to print a message and halt execution normally, you should throw a [PrintMessage] * exception. If you want to exit normally without printing a message, you should throw * [`Abort(error=false)`][Abort]. The callback is passed the current execution context as a * parameter. */ class EagerOption( override val names: Set<String>, override val nvalues: Int, override val optionHelp: String, override val hidden: Boolean, override val helpTags: Map<String, String>, override val groupName: String?, private val callback: OptionTransformContext.() -> Unit ) : StaticallyGroupedOption { constructor(vararg names: String, nvalues: Int = 0, help: String = "", hidden: Boolean = false, helpTags: Map<String, String> = emptyMap(), groupName: String? = null, callback: OptionTransformContext.() -> Unit) : this(names.toSet(), nvalues, help, hidden, helpTags, groupName, callback) init { require(names.isNotEmpty()) { "options must have at least one name" } } override val secondaryNames: Set<String> get() = emptySet() override val parser: OptionParser = FlagOptionParser override fun metavar(context: Context): String? = null override val valueSourceKey: String? get() = null override fun postValidate(context: Context) {} override fun finalize(context: Context, invocations: List<OptionParser.Invocation>) { this.callback(OptionTransformContext(this, context)) } } internal fun helpOption(names: Set<String>, message: String): EagerOption { return EagerOption(names, 0, message, false, emptyMap(), null) { throw PrintHelpMessage(context.command) } } /** * Add an eager option to this command that, when invoked, runs [action]. * * @param name The names that can be used to invoke this option. They must start with a punctuation character. * @param help The description of this option, usually a single line. * @param hidden Hide this option from help outputs. * @param helpTags Extra information about this option to pass to the help formatter * @param groupName All options with that share a group name will be grouped together in help output. * @param action This callback is called when the option is encountered on the command line. If * you want to print a message and halt execution normally, you should throw a [PrintMessage] * exception. If you want to exit normally without printing a message, you should throw * [`Abort(error=false)`][Abort]. The callback is passed the current execution context as a * parameter. */ fun <T : CliktCommand> T.eagerOption( name: String, vararg additionalNames: String, help: String = "", hidden: Boolean = false, helpTags: Map<String, String> = emptyMap(), groupName: String? = null, action: OptionTransformContext.() -> Unit ): T = eagerOption(listOf(name) + additionalNames, help, hidden, helpTags, groupName, action) /** * Add an eager option to this command that, when invoked, runs [action]. * * @param names The names that can be used to invoke this option. They must start with a punctuation character. * @param help The description of this option, usually a single line. * @param hidden Hide this option from help outputs. * @param helpTags Extra information about this option to pass to the help formatter * @param groupName All options with that share a group name will be grouped together in help output. * @param action This callback is called when the option is encountered on the command line. If * you want to print a message and halt execution normally, you should throw a [PrintMessage] * exception. If you want to exit normally without printing a message, you should throw * [`Abort(error=false)`][Abort]. The callback is passed the current execution context as a * parameter. */ fun <T : CliktCommand> T.eagerOption( names: Collection<String>, help: String = "", hidden: Boolean = false, helpTags: Map<String, String> = emptyMap(), groupName: String? = null, action: OptionTransformContext.() -> Unit ): T = apply { registerOption(EagerOption(names.toSet(), 0, help, hidden, helpTags, groupName, action)) } /** Add an eager option to this command that, when invoked, prints a version message and exits. */ inline fun <T : CliktCommand> T.versionOption( version: String, help: String = "Show the version and exit", names: Set<String> = setOf("--version"), crossinline message: (String) -> String = { "$commandName version $it" } ): T = eagerOption(names, help) { throw PrintMessage(message(version)) }
18
null
112
2,125
4c6437bbcec237c018cbf74617ac1086b694be19
5,102
clikt
Apache License 2.0
app/src/main/java/br/com/douglasmotta/whitelabeltutorial/domain/usercase/di/DomainModule.kt
john-lobo
397,693,338
false
null
package br.com.douglasmotta.whitelabeltutorial.domain.usercase.di import br.com.douglasmotta.whitelabeltutorial.domain.usercase.* import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent @Module @InstallIn(ViewModelComponent::class) interface DomainModule { @Binds fun bindCreateProductUseCase(useCase: CreateProductUserImpl): CreateProductUseCase @Binds fun bindUpdateProductUseCase(useCase: UploadProductImageUseCaseImpl): UploadProductImageUseCase @Binds fun bindGetProductUseCase(useCase: GetProductCaseImpl): GetProductUseCase }
0
Kotlin
0
0
c1a63e0cc33b7ad323b8ef406a8f4bc19b463b9f
632
white-label
MIT License
app/src/main/java/com/example/moviedb/data/remote/response/GetMovieImages.kt
dangquanuet
127,717,732
false
{"Kotlin": 277738, "Makefile": 1159}
package com.example.moviedb.data.remote.response import com.example.moviedb.data.model.Backdrop import com.example.moviedb.data.model.Poster import com.squareup.moshi.Json data class GetMovieImages( @Json(name = "id") val id: Int? = null, @Json(name = "backdrops") val backdrops: List<Backdrop?>? = null, @Json(name = "posters") val posters: List<Poster?>? = null ) : BaseResponse()
3
Kotlin
93
413
c5031dcfa879243c0ea44d0973153078e568c013
396
The-Movie-DB-Kotlin
Apache License 2.0
src/test/kotlin/Test.kt
MushroomMif
789,811,233
false
{"Kotlin": 20194}
import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonPrimitive import com.mojang.serialization.Codec import com.mojang.serialization.DataResult import com.mojang.serialization.JsonOps import com.mojang.serialization.codecs.RecordCodecBuilder import me.mushroommif.CODEC import me.mushroommif.CodecUser import me.mushroommif.bindTo import me.mushroommif.createRecordCodec import me.mushroommif.forGet import me.mushroommif.inputCatchingMap import me.mushroommif.oneOf import me.mushroommif.requireRange import me.mushroommif.toDataResult import me.mushroommif.toResult import kotlin.test.Test import kotlin.test.assertEquals object Test { data class Person( val name: String, val age: Int, val friendName: String = "Simon" ) { companion object { val CODEC: Codec<Person> = createRecordCodec( String.CODEC bindTo "name" forGet Person::name, Int.CODEC bindTo "age" forGet Person::age, String.CODEC.optionalFieldOf("friend_name", "Simon") forGet Person::friendName, ::Person ) } } val defaultPerson = Person("Max", 34) val defaultPersonJson = JsonObject().apply { addProperty("name", "Max") addProperty("age", 34) addProperty("friend_name", "Simon") } @Test fun `Test createRecordCodec identity to default builder`() { val defaultCodec: Codec<Person> = RecordCodecBuilder.create { it.group( Codec.STRING.fieldOf("name").forGetter(Person::name), Codec.INT.fieldOf("age").forGetter(Person::age), Codec.STRING.optionalFieldOf("friend_name", "Simon").forGetter(Person::friendName) ).apply(it, ::Person) } assertEquals( defaultCodec.encodeStart(JsonOps.INSTANCE, defaultPerson), Person.CODEC.encodeStart(JsonOps.INSTANCE, defaultPerson) ) assertEquals( defaultCodec.encodeStart(JsonOps.INSTANCE, Person("Max", 34, "Jack")), Person.CODEC.encodeStart(JsonOps.INSTANCE, Person("Max", 34, "Jack")) ) } @Test fun `Test CodecUser identity to default decode and encode`() { val user = CodecUser(JsonOps.INSTANCE) assertEquals<JsonElement>( Person.CODEC.encodeStart(JsonOps.INSTANCE, defaultPerson).getOrThrow(), user.encode(defaultPerson, Person.CODEC).getOrThrow() ) assertEquals<Person>( Person.CODEC.decode(JsonOps.INSTANCE, defaultPersonJson).toResult().getOrThrow().first, user.decode(defaultPersonJson, Person.CODEC).getOrThrow() ) } @Test fun `Test result conversion`() { val successResult = Result.success(Unit) val successDataResult = DataResult.success(Unit) assertEquals(successDataResult, successResult.toDataResult()) assertEquals(successResult, successDataResult.toResult()) val failureResult = Result.failure<Unit>(Exception("Failure")) val failureDataResult = DataResult.error<Unit> { "Failure" } val convertedResult = failureResult.toDataResult() val convertedDataResult = failureDataResult.toResult() assert(convertedResult.isError) assertEquals("Failure", convertedResult.error().get().message()) assert(convertedDataResult.isFailure) assertEquals("Failure", convertedDataResult.exceptionOrNull()!!.message) } @Test fun `Test range extensions`() { val user = CodecUser(JsonOps.INSTANCE) val rangeCodec = Int.CODEC.requireRange(1, 10) val rangeCodec2 = Int.CODEC.requireRange(1..10) val floatRangeCodec = Float.CODEC.requireRange(0.3f, 1.2f) assert(user.decode(JsonPrimitive(5), rangeCodec).isSuccess) assert(user.decode(JsonPrimitive(5), rangeCodec2).isSuccess) assert(user.decode(JsonPrimitive(0), rangeCodec).isFailure) assert(user.decode(JsonPrimitive(0), rangeCodec2).isFailure) assert(user.decode(JsonPrimitive(15), rangeCodec).isFailure) assert(user.decode(JsonPrimitive(15), rangeCodec2).isFailure) assert(user.decode(JsonPrimitive(0.3f), floatRangeCodec).isSuccess) assert(user.decode(JsonPrimitive(1.4f), floatRangeCodec).isFailure) } @Test fun `Test MultipleCodec`() { var isFirstWorked = false var isSecondWorked = false val firstCodec = Int.CODEC.inputCatchingMap({ isFirstWorked = true if (it > 0) Result.success(it) else Result.failure(Exception("Number is too low")) }, { it }) val secondCodec = Int.CODEC.inputCatchingMap({ isSecondWorked = true if (it <= 0) Result.success(it) else Result.failure(Exception("Number is too high")) }, { it }) val bothCodec = oneOf(firstCodec, secondCodec) val user = CodecUser(JsonOps.INSTANCE) user.decode(JsonPrimitive(1), bothCodec) assert(isFirstWorked) assert(!isSecondWorked) user.decode(JsonPrimitive(-1), bothCodec) assert(isSecondWorked) } }
0
Kotlin
0
0
1723fd497b582c1f1fe5010a8a09d274d66950fa
5,208
Kodecs
MIT License
inngest-test-server/src/main/kotlin/com/inngest/testserver/ImageFromPrompt.kt
inngest
712,631,978
false
{"Kotlin": 82773, "Java": 45080, "Makefile": 748, "Nix": 742, "Shell": 514}
package com.inngest.testserver import com.inngest.* class ImageFromPrompt : InngestFunction() { override fun config(builder: InngestFunctionConfigBuilder): InngestFunctionConfigBuilder = builder .id("ImageFromPrompt") .name("Image from Prompt") .triggerEvent("media/prompt.created") override fun execute( ctx: FunctionContext, step: Step, ): String { val imageURL = try { step.run("generate-image-dall-e") { // Call the DALL-E model to generate an image throw Exception("Failed to generate image") "example.com/image-dall-e.jpg" } } catch (e: StepError) { // Fall back to a different image generation model step.run("generate-image-midjourney") { // Call the MidJourney model to generate an image "example.com/image-midjourney.jpg" } } try { step.invoke<Map<String, Any>>( "push-to-slack-channel", "ktor-dev", "PushToSlackChannel", mapOf("image" to imageURL), null, ) } catch (e: StepError) { // Pushing to Slack is not critical, so we can ignore the error, log it // or handle it in some other way. } return imageURL } }
7
Kotlin
3
1
0c1f5981d1cd48800c9063f00ad7b1393c158349
1,488
inngest-kt
Apache License 2.0
src/main/kotlin/com/intellij/plugin/powershell/lang/lsp/LSPInitMain.kt
ant-druha
146,094,753
false
null
/** * adopted from https://github.com/gtache/intellij-lsp */ package com.intellij.plugin.powershell.lang.lsp import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.plugin.powershell.PowerShellFileType import com.intellij.plugin.powershell.ide.run.findPsExecutable import com.intellij.plugin.powershell.lang.lsp.languagehost.EditorServicesLanguageHostStarter import com.intellij.plugin.powershell.lang.lsp.languagehost.LanguageServerEndpoint import com.intellij.plugin.powershell.lang.lsp.languagehost.ServerStatus import com.intellij.plugin.powershell.lang.lsp.languagehost.terminal.PowerShellConsoleTerminalRunner import com.intellij.plugin.powershell.lang.lsp.util.isRemotePath import java.io.File import java.util.concurrent.ConcurrentHashMap @State(name = "PowerShellSettings", storages = [Storage(value = "powerShellSettings.xml", roamingType = RoamingType.DISABLED)]) class LSPInitMain : PersistentStateComponent<LSPInitMain.PowerShellInfo>, Disposable { private val psEditorLanguageServer = ConcurrentHashMap<Project, LanguageServerEndpoint>() private val psConsoleLanguageServer = ConcurrentHashMap<Project, LanguageServerEndpoint>() override fun initializeComponent() { ApplicationManager.getApplication().messageBus.connect(this) .subscribe<ProjectManagerListener>(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosed(project: Project) { psEditorLanguageServer.remove(project) psConsoleLanguageServer.remove(project) } }) LOG.debug("PluginMain init finished") } data class PowerShellInfo( var editorServicesStartupScript: String = "", var powerShellExePath: String? = null, var powerShellVersion: String? = null, var powerShellExtensionPath: String? = null, var editorServicesModuleVersion: String? = null, var isUseLanguageServer: Boolean = true ) { constructor(isUseLanguageServer: Boolean, powerShellExePath: String?) : this("", powerShellExePath, null, null, null, isUseLanguageServer) } fun getPowerShellExecutable(): String { val psExecutable = myPowerShellInfo.powerShellExePath ?: findPsExecutable() myPowerShellInfo.powerShellExePath = psExecutable return psExecutable; } private var myPowerShellInfo: PowerShellInfo = PowerShellInfo() override fun loadState(powerShellInfo: PowerShellInfo) { myPowerShellInfo = powerShellInfo } override fun getState(): PowerShellInfo { return myPowerShellInfo } companion object { private val LOG: Logger = Logger.getInstance(LSPInitMain::class.java) @JvmStatic fun getInstance(): LSPInitMain { return ApplicationManager.getApplication().getService(LSPInitMain::class.java) } fun getServerWithConsoleProcess(project: Project): LanguageServerEndpoint { return getInstance().psConsoleLanguageServer.computeIfAbsent(project) { prj -> LanguageServerEndpoint(PowerShellConsoleTerminalRunner(prj), prj) } } private fun getEditorLanguageServer(project: Project): LanguageServerEndpoint { return getInstance().psEditorLanguageServer.computeIfAbsent(project) { prj -> LanguageServerEndpoint(EditorServicesLanguageHostStarter(prj), prj) } } fun editorOpened(editor: Editor) { val lspMain = getInstance() if (!lspMain.myPowerShellInfo.isUseLanguageServer) return val project = editor.project ?: return val file = FileDocumentManager.getInstance().getFile(editor.document) if (file == null || file.fileType !is PowerShellFileType && !isRemotePath(file.path)) return ApplicationManager.getApplication().executeOnPooledThread { val server = getServer(file, project) server.connectEditor(editor) LOG.info("Registered ${file.path} script for server: $server") } } private fun getServer(file: VirtualFile, project: Project): LanguageServerEndpoint { return findServerForRemoteFile(file, project) ?: getEditorLanguageServer(project) } fun editorClosed(editor: Editor) { val project = editor.project ?: return val vfile = FileDocumentManager.getInstance().getFile(editor.document) ?: return if (vfile.fileType !is PowerShellFileType) return val server = findServer(vfile, project) ?: return server.disconnectEditor(VfsUtil.toUri(File(vfile.path))) LOG.debug("Removed ${vfile.name} script from server: $server") } private fun findServer(file: VirtualFile, project: Project): LanguageServerEndpoint? { return findServerForRemoteFile(file, project) ?: getInstance().psEditorLanguageServer[project] } private fun findServerForRemoteFile(file: VirtualFile, project: Project): LanguageServerEndpoint? { val consoleServer = getInstance().psConsoleLanguageServer[project] ?: return null return if (consoleServer.getStatus() == ServerStatus.STARTED && isRemotePath(file.canonicalPath)) consoleServer else null } } override fun dispose() { psEditorLanguageServer.clear() psConsoleLanguageServer.clear() } }
65
null
20
72
162afd7bc53e2deee8a33c6301ed1fea418ca505
5,738
intellij-powershell
Apache License 2.0
sdk/src/main/java/com/rozetkapay/sdk/domain/models/Currency.kt
rozetkapay
869,498,229
false
{"Kotlin": 223681}
package com.rozetkapay.sdk.domain.models internal enum class Currency( val codes: List<String>, val symbol: String, ) { UAH( codes = listOf("UAH"), symbol = "₴" ), USD( codes = listOf("USD"), symbol = "$" ), EUR( codes = listOf("EUR"), symbol = "€" ), GBP( codes = listOf("GBP"), symbol = "£" ), PLN( codes = listOf("PLN"), symbol = "zł" ), CHF( codes = listOf("CHF"), symbol = "₣" ) ; companion object { private val codesMap: HashMap<String, Currency> by lazy { entries .fold(HashMap()) { map, currency -> currency.codes.forEach { code -> map[code.uppercase()] = currency } map } } fun getSymbol(currencyCode: String?): String { return getCurrency(currencyCode)?.symbol ?: currencyCode.orEmpty() } fun getCurrency(currencyCode: String?): Currency? { return if (currencyCode != null) { return codesMap[currencyCode.uppercase()] } else { null } } } }
0
Kotlin
0
0
da2574a3a8a6a9e2f04a2b47a75221c8d4c8faa8
1,229
android-sdk
MIT License
designer/src/com/android/tools/idea/uibuilder/property/ui/TransformsPanel.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.uibuilder.property.ui import com.android.SdkConstants import com.android.tools.adtui.common.lines3d import com.android.tools.adtui.common.secondaryPanelBackground import com.android.tools.idea.common.command.NlWriteCommandActionUtil import com.android.tools.idea.uibuilder.property.NlPropertiesModel import com.android.tools.idea.uibuilder.property.NlPropertyItem import com.android.tools.property.panel.api.PropertiesModel import com.android.tools.property.panel.api.PropertiesModelListener import com.android.tools.property.panel.api.PropertiesTable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.runReadAction import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.Box import javax.swing.BoxLayout import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JSlider import javax.swing.border.EmptyBorder import org.jetbrains.annotations.VisibleForTesting /** Custom panel to support direct editing of transforms (rotation, etc.) */ class TransformsPanel( private val model: NlPropertiesModel, properties: PropertiesTable<NlPropertyItem>, ) : JPanel(BorderLayout()) { private val PANEL_WIDTH = 200 private val PANEL_HEIGHT = PANEL_WIDTH + 80 private var processingChange: Boolean = false private var processingModelUpdate: Boolean = false private val propertyRotationX = properties.getOrNull(SdkConstants.ANDROID_URI, "rotationX") private val propertyRotationY = properties.getOrNull(SdkConstants.ANDROID_URI, "rotationY") private val propertyRotationZ = properties.getOrNull(SdkConstants.ANDROID_URI, "rotation") private val virtualButton = VirtualWidget() val rotationX = JSlider(-360, 360, 0) val rotationY = JSlider(-360, 360, 0) val rotationZ = JSlider(-360, 360, 0) private var listLabels = ArrayList<JLabel>() private var listValueLabels = ArrayList<JLabel>() private val modelListener = object : PropertiesModelListener<NlPropertyItem> { override fun propertyValuesChanged(model: PropertiesModel<NlPropertyItem>) { updateFromValues() } } init { val panelSize = JBUI.size(PANEL_WIDTH, PANEL_HEIGHT) preferredSize = panelSize val control = JPanel() control.layout = BoxLayout(control, BoxLayout.PAGE_AXIS) control.border = EmptyBorder(10, 10, 10, 10) add(virtualButton) add(control, BorderLayout.SOUTH) val rotationXLabel = JLabel("x") val rotationYLabel = JLabel("y") val rotationZLabel = JLabel("z") val rotationXValue = JLabel("0") val rotationYValue = JLabel("0") val rotationZValue = JLabel("0") listLabels.add(rotationXLabel) listLabels.add(rotationYLabel) listLabels.add(rotationZLabel) listValueLabels.add(rotationXValue) listValueLabels.add(rotationYValue) listValueLabels.add(rotationZValue) val mouseClickX = object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { rotationX.value = 0 } } } val mouseClickY = object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { rotationY.value = 0 } } } val mouseClickZ = object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { rotationZ.value = 0 } } } rotationX.addMouseListener(mouseClickX) rotationY.addMouseListener(mouseClickY) rotationZ.addMouseListener(mouseClickZ) rotationXValue.addMouseListener(mouseClickX) rotationYValue.addMouseListener(mouseClickY) rotationZValue.addMouseListener(mouseClickZ) val controlRotationX = JPanel() controlRotationX.layout = BoxLayout(controlRotationX, BoxLayout.LINE_AXIS) controlRotationX.add(rotationXLabel) controlRotationX.add(rotationX) controlRotationX.add(rotationXValue) val controlRotationY = JPanel() controlRotationY.layout = BoxLayout(controlRotationY, BoxLayout.LINE_AXIS) controlRotationY.add(rotationYLabel) controlRotationY.add(rotationY) controlRotationY.add(rotationYValue) val controlRotationZ = JPanel() controlRotationZ.layout = BoxLayout(controlRotationZ, BoxLayout.LINE_AXIS) controlRotationZ.add(rotationZLabel) controlRotationZ.add(rotationZ) controlRotationZ.add(rotationZValue) val controlLabel = JPanel() controlLabel.layout = BoxLayout(controlLabel, BoxLayout.LINE_AXIS) controlLabel.add(JLabel("Rotation")) controlLabel.add(Box.createHorizontalGlue()) control.add(controlLabel) control.add(controlRotationX) control.add(controlRotationY) control.add(controlRotationZ) control.background = secondaryPanelBackground controlLabel.background = secondaryPanelBackground rotationX.background = secondaryPanelBackground rotationY.background = secondaryPanelBackground rotationZ.background = secondaryPanelBackground controlRotationX.background = secondaryPanelBackground controlRotationY.background = secondaryPanelBackground controlRotationZ.background = secondaryPanelBackground virtualButton.background = secondaryPanelBackground virtualButton.foreground = lines3d rotationX.addChangeListener { processingChange = true val value = rotationX.value.toString() rotationXValue.text = value virtualButton.setRotateX(rotationX.value.toDouble()) if (!rotationX.valueIsAdjusting && !processingModelUpdate) { writeValue(propertyRotationX, value) } processingChange = false } rotationY.addChangeListener { processingChange = true val value = rotationY.value.toString() rotationYValue.text = value virtualButton.setRotateY(rotationY.value.toDouble()) if (!rotationY.valueIsAdjusting && !processingModelUpdate) { writeValue(propertyRotationY, value) } processingChange = false } rotationZ.addChangeListener { processingChange = true val value = rotationZ.value.toString() rotationZValue.text = value virtualButton.setRotate(rotationZ.value.toDouble()) if (!rotationZ.valueIsAdjusting && !processingModelUpdate) { writeValue(propertyRotationZ, value) } processingChange = false } updateFromValues() updateUI() } override fun updateUI() { super.updateUI() if (listLabels != null) { val font = UIUtil.getLabelFont(UIUtil.FontSize.SMALL) val indent = EmptyBorder(0, JBUI.scale(20), 0, 0) for (label in listLabels) { label.font = font label.border = indent } val placeholder = JLabel() placeholder.font = font placeholder.text = "XXXX" val columnSize = placeholder.preferredSize for (label in listValueLabels) { label.font = font label.preferredSize = columnSize } } } override fun addNotify() { super.addNotify() model.addListener(modelListener) } override fun removeNotify() { super.removeNotify() model.removeListener(modelListener) } private fun writeValue(property: NlPropertyItem?, value: String) { if (property == null) { return } val component = property.componentName var propertyValue: String? = value if (propertyValue == "0") { propertyValue = null // set to null as it's the default value } TransactionGuard.submitTransaction( property.model, Runnable { NlWriteCommandActionUtil.run( property.components, "Set $component.${property.name} to $propertyValue", ) { property.value = propertyValue } }, ) } private fun updateFromValues() { if (processingChange) { return } val application = ApplicationManager.getApplication() if (application.isReadAccessAllowed) { updateFromProperty() } else { runReadAction { updateFromProperty() } } } private fun updateFromProperty() { valueOf(propertyRotationX)?.let { processingModelUpdate = true virtualButton.setRotateX(it) rotationX.value = it.toInt() processingModelUpdate = false } valueOf(propertyRotationY)?.let { processingModelUpdate = true virtualButton.setRotateY(it) rotationY.value = it.toInt() processingModelUpdate = false } valueOf(propertyRotationZ)?.let { processingModelUpdate = true rotationZ.value = it.toInt() virtualButton.setRotate(it) processingModelUpdate = false } } @VisibleForTesting fun valueOf(property: NlPropertyItem?): Double? { val stringValue = property?.value?.ifEmpty { "0" } ?: "0" return try { stringValue.toDouble() } catch (ex: NumberFormatException) { 0.0 } } }
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
9,708
android
Apache License 2.0
core/testdata/typealias/asTypeBoundWithVariance.kt
Kotlin
21,763,603
false
null
package _typealias.astypebound class A typealias B = A class C<out T : B> class D<in T : B>
372
Kotlin
8
2,799
ed6c67bd55ad0211b9be40dda3027340eecd5919
93
dokka
Apache License 2.0
src/main/kotlin/com/github/strindberg/emacssearchandcase/actions/search/PreviousReplaceAction.kt
strindberg
497,232,016
false
null
package com.github.strindberg.emacssearchandcase.actions.search import com.github.strindberg.emacssearchandcase.search.PreviousReplaceHandler import com.intellij.openapi.editor.actionSystem.EditorAction class PreviousReplaceAction : ReplaceAction, EditorAction(PreviousReplaceHandler(false))
0
Kotlin
0
0
e0ca848a9808fdad645ae0fa453a3be299d6c7f3
294
emacs-search-and-case
Apache License 2.0
app/src/main/java/com/manish/shopnow/fragments/shopping/HomeFragment.kt
Manishshakya6614
804,889,000
false
{"Kotlin": 129931}
package com.manish.shopnow.fragments.shopping import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.denzcoskun.imageslider.constants.ScaleTypes import com.denzcoskun.imageslider.models.SlideModel import com.example.kelineyt.util.VerticalItemDecoration import com.google.firebase.Firebase import com.google.firebase.firestore.firestore import com.manish.shopnow.R import com.manish.shopnow.adapters.BestDealsAdapter import com.manish.shopnow.adapters.BestProductsAdapter import com.manish.shopnow.adapters.CategoryAdapter import com.manish.shopnow.adapters.OnBestDealsClickListener import com.manish.shopnow.adapters.OnBestProductClickListener import com.manish.shopnow.adapters.OnCategoryClickListener import com.manish.shopnow.adapters.OnSpecialProductClickListener import com.manish.shopnow.adapters.SpecialProductsAdapter import com.manish.shopnow.databinding.FragmentHomeBinding import com.manish.shopnow.model.CategoryModel import com.manish.shopnow.model.ProductModel import com.manish.shopnow.util.HorizontalItemDecoration import com.manish.shopnow.util.Resource import com.manish.shopnow.viewmodel.HomeViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest private val TAG = "MainCategoryFragment" @AndroidEntryPoint class HomeFragment : Fragment(R.layout.fragment_home), OnCategoryClickListener, OnSpecialProductClickListener, OnBestDealsClickListener, OnBestProductClickListener { private lateinit var binding: FragmentHomeBinding private lateinit var specialProductsAdapter: SpecialProductsAdapter private lateinit var bestDealsAdapter: BestDealsAdapter private lateinit var bestProductsAdapter: BestProductsAdapter private val viewModel by viewModels<HomeViewModel>() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentHomeBinding.bind(view) // Setting Slider Images getSliderImages() // Setting Categories Recycler View // val list = viewModel.showCategories() // binding.categoryRecyclerView.adapter = CategoryAdapter(requireContext(), list, this) showCategories() setUpSpecialProductsRV() setupBestDealsRv() setupBestProductsRV() lifecycleScope.launchWhenStarted { viewModel.specialProducts.collectLatest { when (it) { is Resource.Loading -> { showLoading() } is Resource.Success -> { specialProductsAdapter.differ.submitList(it.data) hideLoading() } is Resource.Error -> { hideLoading() Log.e(TAG, it.message.toString()) Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> Unit } } } lifecycleScope.launchWhenStarted { viewModel.bestDealsProducts.collectLatest { when (it) { is Resource.Loading -> { showLoading() } is Resource.Success -> { bestDealsAdapter.differ.submitList(it.data) hideLoading() } is Resource.Error -> { hideLoading() Log.e(TAG, it.message.toString()) Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() } else -> Unit } } } lifecycleScope.launchWhenStarted { viewModel.bestProducts.collectLatest { when (it) { is Resource.Loading -> { binding.bestProductsProgressbar.visibility = View.VISIBLE } is Resource.Success -> { bestProductsAdapter.differ.submitList(it.data) binding.bestProductsProgressbar.visibility = View.GONE } is Resource.Error -> { Log.e(TAG, it.message.toString()) Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show() binding.bestProductsProgressbar.visibility = View.GONE } else -> Unit } } } binding.etSearch.setOnClickListener { findNavController().navigate(R.id.action_homeFragment_to_searchFragment) } } private fun showLoading() { binding.homeProgressbar.visibility = View.VISIBLE } private fun setUpSpecialProductsRV() { specialProductsAdapter = SpecialProductsAdapter(this) binding.specialProductsRecyclerView.apply { adapter = specialProductsAdapter addItemDecoration(VerticalItemDecoration()) addItemDecoration(HorizontalItemDecoration()) } } private fun setupBestDealsRv() { bestDealsAdapter = BestDealsAdapter(this) binding.rvBestDealsProducts.apply { adapter = bestDealsAdapter addItemDecoration(VerticalItemDecoration()) addItemDecoration(HorizontalItemDecoration()) } } private fun setupBestProductsRV() { bestProductsAdapter = BestProductsAdapter(this) binding.rvBestProducts.apply { layoutManager = GridLayoutManager(requireContext(), 2, GridLayoutManager.VERTICAL, false) adapter = bestProductsAdapter addItemDecoration(VerticalItemDecoration()) addItemDecoration(HorizontalItemDecoration()) } } private fun hideLoading() { binding.homeProgressbar.visibility = View.GONE } private fun showCategories() { val list = ArrayList<CategoryModel>() Firebase.firestore.collection("categories") .get().addOnSuccessListener { list.clear() for (doc in it.documents) { val data = doc.toObject(CategoryModel::class.java) list.add(data!!) } binding.categoryRecyclerView.adapter = CategoryAdapter(requireContext(), list, this) } } private fun getSliderImages() { Firebase.firestore.collection("sliders").get() .addOnSuccessListener { val slideList = ArrayList<SlideModel>() for (doc in it.documents) { slideList.add(SlideModel(doc.getString("img"), ScaleTypes.CENTER_CROP)) } binding.sliderHomeImageView.setImageList(slideList) } } override fun onCategoryClick(productCat: String) { val bundle = Bundle().apply { putSerializable("cat",productCat) } findNavController().navigate(R.id.action_homeFragment_to_categoryProductsFragment,bundle) } override fun onSpecialProductClickListener(productModel: ProductModel) { val bundle = Bundle().apply { putSerializable("productModel",productModel) } findNavController().navigate(R.id.action_homeFragment_to_productDetailFragment,bundle) } override fun onBestDealsCategoryClick(productModel: ProductModel) { val bundle = Bundle().apply { putSerializable("productModel",productModel) } findNavController().navigate(R.id.action_homeFragment_to_productDetailFragment,bundle) } override fun onBestProductClick(productModel: ProductModel) { val bundle = Bundle().apply { putSerializable("productModel",productModel) } findNavController().navigate(R.id.action_homeFragment_to_productDetailFragment,bundle) } }
0
Kotlin
0
0
5ecd477e4a4d4ddfdfe0bbfd134e13c0efc07668
8,350
Shop_Now
Apache License 2.0
src/main/java/retrofit2/converter/gson/ExtendedGsonConverterFactory.kt
SoftwareAG
525,378,320
false
{"Kotlin": 769226}
package retrofit2.converter.gson import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.reflect.TypeToken import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type @Suppress("UNCHECKED_CAST") class ExtendedGsonConverterFactory(val gson: Gson = Gson()) : Converter.Factory() { override fun responseBodyConverter(type: Type, annotations: Array<out Annotation>, retrofit: Retrofit): Converter<ResponseBody, *> { val adapter: TypeAdapter<*> = gson.getAdapter(TypeToken.get(type)) return GsonResponseBodyConverter(gson, adapter) } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<out Annotation>, methodAnnotations: Array<out Annotation>, retrofit: Retrofit): Converter<*, RequestBody> { val adapter: TypeAdapter<*> = gson.getAdapter(TypeToken.get(type)) val readOnlyProperties = methodAnnotations.first { it is ReadOnlyProperties } as ReadOnlyProperties? readOnlyProperties?.let { val values: Array<String> = it.value as Array<String> return ExtendedGsonRequestBodyConverter(gson, adapter, values) } return ExtendedGsonRequestBodyConverter(gson, adapter) } }
2
Kotlin
1
3
4c09a39aced1c5fb0677eb2a099a2dcda466f4d4
1,261
cumulocity-clients-kotlin
Apache License 2.0
kotlinx-coroutines-core/js/src/JSDispatcher.kt
Kotlin
61,722,736
false
null
package kotlinx.coroutines import org.w3c.dom.* import kotlin.js.Promise internal actual typealias W3CWindow = Window internal actual fun w3cSetTimeout(window: W3CWindow, handler: () -> Unit, timeout: Int): Int = setTimeout(window, handler, timeout) internal actual fun w3cSetTimeout(handler: () -> Unit, timeout: Int): Int = setTimeout(handler, timeout) internal actual fun w3cClearTimeout(window: W3CWindow, handle: Int) = window.clearTimeout(handle) internal actual fun w3cClearTimeout(handle: Int) = clearTimeout(handle) internal actual class ScheduledMessageQueue actual constructor(private val dispatcher: SetTimeoutBasedDispatcher) : MessageQueue() { internal val processQueue: dynamic = { process() } actual override fun schedule() { dispatcher.scheduleQueueProcessing() } actual override fun reschedule() { setTimeout(processQueue, 0) } internal actual fun setTimeout(timeout: Int) { setTimeout(processQueue, timeout) } } internal object NodeDispatcher : SetTimeoutBasedDispatcher() { override fun scheduleQueueProcessing() { process.nextTick(messageQueue.processQueue) } } internal actual class WindowMessageQueue actual constructor(private val window: W3CWindow) : MessageQueue() { private val messageName = "dispatchCoroutine" init { window.addEventListener("message", { event: dynamic -> if (event.source == window && event.data == messageName) { event.stopPropagation() process() } }, true) } actual override fun schedule() { Promise.resolve(Unit).then({ process() }) } actual override fun reschedule() { window.postMessage(messageName, "*") } } // We need to reference global setTimeout and clearTimeout so that it works on Node.JS as opposed to // using them via "window" (which only works in browser) private external fun setTimeout(handler: dynamic, timeout: Int = definedExternally): Int private external fun clearTimeout(handle: Int = definedExternally) private fun setTimeout(window: Window, handler: () -> Unit, timeout: Int): Int = window.setTimeout(handler, timeout)
295
null
1850
13,033
6c6df2b850382887462eeaf51f21f58bd982491d
2,213
kotlinx.coroutines
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/ConciergeBell.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.ConciergeBell: ImageVector get() { if (_conciergeBell != null) { return _conciergeBell!! } _conciergeBell = Builder(name = "ConciergeBell", 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(24.0f, 19.0f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, -6.109f, -4.589f, -11.166f, -10.5f, -11.906f) verticalLineTo(3.0f) horizontalLineToRelative(1.5f) verticalLineTo(0.0f) horizontalLineToRelative(-6.0f) verticalLineTo(3.0f) horizontalLineToRelative(1.5f) verticalLineToRelative(2.094f) curveTo(4.589f, 5.834f, 0.0f, 10.891f, 0.0f, 17.0f) verticalLineToRelative(2.0f) horizontalLineTo(10.5f) verticalLineToRelative(2.0f) horizontalLineTo(0.0f) verticalLineToRelative(3.0f) horizontalLineTo(24.0f) verticalLineToRelative(-3.0f) horizontalLineTo(13.5f) verticalLineToRelative(-2.0f) horizontalLineToRelative(10.5f) close() moveTo(12.0f, 8.0f) curveToRelative(4.625f, 0.0f, 8.446f, 3.506f, 8.945f, 8.0f) horizontalLineTo(3.055f) curveToRelative(0.499f, -4.494f, 4.32f, -8.0f, 8.945f, -8.0f) close() } } .build() return _conciergeBell!! } private var _conciergeBell: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,489
icons
MIT License
clients/dos/src/main/kotlin/AuthorizationInterceptor.kt
oss-review-toolkit
107,540,288
false
{"Kotlin": 5110480, "JavaScript": 333852, "Shell": 127273, "HTML": 98970, "Python": 51191, "Haskell": 30438, "FreeMarker": 27693, "CSS": 27239, "Dockerfile": 19565, "Swift": 12129, "Ruby": 10007, "Roff": 7688, "Vim Snippet": 6802, "Scala": 6656, "Starlark": 3270, "Go": 1909, "C++": 882, "Java": 559, "Rust": 280, "Emacs Lisp": 191, "C": 162}
/* * Copyright (C) 2024 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.clients.dos import okhttp3.Interceptor import retrofit2.Invocation /** * A custom annotation for skipping the authorization interceptor for certain API calls. */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) internal annotation class SkipAuthorization /** * An HTTP interceptor to conditionally skip authorization. */ internal class AuthorizationInterceptor(private val token: String) : Interceptor { override fun intercept(chain: Interceptor.Chain): okhttp3.Response { val original = chain.request() val skipAuthorization = original.tag(Invocation::class.java) ?.method() ?.isAnnotationPresent(SkipAuthorization::class.java) == true if (skipAuthorization) return chain.proceed(original) val requestBuilder = original.newBuilder() .header("Authorization", "Bearer $token") .method(original.method, original.body) return chain.proceed(requestBuilder.build()) } }
304
Kotlin
309
1,590
ed4bccf37bab0620cc47dbfb6bfea8542164725a
1,779
ort
Apache License 2.0
z2-counter-kotlin-plugin/src/hu/simplexion/z2/counter/kotlin/ir/CounterAnnotationBasedExtension.kt
spxbhuhb
650,083,608
false
null
/* * Copyright © 2022-2023, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.counter.kotlin.ir import org.jetbrains.kotlin.extensions.AnnotationBasedExtension import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.descriptors.toIrBasedDescriptor interface CounterAnnotationBasedExtension : AnnotationBasedExtension { fun IrClass.isAnnotatedWithCounter(): Boolean = toIrBasedDescriptor().hasSpecialAnnotation(null) }
0
Kotlin
0
1
3f2152b5e1a6295a1277d9b0d2396872e8bd0478
528
z2-counter
Apache License 2.0
src/main/kotlin/starter/Structure.kt
kboduch
254,468,070
false
null
package starter import screeps.api.* import screeps.api.structures.Structure fun Structure.isEnergyContainer(): Boolean { return this.isStructureTypeOf(arrayOf<StructureConstant>(STRUCTURE_CONTAINER, STRUCTURE_STORAGE)) } fun Structure.isSpawnEnergyContainer(): Boolean { return this.isStructureTypeOf(arrayOf<StructureConstant>(STRUCTURE_EXTENSION, STRUCTURE_SPAWN)) } fun Structure.isHpBelowPercent(percent: Int): Boolean { return ((hits * 100) / hitsMax) < percent } fun Structure.isHpBelow(amount: Int): Boolean { return hits < amount } fun Structure.isStructureTypeOf(structureTypes: Array<StructureConstant>): Boolean { return structureTypes.contains(this.structureType) } fun Structure.isStructureTypeOf(structureType: StructureConstant): Boolean { return this.structureType == structureType }
0
Kotlin
0
0
4562be624093b44c4229a98a6ec36107a4e70de1
832
screeps
MIT License
inject/src/test/kotlin/fr/xgouchet/elmyr/inject/fixture/KotlinInjectedUnknownAnnotation.kt
xgouchet
92,030,208
false
{"Kotlin": 480997, "Java": 23870}
package fr.xgouchet.elmyr.inject.fixture import org.mockito.Mock class KotlinInjectedUnknownAnnotation { @Mock lateinit var unknownFoo: Foo fun retrieveFooOrNull(): Foo? { return if (::unknownFoo.isInitialized) { unknownFoo } else { null } } }
6
Kotlin
3
83
0ab6c3a673fd8771e9fc02f0676a3a886992a1ef
312
Elmyr
MIT License
arrow-libs/core/arrow-core/src/main/kotlin/arrow/core/extensions/listk/semialign/ListKSemialign.kt
clojj
343,913,289
true
{"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83}
package arrow.core.extensions.listk.semialign import arrow.Kind import arrow.core.ForListK import arrow.core.Ior import arrow.core.ListK import arrow.core.ListK.Companion import arrow.core.Option import arrow.core.Tuple2 import arrow.core.extensions.ListKSemialign import arrow.typeclasses.Semigroup import kotlin.Function1 import kotlin.Function2 import kotlin.PublishedApi import kotlin.Suppress import kotlin.jvm.JvmName /** * cached extension */ @PublishedApi() internal val semialign_singleton: ListKSemialign = object : arrow.core.extensions.ListKSemialign {} @JvmName("align") @Suppress( "UNCHECKED_CAST", "USELESS_CAST", "EXTENSION_SHADOWED_BY_MEMBER", "UNUSED_PARAMETER" ) @Deprecated("@extension projected functions are deprecated", ReplaceWith("arg0.align(arg1)", "arrow.core.align")) fun <A, B> align(arg0: Kind<ForListK, A>, arg1: Kind<ForListK, B>): ListK<Ior<A, B>> = arrow.core.ListK .semialign() .align<A, B>(arg0, arg1) as arrow.core.ListK<arrow.core.Ior<A, B>> @JvmName("alignWith") @Suppress( "UNCHECKED_CAST", "USELESS_CAST", "EXTENSION_SHADOWED_BY_MEMBER", "UNUSED_PARAMETER" ) @Deprecated("@extension projected functions are deprecated", ReplaceWith("arg0.alignWith(arg1, arg2)", "arrow.core.alignWith")) fun <A, B, C> alignWith( arg0: Kind<ForListK, A>, arg1: Kind<ForListK, B>, arg2: Function1<Ior<A, B>, C> ): ListK<C> = arrow.core.ListK .semialign() .alignWith<A, B, C>(arg0, arg1, arg2) as arrow.core.ListK<C> @JvmName("salign") @Suppress( "UNCHECKED_CAST", "USELESS_CAST", "EXTENSION_SHADOWED_BY_MEMBER", "UNUSED_PARAMETER" ) @Deprecated("@extension projected functions are deprecated", ReplaceWith("arg0.salign(arg1, arg2)", "arrow.core.salign")) fun <A> Kind<ForListK, A>.salign(arg1: Semigroup<A>, arg2: Kind<ForListK, A>): ListK<A> = arrow.core.ListK.semialign().run { [email protected]<A>(arg1, arg2) as arrow.core.ListK<A> } @JvmName("padZip") @Suppress( "UNCHECKED_CAST", "USELESS_CAST", "EXTENSION_SHADOWED_BY_MEMBER", "UNUSED_PARAMETER" ) @Deprecated("@extension projected functions are deprecated", ReplaceWith("arg0.padZip(arg1)", "arrow.core.padZip")) fun <A, B> Kind<ForListK, A>.padZip(arg1: Kind<ForListK, B>): ListK<Tuple2<Option<A>, Option<B>>> = arrow.core.ListK.semialign().run { [email protected]<A, B>(arg1) as arrow.core.ListK<arrow.core.Tuple2<arrow.core.Option<A>, arrow.core.Option<B>>> } @JvmName("padZipWith") @Suppress( "UNCHECKED_CAST", "USELESS_CAST", "EXTENSION_SHADOWED_BY_MEMBER", "UNUSED_PARAMETER" ) @Deprecated("@extension projected functions are deprecated", ReplaceWith("arg0.padZipWith(arg1, arg2)", "arrow.core.padZipWith")) fun <A, B, C> Kind<ForListK, A>.padZipWith( arg1: Kind<ForListK, B>, arg2: Function2<Option<A>, Option<B>, C> ): ListK<C> = arrow.core.ListK.semialign().run { [email protected]<A, B, C>(arg1, arg2) as arrow.core.ListK<C> } @Suppress( "UNCHECKED_CAST", "NOTHING_TO_INLINE" ) @Deprecated("Semialign typeclasses is deprecated. Use concrete methods on List") inline fun Companion.semialign(): ListKSemialign = semialign_singleton
0
null
0
0
5eae605bbaeb2b911f69a5bccf3fa45c42578416
3,139
arrow
Apache License 2.0
src/main/java/com/github/ai/kpdiff/domain/usecases/ReadPasswordUseCase.kt
aivanovski
607,687,384
false
null
package com.github.ai.kpdiff.domain.usecases import com.github.ai.kpdiff.data.keepass.KeepassDatabaseFactory import com.github.ai.kpdiff.domain.ErrorHandler import com.github.ai.kpdiff.domain.Strings.ENTER_A_PASSWORD import com.github.ai.kpdiff.domain.Strings.ENTER_A_PASSWORD_FOR_FILE import com.github.ai.kpdiff.domain.Strings.TOO_MANY_ATTEMPTS import com.github.ai.kpdiff.domain.input.InputReaderFactory import com.github.ai.kpdiff.domain.output.OutputPrinter import com.github.ai.kpdiff.entity.Either import com.github.ai.kpdiff.entity.KeepassKey import com.github.ai.kpdiff.entity.exception.KpDiffException import java.io.File class ReadPasswordUseCase( private val determineInputTypeUseCase: DetermineInputTypeUseCase, private val dbFactory: KeepassDatabaseFactory, private val inputReaderFactory: InputReaderFactory, private val errorHandler: ErrorHandler, private val printer: OutputPrinter ) { fun readPassword(paths: List<String>): Either<String> { val filenames = paths.map { path -> File(path).name } val inputType = determineInputTypeUseCase.getInputReaderType() val inputReader = inputReaderFactory.createReader(inputType) for (i in 1..MAX_ATTEMPTS) { if (paths.size == 1) { printer.printLine( String.format( ENTER_A_PASSWORD_FOR_FILE, filenames.first() ) ) } else { printer.printLine(ENTER_A_PASSWORD) } val password = checkPassword(paths, inputReader.read()) if (password.isRight()) { return password } else { errorHandler.handleIfLeft(password) } } return Either.Left(KpDiffException(TOO_MANY_ATTEMPTS)) } private fun checkPassword( paths: List<String>, password: String ): Either<String> { for (path in paths) { val db = dbFactory.createDatabase(path, KeepassKey.PasswordKey(password)) if (db.isLeft()) { return db.mapToLeft() } } return Either.Right(password) } companion object { internal const val MAX_ATTEMPTS = 3 } }
0
null
1
4
5b4d6ca77629cb63190679b12038c8f8e8a121aa
2,296
kp-diff
Apache License 2.0
app/src/debug/java/com/pr0gramm/app/DebugApplicationClass.kt
mopsalarm
30,804,448
false
{"Kotlin": 1414351, "Shell": 6752, "Python": 1124}
package com.pr0gramm.app import android.content.Context import android.os.Debug import android.os.StrictMode import androidx.multidex.MultiDex import com.pr0gramm.app.util.doInBackground class DebugApplicationClass : ApplicationClass() { init { StrictMode.enableDefaults() if (false) { try { // Debug.startMethodTracing(null, 128 * 1024 * 1024) Debug.startMethodTracingSampling(null, 16 * 1024 * 1024, 500) doInBackground { kotlinx.coroutines.delay(6_000) Debug.stopMethodTracing() } } catch (err: Throwable) { Logger("DebugApplicationClass").error(err) { "Could not start method sampling during bootup." } } } } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } }
39
Kotlin
38
284
d6917f3ec16b6664a90a4519843f3d3d4ccae2cf
972
Pr0
MIT License
android/src/com/android/tools/idea/welcome/wizard/AndroidStudioWelcomeScreenProvider.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.welcome.wizard import com.android.annotations.concurrency.WorkerThread import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.sdk.IdeSdks import com.android.tools.idea.ui.GuiTestingService import com.android.tools.idea.welcome.config.AndroidFirstRunPersistentData import com.android.tools.idea.welcome.config.FirstRunWizardMode import com.android.tools.idea.welcome.config.installerData import com.android.tools.idea.welcome.wizard.deprecated.FirstRunWizardHost import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.WelcomeScreen import com.intellij.openapi.wm.WelcomeScreenProvider import com.intellij.util.net.HttpConfigurable import com.intellij.util.proxy.CommonProxy import java.io.IOException import javax.swing.JRootPane val log = logger<AndroidStudioWelcomeScreenProvider>() /** * Shows a wizard first time Android Studio is launched. */ class AndroidStudioWelcomeScreenProvider : WelcomeScreenProvider { override fun createWelcomeScreen(rootPane: JRootPane): WelcomeScreen { ApplicationManager.getApplication().executeOnPooledThread { checkInternetConnection() } val wizardMode = wizardMode!! // This means isAvailable was false! Why are we even called? ourWasShown = true return if (StudioFlags.NPW_FIRST_RUN_WIZARD.get()) StudioFirstRunWelcomeScreen(wizardMode) else FirstRunWizardHost(wizardMode) } override fun isAvailable(): Boolean { val isWizardDisabled = GuiTestingService.getInstance().isGuiTestingMode || java.lang.Boolean.getBoolean(SYSTEM_PROPERTY_DISABLE_WIZARD) return !ourWasShown && !isWizardDisabled && wizardMode != null } companion object { private const val SYSTEM_PROPERTY_DISABLE_WIZARD = "disable.android.first.run" private var ourWasShown: Boolean = false // Do not show wizard multiple times in one session even if it was canceled /** * Analyzes system state and decides if and how the wizard should be invoked. * * @return one of the [FirstRunWizardMode] constants or `null` if wizard is not needed. */ // TODO: Remove this temporary code, once the Welcome Wizard is more completely ported. // This code forces the first run wizard to run every time, but eventually it should only run the first time. val wizardMode: FirstRunWizardMode? @JvmStatic get() { if (StudioFlags.NPW_FIRST_RUN_WIZARD.get() || StudioFlags.NPW_FIRST_RUN_SHOW.get()) { return FirstRunWizardMode.NEW_INSTALL } val persistentData = AndroidFirstRunPersistentData.getInstance() return when { isHandoff(persistentData) -> FirstRunWizardMode.INSTALL_HANDOFF !persistentData.isSdkUpToDate -> FirstRunWizardMode.NEW_INSTALL IdeSdks.getInstance().eligibleAndroidSdks.isEmpty() -> FirstRunWizardMode.MISSING_SDK else -> null } } /** * Returns true if the handoff data was updated since the last time wizard ran. */ private fun isHandoff(persistentData: AndroidFirstRunPersistentData): Boolean { val data = installerData ?: return false return (!persistentData.isSdkUpToDate || !persistentData.isSameTimestamp(data.timestamp)) && data.isCurrentVersion } @WorkerThread private fun checkInternetConnection() { ApplicationManager.getApplication().assertIsNonDispatchThread() CommonProxy.isInstalledAssertion() do { var retryConnection: Boolean try { val connection = HttpConfigurable.getInstance().openHttpConnection("http://developer.android.com") connection.connect() connection.disconnect() retryConnection = false } catch (e: IOException) { retryConnection = promptToRetryFailedConnection() } catch (e: RuntimeException) { retryConnection = promptToRetryFailedConnection() } catch (e: Throwable) { // Some other unexpected error related to JRE setup, e.g. // java.lang.NoClassDefFoundError: Could not initialize class javax.crypto.SunJCE_b // at javax.crypto.KeyGenerator.a(DashoA13*..) // .... // See b/37021138 for more. // This shouldn't cause a crash at startup which prevents starting the IDE! retryConnection = false var message = "Couldn't check internet connection" if (e.toString().contains("crypto")) { message += "; check your JDK/JRE installation / consider running on a newer version." } log.warn(message, e) } } while (retryConnection) } private fun promptToRetryFailedConnection(): Boolean { return invokeAndWaitIfNeeded { promptUserForProxy() } } private fun promptUserForProxy(): Boolean { val selection = Messages.showIdeaMessageDialog( null, "Unable to access Android SDK add-on list", ApplicationNamesInfo.getInstance().fullProductName + " First Run", arrayOf("Setup Proxy", "Cancel"), 1, Messages.getErrorIcon(), null ) val showSetupProxy = selection == 0 if (showSetupProxy) { HttpConfigurable.editConfigurable(null) } return showSetupProxy } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
6,118
android
Apache License 2.0
compiler/testData/codegen/boxInline/anonymousObject/kt19399.kt
JakeWharton
99,388,807
false
null
//WITH_RUNTIME // FILE: 1.kt class Foo { var bar = "" inline fun ifNotBusyPerform(action: (complete: () -> Unit) -> Unit) { action { bar += "K" } } fun ifNotBusySayHello() { ifNotBusyPerform { bar += "O" it() } } inline fun inlineFun(s: () -> Unit) { s() } fun start() { inlineFun { { ifNotBusyPerform { ifNotBusySayHello() } }() } } } // FILE: 2.kt fun box(): String { val foo = Foo() foo.start() return foo.bar }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
637
kotlin
Apache License 2.0
app/src/main/java/com/enact/asa/models/BalanceItem.kt
ASAFINANCIAL
622,867,265
false
{"Kotlin": 39083, "Java": 2227}
package com.enact.asa.models data class BalanceItem( val accountName: String?, val accountNumber: String?, val asaConsumerCode: Int, val asaFiAccountCode: Int, val asaFintechCode: Int, val balance: Double, val currencyCode: Any, val dateOpened: String, val description: String? )
0
Kotlin
0
0
6101b4d0c964710a6c290decfcbc62bb3e3cb35a
316
AsaPalExample
Apache License 2.0
Plugins/VoiceLogger/src/main/kotlin/tw/xserver/plugin/logger/voice/VoiceLogger.kt
IceXinShou
830,436,296
false
{"Kotlin": 201062}
package tw.xserver.plugin.logger.voice import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.IMentionable import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.entities.channel.concrete.TextChannel import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel import net.dv8tion.jda.api.events.channel.update.ChannelUpdateVoiceStatusEvent import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent import net.dv8tion.jda.api.events.interaction.component.EntitySelectInteractionEvent import net.dv8tion.jda.api.interactions.DiscordLocale import net.dv8tion.jda.api.requests.restaction.CacheRestAction import net.dv8tion.jda.api.utils.messages.MessageEditData import org.slf4j.Logger import org.slf4j.LoggerFactory import tw.xserver.loader.builtin.placeholder.Placeholder import tw.xserver.loader.builtin.placeholder.Substitutor import tw.xserver.plugin.creator.message.MessageCreator import tw.xserver.plugin.logger.voice.Event.COMPONENT_PREFIX import tw.xserver.plugin.logger.voice.Event.DEFAULT_LOCALE import tw.xserver.plugin.logger.voice.Event.PLUGIN_DIR_FILE import tw.xserver.plugin.logger.voice.JsonManager.dataMap import tw.xserver.plugin.logger.voice.lang.PlaceholderLocalizations import java.io.File import java.util.stream.Collectors internal object VoiceLogger { private val logger: Logger = LoggerFactory.getLogger(this::class.java) private val creator = MessageCreator(File(PLUGIN_DIR_FILE, "lang"), DEFAULT_LOCALE, COMPONENT_PREFIX) internal fun setting(event: SlashCommandInteractionEvent) = event.hook.editOriginal( getSettingMenu( dataMap.computeIfAbsent(event.channelIdLong) { ChannelData(event.guild!!) }, event.userLocale, Placeholder.getSubstitutor(event) ) ).queue() internal fun onToggle(event: ButtonInteractionEvent) { // update val channelData = JsonManager.toggle(event.guild!!, event.channel.idLong) // reply event.hook.editOriginal( getSettingMenu( channelData, event.userLocale, Placeholder.getSubstitutor(event) ) ).queue() event.deferEdit().queue() } internal fun onDelete(event: ButtonInteractionEvent) { // update JsonManager.delete(event.guild!!.idLong, event.channel.idLong) // reply event.editMessage( MessageEditData.fromCreateData( creator.getCreateBuilder( "delete", event.userLocale, Placeholder.getSubstitutor(event) ).build() ) ).queue() } internal fun onSelect(event: EntitySelectInteractionEvent) { // update val guild = event.guild!! val channelIds = event.values .stream() .map { obj: IMentionable -> obj.idLong } .collect(Collectors.toList()) val channelData = when (event.componentId.removePrefix(COMPONENT_PREFIX)) { "modify_allow" -> { JsonManager.addAllowChannels( guild = guild, listenChannelId = event.channelIdLong, detectedChannelIds = channelIds ) } "modify_block" -> { JsonManager.addBlockChannels( guild = guild, listenChannelId = event.channelIdLong, detectedChannelIds = channelIds ) } else -> throw Exception("Unknown key ${event.componentId.removePrefix(COMPONENT_PREFIX)}") } // reply event.hook.editOriginal( getSettingMenu( channelData, event.userLocale, Placeholder.getSubstitutor(event) ) ).queue() event.deferEdit().queue() } internal fun createSel(event: ButtonInteractionEvent, componentId: String) { event.editMessage( MessageEditData.fromCreateData( creator.getCreateBuilder( componentId, event.userLocale, Placeholder.getSubstitutor(event) ).build() ) ).queue() } fun onChannelStatusNew(event: ChannelUpdateVoiceStatusEvent, data: StatusEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> data.channel in value.getCurrentDetectChannels() } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return data.member.queue { member -> val substitutor = Placeholder.getSubstitutor(member).putAll( "vl_category_mention" to data.channel.parentCategory!!.asMention, "vl_channel_mention" to data.channel.asMention, "vl_channel_url" to data.channel.jumpUrl, "vl_status_after" to data.newStr!!, ) sendListenChannel("on-status-new", event.guild, listenChannelIds, substitutor) } } fun onChannelStatusUpdate(event: ChannelUpdateVoiceStatusEvent, data: StatusEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> data.channel in value.getCurrentDetectChannels() } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return data.member.queue { member -> val substitutor = Placeholder.getSubstitutor(member).putAll( "vl_category_mention" to data.channel.parentCategory!!.asMention, "vl_channel_mention" to data.channel.asMention, "vl_channel_url" to data.channel.jumpUrl, "vl_status_before" to data.oldStr!!, "vl_status_after" to data.newStr!!, ) sendListenChannel("on-status-update", event.guild, listenChannelIds, substitutor) } } fun onChannelStatusDelete(event: ChannelUpdateVoiceStatusEvent, data: StatusEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> data.channel in value.getCurrentDetectChannels() } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return data.member.queue { member -> val substitutor = Placeholder.getSubstitutor(member).putAll( "vl_category_mention" to data.channel.parentCategory!!.asMention, "vl_channel_mention" to data.channel.asMention, "vl_channel_url" to data.channel.jumpUrl, "vl_status_before" to data.oldStr!!, ) sendListenChannel("on-status-delete", event.guild, listenChannelIds, substitutor) } } fun onChannelJoin(event: GuildVoiceUpdateEvent, data: VoiceEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> data.channelJoin!! in value.getCurrentDetectChannels() } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return val substitutor = Placeholder.getSubstitutor(data.member).putAll( "vl_category_join_mention" to data.channelJoin!!.parentCategory!!.asMention, "vl_channel_join_mention" to data.channelJoin.asMention, "vl_channel_join_url" to data.channelJoin.jumpUrl, ) sendListenChannel("on-channel-join", event.guild, listenChannelIds, substitutor) } fun onChannelSwitch(event: GuildVoiceUpdateEvent, data: VoiceEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> (data.channelJoin!! in value.getCurrentDetectChannels()) or (data.channelLeft!! in value.getCurrentDetectChannels()) } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return val substitutor = Placeholder.getSubstitutor(data.member).putAll( "vl_category_join_mention" to data.channelJoin!!.parentCategory!!.asMention, "vl_channel_join_mention" to data.channelJoin.asMention, "vl_channel_join_url" to data.channelJoin.jumpUrl, "vl_category_left_mention" to data.channelLeft!!.parentCategory!!.asMention, "vl_channel_left_mention" to data.channelLeft.asMention, "vl_channel_left_url" to data.channelLeft.jumpUrl, ) sendListenChannel("on-channel-switch", event.guild, listenChannelIds, substitutor) } fun onChannelLeft(event: GuildVoiceUpdateEvent, data: VoiceEventData) { val listenChannelIds: List<Long> = dataMap.entries .filter { (_, value) -> data.channelLeft!! in value.getCurrentDetectChannels() } .map { (key, _) -> key } if (listenChannelIds.isEmpty()) return val substitutor = Placeholder.getSubstitutor(data.member).putAll( "vl_category_left_mention" to data.channelLeft!!.parentCategory!!.asMention, "vl_channel_left_mention" to data.channelLeft.asMention, "vl_channel_left_url" to data.channelLeft.jumpUrl, ) sendListenChannel("on-channel-left", event.guild, listenChannelIds, substitutor) } private fun sendListenChannel(key: String, guild: Guild, listenChannelId: List<Long>, substitutor: Substitutor) { val message = creator.getCreateBuilder(key, guild.locale, substitutor).build() listenChannelId.forEach { val listenChannel = guild.getGuildChannelById(it) ?: return when (listenChannel) { is TextChannel -> listenChannel.sendMessage(message).queue() is VoiceChannel -> listenChannel.sendMessage(message).queue() else -> throw Exception("Unknown channel type") } } } internal data class StatusEventData( val guildId: Long, val locale: DiscordLocale, val channel: VoiceChannel, val member: CacheRestAction<Member>, val oldStr: String?, val newStr: String?, ) internal data class VoiceEventData( val guildId: Long, val locale: DiscordLocale, val member: Member, val channelJoin: AudioChannel?, val channelLeft: AudioChannel?, ) private fun getSettingMenu( channelData: ChannelData, locale: DiscordLocale, substitutor: Substitutor ): MessageEditData { val allowListFormat = PlaceholderLocalizations.allowListFormat[locale] val blockListFormat = PlaceholderLocalizations.blockListFormat[locale] val allowString = StringBuilder().apply { if (!channelData.getAllowArray().isEmpty) channelData.getAllowArray().map { it.asString } .forEach { detectedChannelId -> append( substitutor.parse( allowListFormat .replace("%allowlist_channel_mention%", "<#${detectedChannelId}>") .replace("%allowlist_channel_id%", detectedChannelId) ) ) } else { append(substitutor.parse(PlaceholderLocalizations.empty[locale])) } }.toString() val blockString = StringBuilder().apply { if (!channelData.getBlockArray().isEmpty) channelData.getBlockArray().map { it.asString } .forEach { detectedChannelId -> append( substitutor.parse( blockListFormat .replace("%blocklist_channel_mention%", "<#${detectedChannelId}>") .replace("%blocklist_channel_id%", detectedChannelId) ) ) } else { append(substitutor.parse(PlaceholderLocalizations.empty[locale])) } }.toString() substitutor.apply { putAll( "vl_channel_mode" to if (channelData.getChannelMode()) "ALLOW" else "BLOCK", "vl_allow_list_format" to allowString, "vl_block_list_format" to blockString ) } return MessageEditData.fromCreateData( creator.getCreateBuilder("voice-logger@setting", locale, substitutor).build() ) } }
0
Kotlin
0
1
2d8a9f13e5e6036af9aa6409961ac07b2f6654be
12,713
XsDiscordBotKt
Apache License 2.0
binary-transcoders/src/test/kotlin/com/kamelia/sprinkler/transcoder/binary/decoder/core/DecoderTest.kt
Black-Kamelia
579,095,832
false
{"Kotlin": 467429, "Java": 18620}
package com.kamelia.sprinkler.transcoder.binary.decoder.core import com.kamelia.sprinkler.transcoder.binary.decoder.IntDecoder import com.kamelia.sprinkler.transcoder.binary.decoder.util.assertDoneAndGet import com.kamelia.sprinkler.util.byte import java.io.ByteArrayInputStream import java.nio.ByteBuffer import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class DecoderTest { @Test fun `decode behaves the same way for all overloads`() { val value = 5 val byteArray = byteArrayOf(value.byte(3), value.byte(2), value.byte(1), value.byte(0)) val stream = ByteArrayInputStream(byteArray.copyOf()) val buffer = ByteBuffer.wrap(byteArray.copyOf()).apply { position(limit()) } val decoder = IntDecoder() val byteArrayResult = decoder.decode(byteArray).assertDoneAndGet() val streamResult = decoder.decode(stream).assertDoneAndGet() val bufferResult = decoder.decode(buffer).assertDoneAndGet() assertEquals(value, byteArrayResult) assertEquals(value, streamResult) assertEquals(value, bufferResult) } }
9
Kotlin
0
6
e9be672cd489e7784db2d533b83b72ef9ef4f4d0
1,139
Sprinkler
MIT License
compiler/src/main/kotlin/com/piotrwalkusz/smartlaw/compiler/template/processor/MapTemplateProcessor.kt
piotrwalkusz1
293,285,610
false
null
package com.piotrwalkusz.smartlaw.compiler.template.processor import com.piotrwalkusz.smartlaw.compiler.template.processor.context.TemplateProcessorContext import com.piotrwalkusz.smartlaw.core.model.template.MapTemplate import com.piotrwalkusz.smartlaw.core.model.template.Template class MapTemplateProcessor( private val templateProcessorService: TemplateProcessorService ) : TemplateProcessor { override fun getTemplateType(): Class<*> { return MapTemplate::class.java } override fun <T> processTemplate(template: Template<T>, context: TemplateProcessorContext): T { if (template !is MapTemplate<*>) { throw IllegalArgumentException("Template must be instance of MapTemplate class") } @Suppress("UNCHECKED_CAST") return processTemplate(template, context) as T } private fun <T> processTemplate(template: MapTemplate<T>, context: TemplateProcessorContext): Map<String, T> { return template.items.mapValues { item -> templateProcessorService.processTemplate(item.value, context) } } }
0
Kotlin
0
0
235354ac0469d5ba9630b91124f6fcc4481dad34
1,083
SmartLaw
MIT License
src/main/kotlin/io/github/pr0methean/ochd/texturebase/DyedBlock.kt
Pr0methean
507,628,226
false
null
package io.github.pr0methean.ochd.texturebase import io.github.pr0methean.ochd.LayerListBuilder import io.github.pr0methean.ochd.TaskPlanningContext import io.github.pr0methean.ochd.materials.DYES import io.github.pr0methean.ochd.tasks.AbstractImageTask import io.github.pr0methean.ochd.tasks.PngOutputTask import javafx.scene.paint.Color abstract class DyedBlock(val name: String): Material { abstract fun LayerListBuilder.createTextureLayers( color: Color, sharedLayers: AbstractImageTask ) abstract fun createSharedLayersTask(ctx: TaskPlanningContext): AbstractImageTask override fun outputTasks(ctx: TaskPlanningContext): Sequence<PngOutputTask> = sequence { val sharedLayersTask = createSharedLayersTask(ctx) DYES.forEach { (dyeName, color) -> yield(ctx.out(ctx.stack {createTextureLayers(color, sharedLayersTask)}, "block/${dyeName}_$name")) } } }
1
Kotlin
0
5
3e8182114f7fe0fb70fcd6fa445c28dc5470a3f5
930
OcHd-KotlinBuild
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/risk/storage/internal/RiskCombinatorTest.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.risk.storage.internal import com.google.android.gms.nearby.exposurenotification.ExposureWindow import de.rki.coronawarnapp.presencetracing.risk.PtRiskLevelResult import de.rki.coronawarnapp.presencetracing.risk.calculation.PresenceTracingDayRisk import de.rki.coronawarnapp.risk.EwRiskLevelResult import de.rki.coronawarnapp.risk.RiskState import de.rki.coronawarnapp.risk.RiskState.CALCULATION_FAILED import de.rki.coronawarnapp.risk.RiskState.INCREASED_RISK import de.rki.coronawarnapp.risk.RiskState.LOW_RISK import de.rki.coronawarnapp.risk.result.EwAggregatedRiskResult import de.rki.coronawarnapp.risk.result.ExposureWindowDayRisk import de.rki.coronawarnapp.server.protocols.internal.v2.RiskCalculationParametersOuterClass.NormalizedTimeToRiskLevelMapping.RiskLevel import de.rki.coronawarnapp.util.TimeStamper import io.kotest.matchers.shouldBe import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import org.joda.time.Instant import org.joda.time.LocalDate import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import testhelpers.BaseTest class RiskCombinatorTest : BaseTest() { @MockK lateinit var timeStamper: TimeStamper @BeforeEach fun setup() { MockKAnnotations.init(this) every { timeStamper.nowUTC } returns Instant.ofEpochMilli(1234567890) } private fun createInstance() = RiskCombinator( timeStamper = timeStamper ) @Test fun `Initial results`() { createInstance().initialCombinedResult.apply { riskState shouldBe LOW_RISK } } @Test fun `Fallback results on empty data`() { createInstance().latestCombinedResult.apply { riskState shouldBe LOW_RISK } } @Test fun `combineRisk works`() { val ptRisk0 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 19), riskState = LOW_RISK ) val ptRisk1 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 20), riskState = INCREASED_RISK ) val ptRisk2 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 21), riskState = LOW_RISK ) val ptRisk3 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 22), riskState = CALCULATION_FAILED ) val ptRisk4 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 23), riskState = LOW_RISK ) val ptRisk5 = PresenceTracingDayRisk( localDateUtc = LocalDate(2021, 3, 24), riskState = INCREASED_RISK ) val ewRisk0 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-24T14:00:00.000Z").millis, riskLevel = RiskLevel.HIGH, 0, 0 ) val ewRisk1 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-23T14:00:00.000Z").millis, riskLevel = RiskLevel.HIGH, 0, 0 ) val ewRisk2 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-22T14:00:00.000Z").millis, riskLevel = RiskLevel.HIGH, 0, 0 ) val ewRisk3 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-19T14:00:00.000Z").millis, riskLevel = RiskLevel.LOW, 0, 0 ) val ewRisk4 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-20T14:00:00.000Z").millis, riskLevel = RiskLevel.UNSPECIFIED, 0, 0 ) val ewRisk5 = ExposureWindowDayRisk( dateMillisSinceEpoch = Instant.parse("2021-03-15T14:00:00.000Z").millis, riskLevel = RiskLevel.UNSPECIFIED, 0, 0 ) val ptDayRiskList: List<PresenceTracingDayRisk> = listOf(ptRisk0, ptRisk1, ptRisk2, ptRisk3, ptRisk4, ptRisk5) val ewDayRiskList: List<ExposureWindowDayRisk> = listOf(ewRisk0, ewRisk1, ewRisk2, ewRisk3, ewRisk4, ewRisk5) val result = createInstance().combineRisk(ptDayRiskList, ewDayRiskList) result.size shouldBe 7 result.single { it.localDate == LocalDate(2021, 3, 15) }.riskState shouldBe CALCULATION_FAILED result.single { it.localDate == LocalDate(2021, 3, 19) }.riskState shouldBe LOW_RISK result.single { it.localDate == LocalDate(2021, 3, 20) }.riskState shouldBe CALCULATION_FAILED result.single { it.localDate == LocalDate(2021, 3, 21) }.riskState shouldBe LOW_RISK result.single { it.localDate == LocalDate(2021, 3, 22) }.riskState shouldBe CALCULATION_FAILED result.single { it.localDate == LocalDate(2021, 3, 22) }.riskState shouldBe CALCULATION_FAILED result.single { it.localDate == LocalDate(2021, 3, 23) }.riskState shouldBe INCREASED_RISK result.single { it.localDate == LocalDate(2021, 3, 24) }.riskState shouldBe INCREASED_RISK } @Test fun `combineEwPtRiskLevelResults works`() { val startInstant = Instant.ofEpochMilli(10000) val ptResult = PtRiskLevelResult( calculatedAt = startInstant.plus(1000L), riskState = LOW_RISK ) val ptResult2 = PtRiskLevelResult( calculatedAt = startInstant.plus(3000L), riskState = LOW_RISK ) val ptResult3 = PtRiskLevelResult( calculatedAt = startInstant.plus(6000L), riskState = CALCULATION_FAILED ) val ptResult4 = PtRiskLevelResult( calculatedAt = startInstant.plus(7000L), riskState = CALCULATION_FAILED ) val ptResults = listOf(ptResult, ptResult2, ptResult4, ptResult3) val ewResult = createEwRiskLevelResult( calculatedAt = startInstant.plus(2000L), riskState = LOW_RISK ) val ewResult2 = createEwRiskLevelResult( calculatedAt = startInstant.plus(4000L), riskState = INCREASED_RISK ) val ewResult3 = createEwRiskLevelResult( calculatedAt = startInstant.plus(5000L), riskState = CALCULATION_FAILED ) val ewResult4 = createEwRiskLevelResult( calculatedAt = startInstant.plus(8000L), riskState = CALCULATION_FAILED ) val ewResults = listOf(ewResult, ewResult4, ewResult2, ewResult3) val result = createInstance().combineEwPtRiskLevelResults( ptRiskResults = ptResults, ewRiskResults = ewResults ).sortedByDescending { it.calculatedAt } result.size shouldBe 8 result[0].riskState shouldBe CALCULATION_FAILED result[0].calculatedAt shouldBe startInstant.plus(8000L) result[1].riskState shouldBe CALCULATION_FAILED result[1].calculatedAt shouldBe startInstant.plus(7000L) result[2].riskState shouldBe CALCULATION_FAILED result[2].calculatedAt shouldBe startInstant.plus(6000L) result[3].riskState shouldBe CALCULATION_FAILED result[3].calculatedAt shouldBe startInstant.plus(5000L) result[4].riskState shouldBe INCREASED_RISK result[4].calculatedAt shouldBe startInstant.plus(4000L) result[5].riskState shouldBe LOW_RISK result[5].calculatedAt shouldBe startInstant.plus(3000L) result[6].riskState shouldBe LOW_RISK result[6].calculatedAt shouldBe startInstant.plus(2000L) result[7].riskState shouldBe LOW_RISK result[7].calculatedAt shouldBe startInstant.plus(1000L) } @Test fun `combine RiskState works`() { RiskCombinator.combine(INCREASED_RISK, INCREASED_RISK) shouldBe INCREASED_RISK RiskCombinator.combine(INCREASED_RISK, LOW_RISK) shouldBe INCREASED_RISK RiskCombinator.combine(INCREASED_RISK, CALCULATION_FAILED) shouldBe CALCULATION_FAILED RiskCombinator.combine(LOW_RISK, INCREASED_RISK) shouldBe INCREASED_RISK RiskCombinator.combine(CALCULATION_FAILED, INCREASED_RISK) shouldBe CALCULATION_FAILED RiskCombinator.combine(LOW_RISK, LOW_RISK) shouldBe LOW_RISK RiskCombinator.combine(CALCULATION_FAILED, LOW_RISK) shouldBe CALCULATION_FAILED RiskCombinator.combine(CALCULATION_FAILED, CALCULATION_FAILED) shouldBe CALCULATION_FAILED } } private fun createEwRiskLevelResult( calculatedAt: Instant, riskState: RiskState ): EwRiskLevelResult = object : EwRiskLevelResult { override val calculatedAt: Instant = calculatedAt override val riskState: RiskState = riskState override val failureReason: EwRiskLevelResult.FailureReason? = null override val ewAggregatedRiskResult: EwAggregatedRiskResult? = null override val exposureWindows: List<ExposureWindow>? = null override val matchedKeyCount: Int = 0 }
6
null
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
9,140
cwa-app-android
Apache License 2.0
domain/src/test/java/com/hasegawa/diapp/domain/AddNewsResponsesToRepoUseCaseTest.kt
AranHase
55,708,682
false
null
/* * Copyright 2016 <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.hasegawa.diapp.domain import com.hasegawa.diapp.domain.entities.NewsEntity import com.hasegawa.diapp.domain.repositories.NewsRepository import com.hasegawa.diapp.domain.restservices.responses.NewsResponse import com.hasegawa.diapp.domain.restservices.responses.toEntity import com.hasegawa.diapp.domain.usecases.AddNewsResponsesToRepoUseCase import org.hamcrest.Matchers.* import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.* import org.mockito.MockitoAnnotations import rx.Observable import rx.Subscriber import rx.schedulers.Schedulers import java.util.concurrent.CyclicBarrier import java.util.concurrent.TimeUnit class AddNewsResponsesToRepoUseCaseTest { val et = ExecutionThread(Schedulers.io()) val pet = PostExecutionThread(Schedulers.newThread()) @Mock var newsRepository: NewsRepository? = null val responses = listOf( NewsResponse("titleA", "urlA", "tldrA", 0), NewsResponse("titleB", "urlB", "tldrB", 1), NewsResponse("titleC", "urlC", "tldrC", 2) ) private fun <T> anyObject(): T { return Mockito.anyObject<T>() } @Before fun setUp() { MockitoAnnotations.initMocks(this) } @Test fun onClearRepo() { `when`(newsRepository!!.clearNews()).thenReturn(Observable.just(0)) `when`(newsRepository!!.addAllNews(responses.map { it.toEntity(null) })) .thenReturn(Observable.just(responses.mapIndexed { i, it -> it.toEntity("id$i") })) val useCase = AddNewsResponsesToRepoUseCase(responses, newsRepository!!, et, pet) var completed = false var results: List<NewsEntity>? = null val barrier = CyclicBarrier(2) useCase.execute(object : Subscriber<List<NewsEntity>>() { override fun onCompleted() { completed = true barrier.await() } override fun onError(e: Throwable?) { throw UnsupportedOperationException() } override fun onNext(t: List<NewsEntity>?) { assertThat(t, notNullValue()) results = t } }) barrier.await(10, TimeUnit.SECONDS) assertThat(results, `is`(responses.mapIndexed { i, response -> response.toEntity("id$i") })) assertThat(completed, `is`(true)) verify(newsRepository!!).clearNews() verify(newsRepository!!).addAllNews(responses.map { it.toEntity(null) }) verify(newsRepository!!).notifyChange() verifyNoMoreInteractions(newsRepository!!) } }
6
Kotlin
1
8
80e2c6d345a63ce75a1383f52f08bfb1f0a1535b
3,289
PassosDoImpeachment-app
Apache License 2.0
runtime/src/main/kotlin/kotlin/native/concurrent/Worker.kt
JetBrains
58,957,623
false
null
/* * Copyright 2010-2018 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 kotlin.native.concurrent import kotlin.native.internal.ExportForCppRuntime import kotlin.native.internal.Frozen import kotlin.native.internal.VolatileLambda import kotlin.native.internal.IntrinsicType import kotlin.native.internal.TypedIntrinsic import kotlinx.cinterop.* /** * ## Workers: theory of operations. * * [Worker] represents asynchronous and concurrent computation, usually performed by other threads * in the same process. Object passing between workers is performed using transfer operation, so that * object graph belongs to one worker at the time, but can be disconnected and reconnected as needed. * See 'Object Transfer Basics' and [TransferMode] for more details on how objects shall be transferred. * This approach ensures that no concurrent access happens to same object, while data may flow between * workers as needed. */ /** * Class representing worker. */ @Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS") public inline class Worker @PublishedApi internal constructor(val id: Int) { companion object { /** * Start new scheduling primitive, such as thread, to accept new tasks via `execute` interface. * Typically new worker may be needed for computations offload to another core, for IO it may be * better to use non-blocking IO combined with more lightweight coroutines. * * @param errorReporting controls if an uncaught exceptions in the worker will be printed out * @param name defines the optional name of this worker, if none - default naming is used. * @return worker object, usable across multiple concurrent contexts. */ public fun start(errorReporting: Boolean = true, name: String? = null): Worker = Worker(startInternal(errorReporting, name)) /** * Return the current worker. Worker context is accessible to any valid Kotlin context, * but only actual active worker produced with [Worker.start] automatically processes execution requests. * For other situations [processQueue] must be called explicitly to process request queue. * @return current worker object, usable across multiple concurrent contexts. */ public val current: Worker get() = Worker(currentInternal()) /** * Create worker object from a C pointer. * * This function is deprecated. See [Worker.asCPointer] for more details. * * @param pointer value returned earlier by [Worker.asCPointer] */ @Deprecated("Use kotlinx.cinterop.StableRef instead", level = DeprecationLevel.WARNING) public fun fromCPointer(pointer: COpaquePointer?): Worker = if (pointer != null) Worker(pointer.toLong().toInt()) else throw IllegalArgumentException() } /** * Requests termination of the worker. * * @param processScheduledJobs controls is we shall wait until all scheduled jobs processed, * or terminate immediately. If there are jobs to be execucted with [executeAfter] their execution * is awaited for. */ public fun requestTermination(processScheduledJobs: Boolean = true): Future<Unit> = Future<Unit>(requestTerminationInternal(id, processScheduledJobs)) /** * Plan job for further execution in the worker. Execute is a two-phase operation: * - first [producer] function is executed, and resulting object and whatever it refers to * is analyzed for being an isolated object subgraph, if in checked mode. * - Afterwards, this disconnected object graph and [job] function pointer is being added to jobs queue * of the selected worker. Note that [job] must not capture any state itself, so that whole state is * explicitly stored in object produced by [producer]. Scheduled job is being executed by the worker, * and result of such a execution is being disconnected from worker's object graph. Whoever will consume * the future, can use result of worker's computations. * Note, that some technically disjoint subgraphs may lead to `kotlin.IllegalStateException` * so `kotlin.native.internal.GC.collect()` could be called in the end of `producer` and `job` * if garbage cyclic structures or other uncollected objects refer to the value being transferred. * * @return the future with the computation result of [job]. */ @Suppress("UNUSED_PARAMETER") @TypedIntrinsic(IntrinsicType.WORKER_EXECUTE) public fun <T1, T2> execute(mode: TransferMode, producer: () -> T1, @VolatileLambda job: (T1) -> T2): Future<T2> = /* * This function is a magical operation, handled by lowering in the compiler, and replaced with call to * executeImpl(worker, mode, producer, job) * but first ensuring that `job` parameter doesn't capture any state. */ throw RuntimeException("Shall not be called directly") /** * Plan job for further execution in the worker. [operation] parameter must be either frozen, or execution to be * planned on the current worker. Otherwise [IllegalStateException] will be thrown. * * @param afterMicroseconds defines after how many microseconds delay execution shall happen, 0 means immediately, * @throws [IllegalArgumentException] on negative values of [afterMicroseconds]. * @throws [IllegalStateException] if [operation] parameter is not frozen and worker is not current. */ public fun executeAfter(afterMicroseconds: Long = 0, operation: () -> Unit): Unit { val current = currentInternal() if (Platform.memoryModel != MemoryModel.EXPERIMENTAL && current != id && !operation.isFrozen) throw IllegalStateException("Job for another worker must be frozen") if (afterMicroseconds < 0) throw IllegalArgumentException("Timeout parameter must be non-negative") executeAfterInternal(id, operation, afterMicroseconds) } /** * Process pending job(s) on the queue of this worker. * Note that jobs scheduled with [executeAfter] using non-zero timeout are * not processed this way. If termination request arrives while processing the queue via this API, * worker is marked as terminated and will exit once the current request is done with. * * @throws [IllegalStateException] if this request is executed on non-current [Worker]. * @return `true` if request(s) was processed and `false` otherwise. */ public fun processQueue(): Boolean = processQueueInternal(id) /** * Park execution of the current worker until a new request arrives or timeout specified in * [timeoutMicroseconds] elapsed. If [process] is true, pending queue elements are processed, * including delayed requests. Note that multiple requests could be processed this way. * * @param timeoutMicroseconds defines how long to park worker if no requests arrive, waits forever if -1. * @param process defines if arrived request(s) shall be processed. * @return if [process] is `true`: if request(s) was processed `true` and `false` otherwise. * if [process] is `false`:` true` if request(s) has arrived and `false` if timeout happens. * @throws [IllegalStateException] if this request is executed on non-current [Worker]. * @throws [IllegalArgumentException] if timeout value is incorrect. */ public fun park(timeoutMicroseconds: Long, process: Boolean = false): Boolean { if (timeoutMicroseconds < -1) throw IllegalArgumentException() return parkInternal(id, timeoutMicroseconds, process) } /** * Name of the worker, as specified in [Worker.start] or "worker $id" by default, * * @throws [IllegalStateException] if this request is executed on an invalid worker. */ public val name: String get() { val customName = getWorkerNameInternal(id) return if (customName == null) "worker $id" else customName } /** * String representation of the worker. */ override public fun toString(): String = "Worker $name" /** * Convert worker to a COpaquePointer value that could be passed via native void* pointer. * Can be used as an argument of [Worker.fromCPointer]. * * This function is deprecated. Use `kotlinx.cinterop.StableRef.create(worker).asCPointer()` instead. * The result can be unwrapped with `pointer.asStableRef<Worker>().get()`. * [StableRef] should be eventually disposed manually with [StableRef.dispose]. * * @return worker identifier as C pointer. */ @Deprecated("Use kotlinx.cinterop.StableRef instead", level = DeprecationLevel.WARNING) public fun asCPointer() : COpaquePointer? = id.toLong().toCPointer() } /** * Executes [block] with new [Worker] as resource, by starting the new worker, calling provided [block] * (in current context) with newly started worker as [this] and terminating worker after the block completes. * Note that this operation is pretty heavyweight, use preconfigured worker or worker pool if need to * execute it frequently. * * @param name of the started worker. * @param errorReporting controls if uncaught errors in worker to be reported. * @param block to be executed. * @return value returned by the block. */ public inline fun <R> withWorker(name: String? = null, errorReporting: Boolean = true, block: Worker.() -> R): R { val worker = Worker.start(errorReporting, name) try { return worker.block() } finally { worker.requestTermination().result } }
182
null
625
7,100
9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa
9,803
kotlin-native
Apache License 2.0
Chapter10-dsl/activity10/src/main/kotlin/CarBuilder.kt
TrainingByPackt
168,300,143
false
null
class CarBuilder { var make: String = "" var features = mutableListOf<String>() var color: CarColor = CarColor.nopreference operator fun invoke(block: CarBuilder.() -> Unit): Car { block() return build() } fun features(block: FeatureBuilder.() -> Unit) { val featureBuilder = FeatureBuilder(this) featureBuilder.block() } fun build() : Car { return Car(make, color, features) } }
0
Kotlin
2
2
cd4303736bcffb52309defbf3c32c0853ed67b56
458
Complete-Guide-to-Kotlin
MIT License
src/main/kotlin/space/yaroslav/familybot/executors/eventbased/CustomMessageExecutor.kt
cra
255,575,962
true
{"Kotlin": 221078, "TSQL": 67517, "Dockerfile": 296, "Shell": 192}
package space.yaroslav.familybot.executors.eventbased import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.springframework.stereotype.Component import org.telegram.telegrambots.meta.api.methods.send.SendMessage import org.telegram.telegrambots.meta.api.objects.Message import org.telegram.telegrambots.meta.api.objects.Update import org.telegram.telegrambots.meta.bots.AbsSender import space.yaroslav.familybot.common.utils.toChat import space.yaroslav.familybot.executors.Executor import space.yaroslav.familybot.models.Priority import space.yaroslav.familybot.repos.ifaces.CustomMessageDeliveryRepository @Component class CustomMessageExecutor(private val repository: CustomMessageDeliveryRepository) : Executor { override fun execute(update: Update): suspend (AbsSender) -> Unit { return { sender -> val chat = update.toChat() if (repository.hasNewMessages(chat)) { repository.getNewMessages(chat) .forEach { message -> GlobalScope.launch { delay(2000) sender.execute(SendMessage(message.chat.id, message.message)) repository.markAsDelivered(message) } } } } } override fun canExecute(message: Message): Boolean { return repository.hasNewMessages(message.chat.toChat()) } override fun priority(update: Update): Priority { return Priority.LOW } }
0
Kotlin
0
0
3149c15cfbc3eb1bed4c5a0e147df3f22df9378f
1,594
familybot
Apache License 2.0
src/main/kotlin/com/launchdarkly/intellij/toolwindow/FlagNode.kt
launchdarkly
344,313,910
false
null
package com.launchdarkly.intellij.toolwindow import com.intellij.ide.projectView.PresentationData import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.ui.treeStructure.SimpleNode import com.launchdarkly.api.model.* import com.launchdarkly.intellij.FlagStore import com.launchdarkly.intellij.LDIcons import com.launchdarkly.intellij.featurestore.FlagConfiguration import com.launchdarkly.intellij.settings.LDSettings class RootNode(private val flags: FeatureFlags, private val settings: LDSettings, private val intProject: Project) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { when { myChildren.isEmpty() && flags.items != null -> { myChildren.add(InfoNode("${settings.project} / ${settings.environment}")) for (flag in flags.items) { val flagStore = intProject.service<FlagStore>() val flagViewModel = FlagNodeViewModel(flag, flags, flagStore.flagConfigs[flag.key]) myChildren.add(FlagNodeParent(flagViewModel)) } } (settings.project != "" && settings.environment != "") && flags.items == null -> myChildren.add( FlagNodeBase( "Loading Flags..." ) ) flags.items == null -> myChildren.add(FlagNodeBase("LaunchDarkly is not configured.")) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "root" } } class FlagNodeVariations(private var flag: FeatureFlag) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { for (variation in flag.variations) { myChildren.add(FlagNodeVariation(variation)) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "Variations" data.setIcon(LDIcons.VARIATION) } } class FlagNodeVariation(private val variation: Variation) : SimpleNode() { private var myChildren: MutableList<FlagNodeBase> = ArrayList() override fun getChildren(): Array<FlagNodeBase> { if (variation.name != null) { myChildren.add(FlagNodeBase("Value: ${variation.value}", LDIcons.DESCRIPTION)) } if (variation.description != null) { myChildren.add(FlagNodeBase("Description: ${variation.description}", LDIcons.DESCRIPTION)) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) val label = variation.name ?: variation.value.toString() data.presentableText = label } } class FlagNodeTags(tags: List<String>) : SimpleNode() { var tags: List<String> = tags private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { for (tag in tags) { myChildren.add(FlagNodeBase(tag)) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "Tags" data.setIcon(LDIcons.TAGS) } } class FlagNodeFallthrough(var flag: FeatureFlag, private val flagConfig: FlagConfiguration) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { when { flagConfig.fallthrough?.variation != null -> return NO_CHILDREN flagConfig.fallthrough!!.rollout != null -> myChildren.add( FlagNodeRollout( flagConfig.fallthrough!!.rollout, flag.variations ) ) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) var label = if (flagConfig.fallthrough?.variation != null) { "Fallthrough: ${flag.variations[flagConfig.fallthrough?.variation as Int].name ?: flag.variations[flagConfig.fallthrough?.variation as Int].value}" } else { "Fallthrough" } data.presentableText = label data.setIcon(LDIcons.DESCRIPTION) } } class FlagNodeRollout(private var rollout: Rollout, private var variations: List<Variation>) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { if (rollout.bucketBy != null) { myChildren.add(FlagNodeBase("bucketBy ${rollout.bucketBy}", LDIcons.DESCRIPTION)) } for (variation in rollout.variations) { myChildren.add(FlagNodeBase("Variation: ${variations[variation.variation].name ?: variations[variation.variation].value}")) myChildren.add(FlagNodeBase("Weight: ${variation.weight / 1000.0}%")) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "Rollout" data.setIcon(LDIcons.VARIATION) } } class FlagNodeDefault(private val default: String, private var variation: Variation) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { myChildren.add(FlagNodeVariation(variation)) return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = default data.setIcon(LDIcons.VARIATION) } } class FlagNodePrerequisites(private var prereqs: List<Prerequisite>, private var flags: FeatureFlags) : SimpleNode() { private var myChildren: MutableList<SimpleNode> = ArrayList() override fun getChildren(): Array<SimpleNode> { prereqs.map { myChildren.add(FlagNodeBase("Flag Key: ${it.key}", LDIcons.LOGO)) val flagKey = it.key var flagVariation = flags.items.find { findFlag -> findFlag.key == flagKey } myChildren.add( FlagNodeBase( "Variation: ${flagVariation!!.variations[it.variation].name ?: flagVariation.variations[it.variation].value}", LDIcons.VARIATION ) ) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "Prerequisites" data.setIcon(LDIcons.PREREQUISITE) } } class FlagNodeTargets(private var flag: FeatureFlag, private var targets: List<com.launchdarkly.api.model.Target>) : SimpleNode() { private var myChildren: MutableList<FlagNodeBase> = ArrayList() override fun getChildren(): Array<FlagNodeBase> { targets.map { myChildren.add( FlagNodeBase( "${flag.variations[it.variation].name ?: flag.variations[it.variation].value}: ${it.values.size}", LDIcons.VARIATION ) ) } return myChildren.toTypedArray() } override fun update(data: PresentationData) { super.update(data) data.presentableText = "Targets" data.setIcon(LDIcons.TARGETS) } }
2
null
3
3
e8c08242746176eee3018aaa4764b2bfe37a93e0
7,562
ld-intellij
Apache License 2.0
petblocks-bukkit-plugin/petblocks-bukkit-nms-115R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/service/EntityRegistration115R1ServiceImpl.kt
Shynixn
78,876,167
false
null
package com.github.shynixn.blockball.bukkit.logic.business.nms.v1_15_R1 import com.github.shynixn.blockball.api.business.enumeration.EntityType import com.github.shynixn.blockball.api.business.service.EntityRegistrationService import net.minecraft.server.v1_15_R1.* /** * The EntityRegistration114R1ServiceImpl handles registering the custom PetBlocks entities into Minecraft. * <p> * Version 1.3 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class EntityRegistration115R1ServiceImpl : EntityRegistrationService { private val classes = HashMap<Class<*>, EntityType>() /** * Registers a new customEntity Clazz as the given [entityType]. * Does nothing if the class is already registered. */ override fun <C> register(customEntityClazz: C, entityType: EntityType) { if (customEntityClazz !is Class<*>) { throw IllegalArgumentException("CustomEntityClass has to be a Class!") } if (classes.containsKey(customEntityClazz)) { return } val entityRegistry = IRegistry.ENTITY_TYPE as RegistryBlocks<EntityTypes<*>> val key = entityType.saveGame_11 val internalRegistry = (entityRegistry.get(MinecraftKey(key))); val size = EntityTypes::class.java.getDeclaredMethod("k").invoke(internalRegistry) as EntitySize val entityTypes = IRegistry.a(entityRegistry, "petblocks_" + key.toLowerCase(), EntityTypes.a.a<Entity>(EnumCreatureType.CREATURE).b().a().a(size.width, size.height).a(key)) val registryMaterialsField = RegistryMaterials::class.java.getDeclaredField("b") registryMaterialsField.isAccessible = true val registryId = registryMaterialsField.get(entityRegistry) val dMethod = RegistryID::class.java.getDeclaredMethod("d", Any::class.java) dMethod.isAccessible = true val dValue = dMethod.invoke(registryId, entityTypes) val bMethod = RegistryID::class.java.getDeclaredMethod("b", Any::class.java, Int::class.javaPrimitiveType) bMethod.isAccessible = true val bValue = bMethod.invoke(registryId, entityTypes, dValue) as Int val cField = RegistryID::class.java.getDeclaredField("c") cField.isAccessible = true val c = cField.get(registryId) as IntArray c[bValue] = entityType.entityId classes[customEntityClazz] = entityType } /** * Clears all resources this service has allocated and reverts internal * nms changes. */ override fun clearResources() { classes.clear() } }
22
Kotlin
12
71
730e19e9e70dea1dcdafa3a98f9356b9577565db
3,677
PetBlocks
Apache License 2.0
layout-inspector/testSrc/com/android/tools/idea/layoutinspector/ShowLayoutInspectorActionTest.kt
JetBrains
60,701,247
false
null
/* * 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.android.tools.idea.layoutinspector import com.android.testutils.MockitoKt import com.android.testutils.MockitoKt.any import com.android.testutils.MockitoKt.mock import com.android.testutils.MockitoKt.whenever import com.android.tools.idea.layoutinspector.runningdevices.withEmbeddedLayoutInspector import com.android.tools.idea.streaming.RUNNING_DEVICES_TOOL_WINDOW_ID import com.intellij.notification.Notification import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.replaceService import com.intellij.toolWindow.ToolWindowHeadlessManagerImpl import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito.verify class ShowLayoutInspectorActionTest { @get:Rule val projectRule = ProjectRule() @get:Rule val applicationRule = ApplicationRule() @get:Rule val disposableRule = DisposableRule() private lateinit var fakeToolWindowManager: FakeToolWindowManager private lateinit var fakeNotificationGroupManager: FakeNotificationGroupManager @Before fun setUp() { fakeToolWindowManager = FakeToolWindowManager(projectRule.project) projectRule.project.replaceService( ToolWindowManager::class.java, fakeToolWindowManager, disposableRule.disposable ) fakeNotificationGroupManager = FakeNotificationGroupManager() ApplicationManager.getApplication() .replaceService( NotificationGroupManager::class.java, fakeNotificationGroupManager, disposableRule.disposable ) } @Test fun testActivateLayoutInspectorToolWindow() = withEmbeddedLayoutInspector(false) { val showLayoutInspectorAction = ShowLayoutInspectorAction() assertThat(fakeToolWindowManager.layoutInspectorToolWindow.isActive).isFalse() showLayoutInspectorAction.actionPerformed( createFakeEvent(projectRule.project, showLayoutInspectorAction) ) assertThat(fakeToolWindowManager.layoutInspectorToolWindow.isActive).isTrue() } @Test fun testActivateRunningDevicesToolWindow() = withEmbeddedLayoutInspector { val showLayoutInspectorAction = ShowLayoutInspectorAction() assertThat(fakeToolWindowManager.runningDevicesToolWindow.isActive).isFalse() showLayoutInspectorAction.actionPerformed( createFakeEvent(projectRule.project, showLayoutInspectorAction) ) assertThat(fakeToolWindowManager.runningDevicesToolWindow.isActive).isTrue() } @Test fun testShowLayoutInspectorDiscoveryPopUp() = withEmbeddedLayoutInspector { val showLayoutInspectorAction = ShowLayoutInspectorAction() showLayoutInspectorAction.actionPerformed( createFakeEvent(projectRule.project, showLayoutInspectorAction) ) verify(fakeNotificationGroupManager.mockNotificationGroup) .createNotification( "Layout Inspector is now embedded in the Running Devices window.", "Launch, connect, or mirror a device to start inspecting.", NotificationType.INFORMATION ) verify(fakeNotificationGroupManager.mockNotification).notify(any()) } } private fun createFakeEvent(project: Project, anAction: AnAction) = AnActionEvent.createFromAnAction(anAction, null, "") { when (it) { CommonDataKeys.PROJECT.name -> project else -> null } } private class FakeToolWindowManager(project: Project) : ToolWindowHeadlessManagerImpl(project) { var runningDevicesToolWindow = FakeToolWindow(project) var layoutInspectorToolWindow = FakeToolWindow(project) override fun getToolWindow(id: String?): ToolWindow? { return when (id) { RUNNING_DEVICES_TOOL_WINDOW_ID -> runningDevicesToolWindow LAYOUT_INSPECTOR_TOOL_WINDOW_ID -> layoutInspectorToolWindow else -> super.getToolWindow(id) } } } private class FakeToolWindow(project: Project) : ToolWindowHeadlessManagerImpl.MockToolWindow(project) { private var isActive = false override fun activate(runnable: Runnable?) { isActive = true } override fun isActive(): Boolean { return isActive } } private class FakeNotificationGroupManager : NotificationGroupManager { val mockNotification = mock<Notification>() val mockNotificationGroup = mock<NotificationGroup>() init { whenever( mockNotificationGroup.createNotification( MockitoKt.any<String>(), MockitoKt.any<String>(), MockitoKt.any<NotificationType>() ) ) .thenAnswer { mockNotification } } override fun getNotificationGroup(groupId: String): NotificationGroup { return when (groupId) { "LAYOUT_INSPECTOR_DISCOVERY" -> mockNotificationGroup else -> throw IllegalArgumentException("Unexpected groupId: $groupId") } } override fun isGroupRegistered(groupId: String): Boolean { return when (groupId) { "LAYOUT_INSPECTOR_DISCOVERY" -> true else -> false } } override fun getRegisteredNotificationGroups() = mutableListOf(mockNotificationGroup) override fun isRegisteredNotificationId(notificationId: String) = false }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
6,316
android
Apache License 2.0
frogocoreconsumeapi/src/main/java/com/frogobox/coreapi/movie/model/ConfigurationApiImage.kt
frogobox
389,577,716
false
null
package com.frogobox.coreapi.movie.model import com.google.gson.annotations.SerializedName /** * Created by <NAME> * FrogoBox Inc License * ========================================= * consumable-code-movie-tmdb-api * Copyright (C) 26/03/2020. * All rights reserved * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * LinkedIn : linkedin.com/in/faisalamircs * ----------------------------------------- * FrogoBox Software Industries * com.frogobox.frogoconsumeapi.movie.model * */ data class ConfigurationApiImage( @SerializedName("base_url") var base_url: String? = null, @SerializedName("secure_base_url") var secure_base_url: String? = null, @SerializedName("backdrop_sizes") var backdrop_sizes: List<String>? = null, @SerializedName("logo_sizes") var logo_sizes: List<String>? = null, @SerializedName("poster_sizes") var poster_sizes: List<String>? = null, @SerializedName("profile_sizes") var profile_sizes: List<String>? = null, @SerializedName("still_sizes") var still_sizes: List<String>? = null )
0
Kotlin
6
7
1dd90a037f9acb2ba30066f753d35f7b909621a6
1,156
frogo-consume-api
Apache License 2.0
petsearch-shared/core/util/src/commonMain/kotlin/com/msa/petsearch/shared/core/util/sharedviewmodel/coroutines/EventsConfiguration.kt
msa1422
534,594,528
false
null
package com.msa.petsearch.shared.core.util.sharedviewmodel.coroutines import kotlinx.coroutines.channels.BufferOverflow data class EventsConfiguration( val replays: Int = 10, val extraBufferCapacity: Int = 10, val backPressureStrategy: BufferOverflow = BufferOverflow.DROP_LATEST )
1
Kotlin
0
11
5bac19e4b31e0b8e5327e0504be13adfd4d58733
296
KMM-Arch-PetSearch
MIT License
app/src/main/java/com/duckduckgo/app/onboarding/ui/OnboardingViewModel.kt
andrey-p
164,923,819
false
null
/* * Copyright (c) 2018 DuckDuckGo * * 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.duckduckgo.app.onboarding.ui import androidx.lifecycle.ViewModel import com.duckduckgo.app.browser.defaultBrowsing.DefaultBrowserDetector import com.duckduckgo.app.onboarding.store.OnboardingStore class OnboardingViewModel( private val onboardingStore: OnboardingStore, private val defaultWebBrowserCapability: DefaultBrowserDetector ) : ViewModel() { fun pageCount(): Int { return if (shouldShowDefaultBrowserPage()) 3 else 2 } fun onOnboardingDone() { onboardingStore.onboardingShown() } fun getItem(position: Int): OnboardingPageFragment? { return when (position) { 0 -> OnboardingPageFragment.ProtectDataPage() 1 -> OnboardingPageFragment.NoTracePage() 2 -> { return if (shouldShowDefaultBrowserPage()) { OnboardingPageFragment.DefaultBrowserPage() } else null } else -> null } } private fun shouldShowDefaultBrowserPage(): Boolean { return defaultWebBrowserCapability.deviceSupportsDefaultBrowserConfiguration() } }
1
null
1
1
e4328e68fda04b2e7d874fd0c974311014afe9fe
1,730
Android
Apache License 2.0
samples/graphics/ultrahdr/src/main/java/com/example/platform/graphics/ultrahdr/display/DisplayingUltraHDRUsing3PLibrary.kt
android
623,336,962
false
{"Kotlin": 24828, "Shell": 5812}
/* * Copyright 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.platform.graphics.ultrahdr.display import android.content.pm.ActivityInfo import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build.VERSION_CODES import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RadioButton import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import coil.ImageLoader import coil.request.ImageRequest import com.bumptech.glide.Glide import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.target.CustomViewTarget import com.bumptech.glide.request.transition.Transition import com.example.platform.graphics.ultrahdr.databinding.DisplayingUltrahdrUsing3pLibraryBinding import com.facebook.common.executors.CallerThreadExecutor import com.facebook.common.references.CloseableReference import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.request.ImageRequestBuilder import com.google.android.catalog.framework.annotations.Sample import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @Sample( name = "Displaying UltraHDR (3P Libraries)", description = "This sample demonstrates using the various popular image loading library to" + " detect the presence of a gainmap to enable HDR mode when displaying an UltraHDR image", documentation = "https://github.com/bumptech/glide", tags = ["UltraHDR"], ) @RequiresApi(VERSION_CODES.UPSIDE_DOWN_CAKE) class DisplayingUltraHDRUsing3PLibrary : Fragment() { private enum class Library(val value: Int) { GLIDE(0), FRESCO(1), COIL(2); companion object { fun fromInt(value: Int) = Library.values().first { it.value == value } } } /** * Android ViewBinding. */ private var _binding: DisplayingUltrahdrUsing3pLibraryBinding? = null private val binding get() = _binding!! /** * Current 3p library selected. */ private lateinit var currentLibrary: Library override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize Fresco Library if (!Fresco.hasBeenInitialized()) Fresco.initialize(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = DisplayingUltrahdrUsing3pLibraryBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.colorModeControls.setWindow(requireActivity().window) // Disable color mode controls to demonstrate 3P libraries enabling hdr mode when a // gainmap is is detected. binding.colorModeControls.binding.ultrahdrColorModeSdr.isEnabled = false binding.colorModeControls.binding.ultrahdrColorModeSdr.text = "SDR (Automatic)" binding.colorModeControls.binding.ultrahdrColorModeHdr.isEnabled = false binding.colorModeControls.binding.ultrahdrColorModeHdr.text = "HDR (Automatic)" binding.librarySelectionGroup.setOnCheckedChangeListener { group, i -> val selected = group.findViewById<RadioButton>(i) val index = group.indexOfChild(selected) currentLibrary = Library.fromInt(index) loadWithSelectedLibrary(SDR_IMAGE_URL) } binding.optionSdrImage.setOnClickListener { loadWithSelectedLibrary(SDR_IMAGE_URL) } binding.optionUltrahdrImage.setOnClickListener { loadWithSelectedLibrary(ULTRAHDR_IMAGE) } // Initially load using Glide. binding.modeGlide.isChecked = true } /** * Load the image with the currently selected library. */ private fun loadWithSelectedLibrary(url: String) { // Initially null out image bitmap binding.imageContainer.setImageBitmap(null) when (currentLibrary) { Library.GLIDE -> loadImageWithGlide(url) Library.FRESCO -> loadImageWithFresco(url) Library.COIL -> loadImageWithCoil(url) } // Disable corresponding button. when (url) { SDR_IMAGE_URL -> { binding.optionSdrImage.isEnabled = false binding.optionUltrahdrImage.isEnabled = true } ULTRAHDR_IMAGE -> { binding.optionSdrImage.isEnabled = true binding.optionUltrahdrImage.isEnabled = false } } } /** * Load an image using [Glide]. */ private fun loadImageWithGlide(path: String) { Glide.with(this) .asBitmap() .load(Uri.parse(path)) .into(target) } /** * Using [Glide]s [CustomTarget] class, we can access the given [Bitmap] to check for the * presence of a gainmap, indicating that we should enable the HDR color mode. * * The same could be done with [CustomViewTarget] as well. */ private val target: CustomTarget<Bitmap> = object : CustomTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { binding.imageContainer.setImageBitmap(resource) // Set color mode of the activity to the correct color mode. requireActivity().window.colorMode = when (resource.hasGainmap()) { true -> ActivityInfo.COLOR_MODE_HDR else -> ActivityInfo.COLOR_MODE_DEFAULT } } override fun onLoadCleared(placeholder: Drawable?) { // clear resources if need be. } } /** * Load an image using [Fresco]. */ private fun loadImageWithFresco(path: String) { val imageRequest = ImageRequestBuilder .newBuilderWithSource(Uri.parse(path)) .build() // Use Fresco's ImagePipeline to fetch and decode image into Bitmap subscriber. Fresco.getImagePipeline() .fetchDecodedImage(imageRequest, this) .apply { subscribe(subscriber, CallerThreadExecutor.getInstance()) } } /** * Using [Fresco]'s [BaseBitmapDataSubscriber] class so we can access the given [Bitmap] to * check for the, presence of a gainmap, indicating that we should enable the HDR color mode. */ private val subscriber = object : BaseBitmapDataSubscriber() { override fun onNewResultImpl(bitmap: Bitmap?) { binding.imageContainer.setImageBitmap(bitmap) lifecycleScope.launch { // Set color mode of the activity to the correct color mode. requireActivity().window.colorMode = when (bitmap?.hasGainmap()) { true -> ActivityInfo.COLOR_MODE_HDR else -> ActivityInfo.COLOR_MODE_DEFAULT } } } override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>) { dataSource.close() } } /** * Load an image using [ImageLoader] & [ImageRequest] from Coil. */ private fun loadImageWithCoil(url: String) { lifecycleScope.launch(Dispatchers.IO) { val loader = ImageLoader(requireContext()) val request = ImageRequest.Builder(requireContext()) .data(url) .crossfade(true) .crossfade(100) .build() val result = loader.execute(request) // convert bitmap from drawable. val bitmap = (result.drawable as BitmapDrawable).bitmap // Activate HDR mode if bitmap has gain map withContext(Dispatchers.Main) { binding.imageContainer.setImageBitmap(bitmap) requireActivity().window.colorMode = when (bitmap.hasGainmap()) { true -> ActivityInfo.COLOR_MODE_HDR else -> ActivityInfo.COLOR_MODE_DEFAULT } } } } override fun onDetach() { super.onDetach() binding.colorModeControls.detach() } companion object { /** * Sample UltraHDR images paths */ private const val SDR_IMAGE_URL = "https://raw.githubusercontent.com/android/platform-samples/main/samples/graphics/" + "ultrahdr/src/main/assets/sdr/night_highrise.jpg" private const val ULTRAHDR_IMAGE = "https://raw.githubusercontent.com/android/platform-samples/main/samples/graphics/" + "ultrahdr/src/main/assets/gainmaps/night_highrise.jpg" } }
15
Kotlin
185
977
0479d2e8697c5d986d8ac7c135399e408bea78c8
9,731
platform-samples
Apache License 2.0
SKIE/skie-gradle/plugin/src/main/kotlin/co/touchlab/skie/plugin/util/DarwinTarget.kt
touchlab
685,579,240
false
{"Kotlin": 1366616, "Swift": 25254, "Shell": 763}
package co.touchlab.skie.plugin.util import org.jetbrains.kotlin.gradle.tasks.FrameworkDescriptor import org.jetbrains.kotlin.konan.target.KonanTarget internal data class DarwinTarget( val konanTarget: KonanTarget, val targetTriple: TargetTriple, val sdk: String, ) { constructor( konanTarget: KonanTarget, targetTripleString: String, sdk: String, ) : this(konanTarget, TargetTriple.fromString(targetTripleString), sdk) companion object { val allTargets = listOf( DarwinTarget(KonanTarget.IOS_ARM32, "armv7-apple-ios", "iphoneos"), DarwinTarget(KonanTarget.IOS_ARM64, "arm64-apple-ios", "iphoneos"), DarwinTarget(KonanTarget.IOS_X64, "x86_64-apple-ios-simulator", "iphonesimulator"), DarwinTarget(KonanTarget.IOS_SIMULATOR_ARM64, "arm64-apple-ios-simulator", "iphonesimulator"), DarwinTarget(KonanTarget.WATCHOS_ARM32, "armv7k-apple-watchos", "watchos"), DarwinTarget(KonanTarget.WATCHOS_ARM64, "arm64_32-apple-watchos", "watchos"), DarwinTarget(KonanTarget.WATCHOS_DEVICE_ARM64, "arm64-apple-watchos", "watchos"), DarwinTarget(KonanTarget.WATCHOS_X86, "i386-apple-watchos-simulator", "watchsimulator"), DarwinTarget(KonanTarget.WATCHOS_X64, "x86_64-apple-watchos-simulator", "watchsimulator"), DarwinTarget(KonanTarget.WATCHOS_SIMULATOR_ARM64, "arm64-apple-watchos-simulator", "watchsimulator"), DarwinTarget(KonanTarget.TVOS_ARM64, "arm64-apple-tvos", "appletvos"), DarwinTarget(KonanTarget.TVOS_X64, "x86_64-apple-tvos-simulator", "appletvsimulator"), DarwinTarget(KonanTarget.TVOS_SIMULATOR_ARM64, "arm64-apple-tvos-simulator", "appletvsimulator"), DarwinTarget(KonanTarget.MACOS_X64, "x86_64-apple-macos", "macosx"), DarwinTarget(KonanTarget.MACOS_ARM64, "arm64-apple-macos", "macosx"), ).associateBy { it.konanTarget.name } } } internal val FrameworkDescriptor.darwinTarget: DarwinTarget get() = target.darwinTarget internal val KonanTarget.darwinTarget: DarwinTarget // We can't use `KotlinTarget` directly as the instance can differ when Gradle Configuration Cache is used get() = DarwinTarget.allTargets[name] ?: error("Unknown konan target: $this")
8
Kotlin
8
557
8584e39d50e901b93a5fea9c5b91fba11f69ea7e
2,326
SKIE
Apache License 2.0
app/src/main/java/com/example/afisha/ui/top/MovieTopAdapter.kt
sshiae
719,299,632
false
{"Kotlin": 74790}
package com.example.afisha.ui.top import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.afisha.base.ui.BasePagingAdapter import com.example.afisha.databinding.MovieTopListItemBinding import com.example.afisha.domain.model.Movie import com.example.afisha.ui.top.uiState.MovieState import com.squareup.picasso.Picasso class MovieTopAdapter ( onItemClicked: (Movie) -> Unit ) : BasePagingAdapter<Movie, MovieState, MovieTopAdapter.ItemViewHolder>( createDiffCallback( { oldItem, newItem -> oldItem.title == newItem.title }, { oldItem, newItem -> oldItem == newItem } ), onItemClicked ) { override fun createViewHolder(parent: ViewGroup): ItemViewHolder = ItemViewHolder( MovieTopListItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun bindViewHolder(holder: ItemViewHolder, item: MovieState) = holder.bind(item) class ItemViewHolder( private val binding: MovieTopListItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(movie: MovieState) = with(binding) { loadImage(movie.posterUrl) tvTitle.text = movie.title tvGenres.text = movie.genres tvDescription.text = movie.description tvRating.text = movie.rating tvRating.setTextColor(movie.colorRating) } private fun loadImage(url: String) { Picasso.get().load(url).into(binding.ivPreview) } } }
0
Kotlin
0
0
b88fd0aa909e8684a461049fee06302269556b26
1,638
MoviePoster
Apache License 2.0
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/heancms/HeanCms.kt
kevin01523
612,636,298
false
null
package eu.kanade.tachiyomi.multisrc.heancms import android.app.Application import android.content.SharedPreferences import androidx.preference.PreferenceScreen import androidx.preference.SwitchPreferenceCompat import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.IOException import java.text.SimpleDateFormat import java.util.Locale abstract class HeanCms( override val name: String, override val baseUrl: String, override val lang: String, protected val apiUrl: String = baseUrl.replace("://", "://api."), ) : ConfigurableSource, HttpSource() { private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override fun setupPreferenceScreen(screen: PreferenceScreen) { SwitchPreferenceCompat(screen.context).apply { key = SHOW_PAID_CHAPTERS_PREF title = intl.prefShowPaidChapterTitle summaryOn = intl.prefShowPaidChapterSummaryOn summaryOff = intl.prefShowPaidChapterSummaryOff setDefaultValue(SHOW_PAID_CHAPTERS_DEFAULT) setOnPreferenceChangeListener { _, newValue -> preferences.edit() .putBoolean(SHOW_PAID_CHAPTERS_PREF, newValue as Boolean) .commit() } }.also(screen::addPreference) } override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient protected open val slugStrategy = SlugStrategy.NONE protected open val useNewQueryEndpoint = false private var seriesSlugMap: Map<String, HeanCmsTitle>? = null /** * Custom Json instance to make usage of `encodeDefaults`, * which is not enabled on the injected instance of the app. */ protected val json: Json = Json { ignoreUnknownKeys = true explicitNulls = false encodeDefaults = true } protected val intl by lazy { HeanCmsIntl(lang) } protected open val coverPath: String = "cover/" protected open val mangaSubDirectory: String = "series" protected open val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", Locale.US) override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("Origin", baseUrl) .add("Referer", "$baseUrl/") override fun popularMangaRequest(page: Int): Request { if (useNewQueryEndpoint) { return newEndpointPopularMangaRequest(page) } val payloadObj = HeanCmsQuerySearchPayloadDto( page = page, order = "desc", orderBy = "total_views", status = "All", type = "Comic", ) val payload = json.encodeToString(payloadObj).toRequestBody(JSON_MEDIA_TYPE) val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .add("Content-Type", payload.contentType().toString()) .build() return POST("$apiUrl/series/querysearch", apiHeaders, payload) } protected fun newEndpointPopularMangaRequest(page: Int): Request { val url = "$apiUrl/query".toHttpUrl().newBuilder() .addQueryParameter("query_string", "") .addQueryParameter("series_status", "All") .addQueryParameter("order", "desc") .addQueryParameter("orderBy", "total_views") .addQueryParameter("series_type", "Comic") .addQueryParameter("page", page.toString()) .addQueryParameter("perPage", "12") .addQueryParameter("tags_ids", "[]") return GET(url.build(), headers) } override fun popularMangaParse(response: Response): MangasPage { val json = response.body.string() if (json.startsWith("{")) { val result = json.parseAs<HeanCmsQuerySearchDto>() val mangaList = result.data.map { if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { map -> map[it.slug.toPermSlugIfNeeded()] = it.slug } } it.toSManga(apiUrl, coverPath, mangaSubDirectory, slugStrategy) } fetchAllTitles() return MangasPage(mangaList, result.meta?.hasNextPage ?: false) } val mangaList = json.parseAs<List<HeanCmsSeriesDto>>() .map { if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { map -> map[it.slug.toPermSlugIfNeeded()] = it.slug } } it.toSManga(apiUrl, coverPath, mangaSubDirectory, slugStrategy) } fetchAllTitles() return MangasPage(mangaList, hasNextPage = false) } override fun latestUpdatesRequest(page: Int): Request { if (useNewQueryEndpoint) { return newEndpointLatestUpdatesRequest(page) } val payloadObj = HeanCmsQuerySearchPayloadDto( page = page, order = "desc", orderBy = "latest", status = "All", type = "Comic", ) val payload = json.encodeToString(payloadObj).toRequestBody(JSON_MEDIA_TYPE) val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .add("Content-Type", payload.contentType().toString()) .build() return POST("$apiUrl/series/querysearch", apiHeaders, payload) } protected fun newEndpointLatestUpdatesRequest(page: Int): Request { val url = "$apiUrl/query".toHttpUrl().newBuilder() .addQueryParameter("query_string", "") .addQueryParameter("series_status", "All") .addQueryParameter("order", "desc") .addQueryParameter("orderBy", "latest") .addQueryParameter("series_type", "Comic") .addQueryParameter("page", page.toString()) .addQueryParameter("perPage", "12") .addQueryParameter("tags_ids", "[]") return GET(url.build(), headers) } override fun latestUpdatesParse(response: Response): MangasPage = popularMangaParse(response) override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { if (!query.startsWith(SEARCH_PREFIX)) { return super.fetchSearchManga(page, query, filters) } val slug = query.substringAfter(SEARCH_PREFIX) val manga = SManga.create().apply { url = if (slugStrategy != SlugStrategy.NONE) { val mangaId = getIdBySlug(slug) "/$mangaSubDirectory/${slug.toPermSlugIfNeeded()}#$mangaId" } else { "/$mangaSubDirectory/$slug" } } return fetchMangaDetails(manga).map { MangasPage(listOf(it), false) } } private fun getIdBySlug(slug: String): Int { val result = runCatching { val response = client.newCall(GET("$apiUrl/series/$slug", headers)).execute() val json = response.body.string() val seriesDetail = json.parseAs<HeanCmsSeriesDto>() preferences.slugMap = preferences.slugMap.toMutableMap() .also { it[seriesDetail.slug.toPermSlugIfNeeded()] = seriesDetail.slug } seriesDetail.id } return result.getOrNull() ?: throw Exception(intl.idNotFoundError + slug) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (useNewQueryEndpoint) { return newEndpointSearchMangaRequest(page, query, filters) } if (query.isNotBlank()) { val searchPayloadObj = HeanCmsSearchPayloadDto(query) val searchPayload = json.encodeToString(searchPayloadObj) .toRequestBody(JSON_MEDIA_TYPE) val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .add("Content-Type", searchPayload.contentType().toString()) .build() return POST("$apiUrl/series/search", apiHeaders, searchPayload) } val sortByFilter = filters.firstInstanceOrNull<SortByFilter>() val payloadObj = HeanCmsQuerySearchPayloadDto( page = page, order = if (sortByFilter?.state?.ascending == true) "asc" else "desc", orderBy = sortByFilter?.selected ?: "total_views", status = filters.firstInstanceOrNull<StatusFilter>()?.selected?.value ?: "Ongoing", type = "Comic", tagIds = filters.firstInstanceOrNull<GenreFilter>()?.state ?.filter(Genre::state) ?.map(Genre::id) .orEmpty(), ) val payload = json.encodeToString(payloadObj).toRequestBody(JSON_MEDIA_TYPE) val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .add("Content-Type", payload.contentType().toString()) .build() return POST("$apiUrl/series/querysearch", apiHeaders, payload) } protected fun newEndpointSearchMangaRequest(page: Int, query: String, filters: FilterList): Request { val sortByFilter = filters.firstInstanceOrNull<SortByFilter>() val statusFilter = filters.firstInstanceOrNull<StatusFilter>() val tagIds = filters.firstInstanceOrNull<GenreFilter>()?.state.orEmpty() .filter(Genre::state) .map(Genre::id) .joinToString(",", prefix = "[", postfix = "]") val url = "$apiUrl/query".toHttpUrl().newBuilder() .addQueryParameter("query_string", query) .addQueryParameter("series_status", statusFilter?.selected?.value ?: "All") .addQueryParameter("order", if (sortByFilter?.state?.ascending == true) "asc" else "desc") .addQueryParameter("orderBy", sortByFilter?.selected ?: "total_views") .addQueryParameter("series_type", "Comic") .addQueryParameter("page", page.toString()) .addQueryParameter("perPage", "12") .addQueryParameter("tags_ids", tagIds) return GET(url.build(), headers) } override fun searchMangaParse(response: Response): MangasPage { val json = response.body.string() if (response.request.url.pathSegments.last() == "search") { fetchAllTitles() val result = json.parseAs<List<HeanCmsSearchDto>>() val mangaList = result .filter { it.type == "Comic" } .map { it.slug = it.slug.toPermSlugIfNeeded() it.toSManga(apiUrl, coverPath, mangaSubDirectory, seriesSlugMap.orEmpty(), slugStrategy) } return MangasPage(mangaList, false) } if (json.startsWith("{")) { val result = json.parseAs<HeanCmsQuerySearchDto>() val mangaList = result.data.map { if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { map -> map[it.slug.toPermSlugIfNeeded()] = it.slug } } it.toSManga(apiUrl, coverPath, mangaSubDirectory, slugStrategy) } fetchAllTitles() return MangasPage(mangaList, result.meta?.hasNextPage ?: false) } val mangaList = json.parseAs<List<HeanCmsSeriesDto>>() .map { if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { map -> map[it.slug.toPermSlugIfNeeded()] = it.slug } } it.toSManga(apiUrl, coverPath, mangaSubDirectory, slugStrategy) } fetchAllTitles() return MangasPage(mangaList, hasNextPage = false) } override fun getMangaUrl(manga: SManga): String { val seriesSlug = manga.url .substringAfterLast("/") .substringBefore("#") .toPermSlugIfNeeded() val currentSlug = if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap[seriesSlug] ?: seriesSlug } else { seriesSlug } return "$baseUrl/$mangaSubDirectory/$currentSlug" } override fun mangaDetailsRequest(manga: SManga): Request { if (slugStrategy != SlugStrategy.NONE && (manga.url.contains(TIMESTAMP_REGEX))) { throw Exception(intl.urlChangedError(name)) } if (slugStrategy == SlugStrategy.ID && !manga.url.contains("#")) { throw Exception(intl.urlChangedError(name)) } val seriesSlug = manga.url .substringAfterLast("/") .substringBefore("#") .toPermSlugIfNeeded() val seriesId = manga.url.substringAfterLast("#") fetchAllTitles() val seriesDetails = seriesSlugMap?.get(seriesSlug) val currentSlug = seriesDetails?.slug ?: seriesSlug val currentStatus = seriesDetails?.status ?: manga.status val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .build() return if (slugStrategy == SlugStrategy.ID) { GET("$apiUrl/series/id/$seriesId", apiHeaders) } else { GET("$apiUrl/series/$currentSlug#$currentStatus", apiHeaders) } } override fun mangaDetailsParse(response: Response): SManga { val mangaStatus = response.request.url.fragment?.toIntOrNull() ?: SManga.UNKNOWN val result = runCatching { response.parseAs<HeanCmsSeriesDto>() } val seriesResult = result.getOrNull() ?: throw Exception(intl.urlChangedError(name)) if (slugStrategy != SlugStrategy.NONE) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { it[seriesResult.slug.toPermSlugIfNeeded()] = seriesResult.slug } } val seriesDetails = seriesResult.toSManga(apiUrl, coverPath, mangaSubDirectory, slugStrategy) return seriesDetails.apply { status = status.takeUnless { it == SManga.UNKNOWN } ?: mangaStatus } } override fun chapterListRequest(manga: SManga): Request = mangaDetailsRequest(manga) override fun chapterListParse(response: Response): List<SChapter> { val result = response.parseAs<HeanCmsSeriesDto>() if (slugStrategy == SlugStrategy.ID) { preferences.slugMap = preferences.slugMap.toMutableMap() .also { it[result.slug.toPermSlugIfNeeded()] = result.slug } } val currentTimestamp = System.currentTimeMillis() val showPaidChapters = preferences.showPaidChapters if (useNewQueryEndpoint) { return result.seasons.orEmpty() .flatMap { it.chapters.orEmpty() } .filter { it.price == 0 || showPaidChapters } .map { it.toSChapter(result.slug, mangaSubDirectory, dateFormat, slugStrategy) } .filter { it.date_upload <= currentTimestamp } } return result.chapters.orEmpty() .filter { it.price == 0 || showPaidChapters } .map { it.toSChapter(result.slug, mangaSubDirectory, dateFormat, slugStrategy) } .filter { it.date_upload <= currentTimestamp } .reversed() } override fun getChapterUrl(chapter: SChapter): String { if (slugStrategy == SlugStrategy.NONE) return baseUrl + chapter.url val seriesSlug = chapter.url .substringAfter("/$mangaSubDirectory/") .substringBefore("/") .toPermSlugIfNeeded() val currentSlug = preferences.slugMap[seriesSlug] ?: seriesSlug val chapterUrl = chapter.url.replaceFirst(seriesSlug, currentSlug) return baseUrl + chapterUrl } override fun pageListRequest(chapter: SChapter): Request { if (useNewQueryEndpoint) { if (slugStrategy != SlugStrategy.NONE) { val seriesPermSlug = chapter.url.substringAfter("/$mangaSubDirectory/").substringBefore("/") val seriesSlug = preferences.slugMap[seriesPermSlug] ?: seriesPermSlug val chapterUrl = chapter.url.replaceFirst(seriesPermSlug, seriesSlug) return GET(baseUrl + chapterUrl, headers) } return GET(baseUrl + chapter.url, headers) } val chapterId = chapter.url.substringAfterLast("#").substringBefore("-paid") val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .build() return GET("$apiUrl/series/chapter/$chapterId", apiHeaders) } override fun pageListParse(response: Response): List<Page> { if (useNewQueryEndpoint) { val paidChapter = response.request.url.fragment?.contains("-paid") val document = response.asJsoup() val images = document.selectFirst("div.min-h-screen > div.container > p.items-center") if (images == null && paidChapter == true) { throw IOException(intl.paidChapterError) } return images?.select("img").orEmpty().mapIndexed { i, img -> val imageUrl = if (img.hasClass("lazy")) img.absUrl("data-src") else img.absUrl("src") Page(i, "", imageUrl) } } val images = response.parseAs<HeanCmsReaderDto>().content?.images.orEmpty() val paidChapter = response.request.url.fragment?.contains("-paid") if (images.isEmpty() && paidChapter == true) { throw IOException(intl.paidChapterError) } return images.filterNot { imageUrl -> // Their image server returns HTTP 403 for hidden files that starts // with a dot in the file name. To avoid download errors, these are removed. imageUrl .removeSuffix("/") .substringAfterLast("/") .startsWith(".") } .mapIndexed { i, url -> Page(i, imageUrl = if (url.startsWith("http")) url else "$apiUrl/$url") } } override fun fetchImageUrl(page: Page): Observable<String> = Observable.just(page.imageUrl!!) override fun imageUrlParse(response: Response): String = "" override fun imageRequest(page: Page): Request { val imageHeaders = headersBuilder() .add("Accept", ACCEPT_IMAGE) .build() return GET(page.imageUrl!!, imageHeaders) } protected open fun fetchAllTitles() { if (!seriesSlugMap.isNullOrEmpty() || slugStrategy != SlugStrategy.FETCH_ALL) { return } val result = runCatching { var hasNextPage = true var page = 1 val tempMap = mutableMapOf<String, HeanCmsTitle>() while (hasNextPage) { val response = client.newCall(allTitlesRequest(page)).execute() val json = response.body.string() if (json.startsWith("{")) { val result = json.parseAs<HeanCmsQuerySearchDto>() tempMap.putAll(parseAllTitles(result.data)) hasNextPage = result.meta?.hasNextPage ?: false page++ } else { val result = json.parseAs<List<HeanCmsSeriesDto>>() tempMap.putAll(parseAllTitles(result)) hasNextPage = false } } tempMap.toMap() } seriesSlugMap = result.getOrNull() preferences.slugMap = preferences.slugMap.toMutableMap() .also { it.putAll(seriesSlugMap.orEmpty().mapValues { (_, v) -> v.slug }) } } protected open fun allTitlesRequest(page: Int): Request { if (useNewQueryEndpoint) { val url = "$apiUrl/query".toHttpUrl().newBuilder() .addQueryParameter("series_type", "Comic") .addQueryParameter("page", page.toString()) .addQueryParameter("perPage", PER_PAGE_MANGA_TITLES.toString()) return GET(url.build(), headers) } val payloadObj = HeanCmsQuerySearchPayloadDto( page = page, order = "desc", orderBy = "total_views", type = "Comic", ) val payload = json.encodeToString(payloadObj).toRequestBody(JSON_MEDIA_TYPE) val apiHeaders = headersBuilder() .add("Accept", ACCEPT_JSON) .add("Content-Type", payload.contentType().toString()) .build() return POST("$apiUrl/series/querysearch", apiHeaders, payload) } protected open fun parseAllTitles(result: List<HeanCmsSeriesDto>): Map<String, HeanCmsTitle> { return result .filter { it.type == "Comic" } .associateBy( keySelector = { it.slug.replace(TIMESTAMP_REGEX, "") }, valueTransform = { HeanCmsTitle( slug = it.slug, thumbnailFileName = it.thumbnail, status = it.status?.toStatus() ?: SManga.UNKNOWN, ) }, ) } /** * Used to store the current slugs for sources that change it periodically and for the * search that doesn't return the thumbnail URLs. */ data class HeanCmsTitle(val slug: String, val thumbnailFileName: String, val status: Int) /** * Used to specify the strategy to use when fetching the slug for a manga. * This is needed because some sources change the slug periodically. * [NONE]: Use series_slug without changes. * [ID]: Use series_id to fetch the slug from the API. * IMPORTANT: [ID] is only available in the new query endpoint. * [FETCH_ALL]: Convert the slug to a permanent slug by removing the timestamp. * At extension start, all the slugs are fetched and stored in a map. */ enum class SlugStrategy { NONE, ID, FETCH_ALL } private fun String.toPermSlugIfNeeded(): String { return if (slugStrategy != SlugStrategy.NONE) { this.replace(TIMESTAMP_REGEX, "") } else { this } } protected open fun getStatusList(): List<Status> = listOf( Status(intl.statusAll, "All"), Status(intl.statusOngoing, "Ongoing"), Status(intl.statusOnHiatus, "Hiatus"), Status(intl.statusDropped, "Dropped"), ) protected open fun getSortProperties(): List<SortProperty> = listOf( SortProperty(intl.sortByTitle, "title"), SortProperty(intl.sortByViews, "total_views"), SortProperty(intl.sortByLatest, "latest"), SortProperty(intl.sortByCreatedAt, "created_at"), ) protected open fun getGenreList(): List<Genre> = emptyList() override fun getFilterList(): FilterList { val genres = getGenreList() val filters = listOfNotNull( Filter.Header(intl.filterWarning), StatusFilter(intl.statusFilterTitle, getStatusList()), SortByFilter(intl.sortByFilterTitle, getSortProperties()), GenreFilter(intl.genreFilterTitle, genres).takeIf { genres.isNotEmpty() }, ) return FilterList(filters) } protected inline fun <reified T> Response.parseAs(): T = use { it.body.string().parseAs() } protected inline fun <reified T> String.parseAs(): T = json.decodeFromString(this) protected inline fun <reified R> List<*>.firstInstanceOrNull(): R? = filterIsInstance<R>().firstOrNull() protected var SharedPreferences.slugMap: MutableMap<String, String> get() { val jsonMap = getString(PREF_URL_MAP_SLUG, "{}")!! val slugMap = runCatching { json.decodeFromString<Map<String, String>>(jsonMap) } return slugMap.getOrNull()?.toMutableMap() ?: mutableMapOf() } set(newSlugMap) { edit() .putString(PREF_URL_MAP_SLUG, json.encodeToString(newSlugMap)) .apply() } private val SharedPreferences.showPaidChapters: Boolean get() = getBoolean(SHOW_PAID_CHAPTERS_PREF, SHOW_PAID_CHAPTERS_DEFAULT) companion object { private const val ACCEPT_IMAGE = "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" private const val ACCEPT_JSON = "application/json, text/plain, */*" private val JSON_MEDIA_TYPE = "application/json".toMediaType() val TIMESTAMP_REGEX = """-\d{13}$""".toRegex() private const val PER_PAGE_MANGA_TITLES = 10000 const val SEARCH_PREFIX = "slug:" private const val PREF_URL_MAP_SLUG = "pref_url_map" private const val SHOW_PAID_CHAPTERS_PREF = "pref_show_paid_chap" private const val SHOW_PAID_CHAPTERS_DEFAULT = false } }
632
null
1252
9
8ca7f06a4fdfbfdd66520a4798c8636274263428
25,999
tachiyomi-extensions
Apache License 2.0
src/main/kotlin/dev/monosoul/jooq/settings/Image.kt
monosoul
497,003,599
false
null
package dev.monosoul.jooq.settings import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional data class Image( @get:Input var name: String = "postgres:14.4-alpine", @get:Input var envVars: Map<String, String> = mapOf(), @get:Input var testQuery: String = "SELECT 1", @get:Input @get:Optional var command: String? = null, ) : SettingsElement { constructor(database: Database.Internal) : this( envVars = mapOf( "POSTGRES_USER" to database.username, "POSTGRES_PASSWORD" to database.password, "POSTGRES_DB" to database.name, ), ) }
2
Kotlin
5
9
f3cc5cbaf77e3a2a22c767fee75de4f809cea477
647
jooq-gradle-plugin
Apache License 2.0
src/test/java/no/nav/familie/integrasjoner/dokarkiv/DokarkivControllerTest.kt
navikt
224,182,192
false
{"Kotlin": 555751, "Java": 39493, "Dockerfile": 204}
package no.nav.familie.integrasjoner.dokarkiv import ch.qos.logback.classic.Logger import ch.qos.logback.classic.spi.ILoggingEvent import com.fasterxml.jackson.module.kotlin.KotlinModule import no.nav.familie.integrasjoner.OppslagSpringRunnerTest import no.nav.familie.kontrakter.felles.BrukerIdType import no.nav.familie.kontrakter.felles.Ressurs import no.nav.familie.kontrakter.felles.Tema import no.nav.familie.kontrakter.felles.dokarkiv.ArkiverDokumentResponse import no.nav.familie.kontrakter.felles.dokarkiv.BulkOppdaterLogiskVedleggRequest import no.nav.familie.kontrakter.felles.dokarkiv.DokarkivBruker import no.nav.familie.kontrakter.felles.dokarkiv.Dokumenttype import no.nav.familie.kontrakter.felles.dokarkiv.LogiskVedleggRequest import no.nav.familie.kontrakter.felles.dokarkiv.LogiskVedleggResponse import no.nav.familie.kontrakter.felles.dokarkiv.OppdaterJournalpostRequest import no.nav.familie.kontrakter.felles.dokarkiv.OppdaterJournalpostResponse import no.nav.familie.kontrakter.felles.dokarkiv.Sak import no.nav.familie.kontrakter.felles.dokarkiv.v2.ArkiverDokumentRequest import no.nav.familie.kontrakter.felles.dokarkiv.v2.Dokument import no.nav.familie.kontrakter.felles.dokarkiv.v2.Filtype import no.nav.familie.kontrakter.felles.objectMapper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockserver.integration.ClientAndServer import org.mockserver.junit.jupiter.MockServerExtension import org.mockserver.junit.jupiter.MockServerSettings import org.mockserver.model.HttpRequest.request import org.mockserver.model.HttpResponse.response import org.mockserver.model.JsonBody.json import org.slf4j.LoggerFactory import org.springframework.boot.test.web.client.exchange import org.springframework.core.io.ClassPathResource import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.test.context.ActiveProfiles import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.util.LinkedList import kotlin.test.assertFalse @ActiveProfiles(profiles = ["integrasjonstest", "mock-sts", "mock-aktor", "mock-personopplysninger", "mock-pdl"]) @ExtendWith(MockServerExtension::class) @MockServerSettings(ports = [OppslagSpringRunnerTest.MOCK_SERVER_PORT]) class DokarkivControllerTest(private val client: ClientAndServer) : OppslagSpringRunnerTest() { @BeforeEach fun setUp() { client.reset() headers.setBearerAuth(lokalTestToken) objectMapper.registerModule(KotlinModule.Builder().build()) (LoggerFactory.getLogger("secureLogger") as Logger) .addAppender(listAppender) } @Test fun `skal returnere bad request hvis ingen hoveddokumenter`() { val body = ArkiverDokumentRequest( "fnr", false, LinkedList(), ) val responseDeprecated: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headers), ) assertThat(responseDeprecated.statusCode).isEqualTo(HttpStatus.BAD_REQUEST) assertThat(responseDeprecated.body?.status).isEqualTo(Ressurs.Status.FEILET) assertThat(responseDeprecated.body?.melding).contains("hoveddokumentvarianter=must not be empty") } @Test fun `skal midlertidig journalføre dokument`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/journalpost") .withQueryStringParameter("forsoekFerdigstill", "false"), ) .respond(response().withBody(json(gyldigDokarkivResponse()))) val body = ArkiverDokumentRequest( "FNR", false, listOf(HOVEDDOKUMENT), ) val response: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) assertThat(response.body?.data?.journalpostId).isEqualTo("12345678") assertFalse(response.body?.data?.ferdigstilt!!) } @Test fun `skal sende med navIdent fra header til journalpost`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/journalpost") .withQueryStringParameter("forsoekFerdigstill", "false"), ) .respond(response().withBody(json(gyldigDokarkivResponse()))) val body = ArkiverDokumentRequest( "FNR", false, listOf(HOVEDDOKUMENT), ) val response: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headersWithNavUserId()), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) assertThat(response.body?.data?.journalpostId).isEqualTo("12345678") assertFalse(response.body?.data?.ferdigstilt!!) client.verify(request().withHeader("Nav-User-Id", "k123123")) } @Test fun `skal returnere 409 ved 409 response fra dokarkiv`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/journalpost") .withQueryStringParameter("forsoekFerdigstill", "false"), ) .respond( response() .withStatusCode(409) .withHeader("Content-Type", "application/json;charset=UTF-8") .withBody("Tekst fra body"), ) val body = ArkiverDokumentRequest( "FNR", false, listOf(HOVEDDOKUMENT), ) val response: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headersWithNavUserId()), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CONFLICT) assertThat(response.body?.status).isEqualTo(Ressurs.Status.FEILET) assertThat(response.body?.melding).isEqualTo("[Dokarkiv][Feil ved opprettelse av journalpost ][org.springframework.web.client.HttpClientErrorException\$Conflict]") } @Test fun `skal midlertidig journalføre dokument med vedlegg`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/journalpost") .withQueryStringParameter("forsoekFerdigstill", "false"), ) .respond(response().withBody(json(gyldigDokarkivResponse()))) val body = ArkiverDokumentRequest( "FNR", false, listOf(HOVEDDOKUMENT), listOf(VEDLEGG), ) val response: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) assertThat(response.body?.data?.journalpostId).isEqualTo("12345678") assertFalse(response.body?.data?.ferdigstilt!!) } @Test fun `dokarkiv returnerer 401`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/journalpost") .withQueryStringParameter("forsoekFerdigstill", "false"), ) .respond( response() .withStatusCode(401) .withHeader("Content-Type", "application/json;charset=UTF-8") .withBody("Tekst fra body"), ) val body = ArkiverDokumentRequest( "FNR", false, listOf(HOVEDDOKUMENT), ) val responseDeprecated: ResponseEntity<Ressurs<ArkiverDokumentResponse>> = restTemplate.exchange( localhost(DOKARKIV_URL_V4), HttpMethod.POST, HttpEntity(body, headers), ) assertThat(responseDeprecated.statusCode).isEqualTo(HttpStatus.UNAUTHORIZED) assertThat(responseDeprecated.body?.status).isEqualTo(Ressurs.Status.FEILET) assertThat(responseDeprecated.body?.melding).contains("Unauthorized") } @Test fun `oppdaterJournalpost returnerer OK`() { val journalpostId = "12345678" client.`when`( request() .withMethod("PUT") .withPath("/rest/journalpostapi/v1/journalpost/$journalpostId"), ) .respond(response().withBody(json(gyldigDokarkivResponse()))) val body = OppdaterJournalpostRequest( bruker = DokarkivBruker(BrukerIdType.FNR, "12345678910"), tema = Tema.ENF, sak = Sak("11111111", "fagsaksystem"), ) val response: ResponseEntity<Ressurs<OppdaterJournalpostResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL_V2/12345678"), HttpMethod.PUT, HttpEntity(body, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) assertThat(response.body?.data?.journalpostId).isEqualTo("12345678") } @Test fun `dokarkiv skal logge detaljert feilmelding til secureLogger ved HttpServerErrorExcetion`() { val journalpostId = "12345678" client.`when`( request() .withMethod("PUT") .withPath("/rest/journalpostapi/v1/journalpost/$journalpostId"), ) .respond( response().withStatusCode(500) .withHeader("Content-Type", "application/json;charset=UTF-8") .withBody(gyldigDokarkivResponse(500)), ) val body = OppdaterJournalpostRequest( bruker = DokarkivBruker(BrukerIdType.FNR, "12345678910"), tema = Tema.ENF, sak = Sak("11111111", "fagsaksystem"), ) val response: ResponseEntity<Ressurs<OppdaterJournalpostResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL_V2/12345678"), HttpMethod.PUT, HttpEntity(body, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) assertThat(response.body?.status).isEqualTo(Ressurs.Status.FEILET) assertThat(loggingEvents) .extracting<String, RuntimeException> { obj: ILoggingEvent -> obj.formattedMessage } .anyMatch { message -> message.contains("Fant ikke person med ident: 12345678910") } } @Test fun `ferdigstill returnerer ok`() { client.`when`( request() .withMethod("PATCH") .withPath("/rest/journalpostapi/v1/journalpost/123/ferdigstill"), ) .respond(response().withStatusCode(200).withBody("Journalpost ferdigstilt")) val response: ResponseEntity<Ressurs<Map<String, String>>> = restTemplate.exchange( localhost("$DOKARKIV_URL_V2/123/ferdigstill?journalfoerendeEnhet=9999"), HttpMethod.PUT, HttpEntity(null, headersWithNavUserId()), ) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) client.verify(request().withHeader("Nav-User-Id", "k123123")) } @Test fun `ferdigstill returnerer 400 hvis ikke mulig ferdigstill`() { client.`when`( request() .withMethod("PATCH") .withPath("/rest/journalpostapi/v1/journalpost/123/ferdigstill"), ) .respond(response().withStatusCode(400)) val response: ResponseEntity<Ressurs<Map<String, String>>> = restTemplate.exchange( localhost("$DOKARKIV_URL_V2/123/ferdigstill?journalfoerendeEnhet=9999"), HttpMethod.PUT, HttpEntity(null, headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST) assertThat(response.body?.status).isEqualTo(Ressurs.Status.FEILET) assertThat(response.body?.melding).contains("Kan ikke ferdigstille journalpost 123") } @Test fun `skal opprette logisk vedlegg`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/dokumentInfo/321/logiskVedlegg/"), ) .respond( response() .withStatusCode(200) .withBody(json(objectMapper.writeValueAsString(LogiskVedleggResponse(21L)))), ) val response: ResponseEntity<Ressurs<LogiskVedleggResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL/dokument/321/logiskVedlegg"), HttpMethod.POST, HttpEntity(LogiskVedleggRequest("Ny tittel"), headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED) assertThat(response.body?.data?.logiskVedleggId).isEqualTo(21L) assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) } @Test fun `skal returnere feil hvis man ikke kan opprette logisk vedlegg`() { client.`when`( request() .withMethod("POST") .withPath("/rest/journalpostapi/v1/dokumentInfo/321/logiskVedlegg/"), ) .respond( response() .withStatusCode(404) .withBody("melding fra klient"), ) val response: ResponseEntity<Ressurs<LogiskVedleggResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL/dokument/321/logiskVedlegg"), HttpMethod.POST, HttpEntity(LogiskVedleggRequest("Ny tittel"), headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) assertThat(response.body?.melding).contains("melding fra klient") assertThat(response.body?.status).isEqualTo(Ressurs.Status.FEILET) } @Test fun `skal slette logisk vedlegg`() { client.`when`( request() .withMethod("DELETE") .withPath("/rest/journalpostapi/v1/dokumentInfo/321/logiskVedlegg/432"), ) .respond( response() .withStatusCode(200), ) val response: ResponseEntity<Ressurs<LogiskVedleggResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL/dokument/321/logiskVedlegg/432"), HttpMethod.DELETE, HttpEntity(LogiskVedleggRequest("Ny tittel"), headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body?.data?.logiskVedleggId).isEqualTo(432L) assertThat(response.body?.melding).contains("logisk vedlegg slettet") assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) } @Test fun `skal bulk oppdatere logiske vedlegg for et dokument`() { client.`when`( request() .withMethod("PUT") .withPath("/rest/journalpostapi/v1/dokumentInfo/321/logiskVedlegg"), ) .respond( response() .withStatusCode(204), ) val response: ResponseEntity<Ressurs<String>> = restTemplate.exchange( localhost("$DOKARKIV_URL/dokument/321/logiskVedlegg"), HttpMethod.PUT, HttpEntity(BulkOppdaterLogiskVedleggRequest(titler = listOf("Logisk vedlegg 1", "Logisk vedlegg 2")), headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.OK) assertThat(response.body?.data).isEqualTo("321") assertThat(response.body?.melding).contains("logiske vedlegg oppdatert") assertThat(response.body?.status).isEqualTo(Ressurs.Status.SUKSESS) } @Test fun `skal returnere feil hvis man ikke kan slette logisk vedlegg`() { client.`when`( request() .withMethod("DELETE") .withPath("/rest/journalpostapi/v1/dokumentInfo/321/logiskVedlegg/432"), ) .respond( response() .withStatusCode(404) .withBody("sletting feilet"), ) val response: ResponseEntity<Ressurs<LogiskVedleggResponse>> = restTemplate.exchange( localhost("$DOKARKIV_URL/dokument/321/logiskVedlegg/432"), HttpMethod.DELETE, HttpEntity(LogiskVedleggRequest("Ny tittel"), headers), ) assertThat(response.statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) assertThat(response.body?.melding).contains("sletting feilet") assertThat(response.body?.status).isEqualTo(Ressurs.Status.FEILET) } @Throws(IOException::class) private fun gyldigDokarkivResponse(statusKode: Int? = null): String { return Files.readString( ClassPathResource("dokarkiv/gyldig${statusKode ?: ""}response.json").file.toPath(), StandardCharsets.UTF_8, ) } private fun headersWithNavUserId(): HttpHeaders { return headers.apply { add("Nav-User-Id", NAV_USER_ID_VALUE) } } companion object { private const val DOKARKIV_URL = "/api/arkiv" private const val DOKARKIV_URL_V2 = "$DOKARKIV_URL/v2" private const val DOKARKIV_URL_V4 = "$DOKARKIV_URL/v4" private const val NAV_USER_ID_VALUE = "k123123" private val HOVEDDOKUMENT = Dokument( "foo".toByteArray(), Filtype.JSON, "filnavn", null, Dokumenttype.KONTANTSTØTTE_SØKNAD, ) private val VEDLEGG = Dokument( "foo".toByteArray(), Filtype.PDFA, "filnavn", "Vedlegg", Dokumenttype.KONTANTSTØTTE_SØKNAD_VEDLEGG, ) } }
9
Kotlin
0
3
9f8acc90db019f87400d1810b581ebe5347c5025
19,577
familie-integrasjoner
MIT License
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/Dijkstras.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* class Dijkstras { fun dijkstrasAlgorithm(start: Int, edges: List<List<List<Int>>>): List<Int> { val numberOfVertices = edges.size val minDist = MutableList<Int>(edges.size) { Int.MAX_VALUE } minDist[start] = 0 val minDistPair = mutableListOf<Pair<Int, Int>>() for (i in 0 until edges.size) { minDistPair.add(Pair(i, Int.MAX_VALUE)) } val pq = PriorityQueue<Pair<Int, Int>>() pq.add(Pair(start, 0)) while (pq.isNotEmpty()) { val (vertex, currentMin) = pq.remove()!! if (currentMin == Int.MAX_VALUE) break for (edge in edges[vertex]) { val (destination, distance) = edge val newPath = currentMin + distance val currentDistance = minDist[destination] if (newPath < currentDistance) { minDist[destination] = newPath pq.add(Pair(destination, newPath)) } } } return minDist.map() { x -> if (x == Int.MAX_VALUE) -1 else x } } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,179
DS_Algo_Kotlin
MIT License
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/common/Resources.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.common import java.io.IOException internal object Resources /** * Reads a file from the resources. * @param fileName the name of the file, relative to the resources root * @return the contents of the resource */ fun readResource(fileName: String) = Resources.javaClass.getResource("/$fileName")?.readText()?.trim() ?: throw IOException("File does not exist: $fileName")
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
403
advent-of-code
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsprisonvisitstestinghelperapi/integration/VisitControllerIntegrationTest.kt
ministryofjustice
724,574,246
false
{"Kotlin": 185225, "Dockerfile": 1380, "Shell": 238}
package uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.integration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.springframework.http.HttpHeaders import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.CreateNotificationEventDto import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.enums.TestDBNotificationEventTypes.PRISON_VISITS_BLOCKED_FOR_DATE import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.enums.VisitNoteType import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.enums.VisitStatus import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.enums.VisitStatus.BOOKED import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.dto.enums.VisitStatus.CANCELLED import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.helper.callDelete import uk.gov.justice.digital.hmpps.hmppsprisonvisitstestinghelperapi.helper.callPut import java.time.LocalDate import java.time.LocalTime @DisplayName("Visit Controller") class VisitControllerIntegrationTest : IntegrationTestBase() { val prisonCode = "HEI" val prison2Code = "BLI" val sessionTemplateReference = "session-1" val sessionSlotReference = "session-slot-1" val sessionTimeSlotStart: LocalTime = LocalTime.of(9, 0) val sessionTimeSlotEnd: LocalTime = LocalTime.of(10, 0) val existingStatus = BOOKED val visitDate: LocalDate = LocalDate.now() val visitReference = "aa-bb-cc-dd" @BeforeEach fun setup() { clearDb() dBRepository.createPrison(prisonCode) dBRepository.createPrison(prison2Code) dBRepository.createSessionTemplate(prisonCode, "room", "SOCIAL", 10, 1, sessionTimeSlotStart, sessionTimeSlotEnd, LocalDate.now(), LocalDate.now().dayOfWeek, sessionTemplateReference, sessionTemplateReference) dBRepository.createSessionSlot("session-slot-1", visitDate, visitDate.atTime(sessionTimeSlotStart), visitDate.atTime(sessionTimeSlotEnd), sessionTemplateReference) } @AfterEach fun clearAll() { clearDb() } @Test fun `when visit status change called visit status is updated`() { // Given val newStatus = CANCELLED dBRepository.createVisit("AA123", visitReference, "SOCIAL", "ROOM-1", existingStatus, "OPEN", sessionSlotReference) // When val responseSpec = callChangeVisitStatus(webTestClient, setAuthorisation(roles = listOf("ROLE_TEST_VISIT_SCHEDULER")), visitReference, newStatus) // Then responseSpec.expectStatus().isOk val updatedStatus = dBRepository.getVisitStatus(visitReference) assertThat(updatedStatus).isEqualTo(CANCELLED.toString()) } @Test fun `when visit prison change called visit prison is updated`() { // Given dBRepository.createVisit("AA123", visitReference, "SOCIAL", "ROOM-1", existingStatus, "OPEN", sessionSlotReference) // When val responseSpec = callChangeVisitPrison(webTestClient, setAuthorisation(roles = listOf("ROLE_TEST_VISIT_SCHEDULER")), visitReference, prison2Code) // Then responseSpec.expectStatus().isOk val updatedPrisonCode = dBRepository.getVisitPrisonCode(visitReference) assertThat(updatedPrisonCode).isEqualTo(prison2Code) } @Test fun `when delete visit and children called then visit and all children related are deleted`() { // Given val visitNotificationReference = "aa-11-bb-22-aa" visitSchedulerMockServer.stubCancelVisit(visitReference) dBRepository.createVisit("AA123", visitReference, "SOCIAL", "ROOM-1", existingStatus, "OPEN", sessionSlotReference) dBRepository.createVisitVisitor(visitReference, 4776543, true) dBRepository.createVisitSupport(visitReference, "visit support description") dBRepository.createVisitNote(visitReference, VisitNoteType.VISIT_COMMENT, "visit note description") dBRepository.createVisitContact(visitReference, "John", "07777777777") dBRepository.createVisitNotification("PRISON_VISITS_BLOCKED_FOR_DATE", visitNotificationReference, visitReference) dBRepository.createActionedBy("", "ALED", "STAFF") val actionById = dBRepository.getActionById() dBRepository.createEventAudit(visitReference, "appRef", sessionSlotReference, "BOOKED_VISIT", "NOT_KNOWN", actionById) val visitId = dBRepository.getVisitIdByReference(visitReference) // When val responseSpec = callDeleteVisitAndAllChildren(webTestClient, setAuthorisation(roles = listOf("ROLE_TEST_VISIT_SCHEDULER")), visitReference) // Then assertDeletedVisitAndAssociatedObjectsHaveBeenDeleted(responseSpec, visitReference, visitId, actionById) } @Test fun `when delete visit notification event called all visit notifications are deleted`() { // Given val visitNotificationReference = "aa-11-bb-22" dBRepository.createVisit("AA123", visitReference, "SOCIAL", "ROOM-1", existingStatus, "OPEN", sessionSlotReference) dBRepository.createVisitNotification("PRISON_VISITS_BLOCKED_FOR_DATE", visitNotificationReference, visitReference) val hasVisitNotificationsBeforeCall = dBRepository.hasVisitNotificationsByBookingReference(visitReference) val responseSpec = callDeleteVisitNotificationEvents(webTestClient, setAuthorisation(roles = listOf("ROLE_TEST_VISIT_SCHEDULER")), visitReference) // Then responseSpec.expectStatus().isOk assertThat(hasVisitNotificationsBeforeCall).isTrue() val hasVisitNotifications = dBRepository.hasVisitNotificationsByBookingReference(visitReference) assertThat(hasVisitNotifications).isFalse() } @Test fun `when create visit notification event called visit notification events are created`() { // Given dBRepository.createVisit("AA123", visitReference, "SOCIAL", "ROOM-1", existingStatus, "OPEN", sessionSlotReference) val hasVisitNotificationsBeforeCall = dBRepository.hasVisitNotificationsByBookingReference(visitReference) val responseSpec = callCreateVisitNotificationEvents(webTestClient, setAuthorisation(roles = listOf("ROLE_TEST_VISIT_SCHEDULER")), visitReference, CreateNotificationEventDto(PRISON_VISITS_BLOCKED_FOR_DATE)) // Then responseSpec.expectStatus().isCreated assertThat(hasVisitNotificationsBeforeCall).isFalse() val hasVisitNotifications = dBRepository.hasVisitNotificationsByBookingReference(visitReference) assertThat(hasVisitNotifications).isTrue() } private fun assertDeletedVisitAndAssociatedObjectsHaveBeenDeleted(responseSpec: ResponseSpec, visitReference: String, visitId: Long, actionById: Int) { responseSpec.expectStatus().isOk assertThat(dBRepository.hasVisitWithReference(visitReference)).isFalse() assertThat(dBRepository.hasVisitVisitor(visitId)).isFalse() assertThat(dBRepository.hasVisitSupport(visitId)).isFalse() assertThat(dBRepository.hasVisitContact(visitId)).isFalse() assertThat(dBRepository.hasVisitNotes(visitId)).isFalse() assertThat(dBRepository.hasVisitNotificationsByBookingReference(visitReference)).isFalse() assertThat(dBRepository.hasEventAuditByBookingReference(visitReference)).isFalse() assertThat(dBRepository.hasActionedBy(actionById)).isFalse() } private fun callDeleteVisitAndAllChildren( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, ): ResponseSpec { return callDelete( webTestClient, "test/visit/$reference", authHttpHeaders, ) } private fun callChangeVisitStatus( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, status: VisitStatus, ): ResponseSpec { return callPut( null, webTestClient, "test/visit/$reference/status/$status", authHttpHeaders, ) } private fun callChangeVisitPrison( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, prisonCode: String, ): ResponseSpec { return callPut( null, webTestClient, "test/visit/$reference/change/prison/$prisonCode", authHttpHeaders, ) } private fun callDeleteVisitNotificationEvents( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, ): ResponseSpec { return callDelete( webTestClient, "test/visit/$reference/notifications", authHttpHeaders, ) } private fun callCreateVisitNotificationEvents( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, createNotificationEvent: CreateNotificationEventDto, ): ResponseSpec { return callPut( createNotificationEvent, webTestClient, "test/visit/$reference/notifications", authHttpHeaders, ) } private fun callCancelVisit( webTestClient: WebTestClient, authHttpHeaders: (HttpHeaders) -> Unit, reference: String, ): ResponseSpec { return callDelete( webTestClient, "test/visit/$reference/cancel", authHttpHeaders, ) } }
5
Kotlin
0
0
d4684e057a15241b2191b8a0e1c3357f91f7d2e8
9,288
hmpps-prison-visits-testing-helper-api
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/config/RedisConfiguration.kt
ministryofjustice
515,276,548
false
null
package uk.gov.justice.digital.hmpps.approvedpremisesapi.config import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer import org.springframework.boot.info.BuildProperties import org.springframework.cache.annotation.EnableCaching import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.cache.RedisCacheConfiguration import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder import org.springframework.data.redis.connection.RedisConnectionFactory import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair import org.springframework.data.redis.serializer.RedisSerializer import org.springframework.data.redis.serializer.StringRedisSerializer import org.springframework.http.HttpStatus import redis.lock.redlock.RedLock import uk.gov.justice.digital.hmpps.approvedpremisesapi.client.ClientResult import uk.gov.justice.digital.hmpps.approvedpremisesapi.client.MarshallableHttpMethod import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.bankholidaysapi.UKBankHolidays import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.StaffUserDetails import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.UserOffenderAccess import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.CaseDetail import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.ManagingTeamsResponse import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.StaffMembersPage import java.time.Duration @Configuration @EnableCaching class RedisConfiguration { @Bean fun redisCacheManagerBuilderCustomizer( buildProperties: BuildProperties, objectMapper: ObjectMapper, @Value("\${caches.staffMembers.expiry-seconds}") staffMembersExpirySeconds: Long, @Value("\${caches.staffMember.expiry-seconds}") staffMemberExpirySeconds: Long, @Value("\${caches.userAccess.expiry-seconds}") userAccessExpirySeconds: Long, @Value("\${caches.staffDetails.expiry-seconds}") staffDetailsExpirySeconds: Long, @Value("\${caches.teamManagingCases.expiry-seconds}") teamManagingCasesExpirySeconds: Long, @Value("\${caches.ukBankHolidays.expiry-seconds}") ukBankHolidaysExpirySeconds: Long, @Value("21600") crnGetCaseDetailExpirySeconds: Long, ): RedisCacheManagerBuilderCustomizer? { val time = buildProperties.time.epochSecond.toString() return RedisCacheManagerBuilderCustomizer { builder: RedisCacheManagerBuilder -> builder.clientCacheFor<StaffMembersPage>("qCodeStaffMembersCache", Duration.ofSeconds(staffMembersExpirySeconds), time, objectMapper) .clientCacheFor<UserOffenderAccess>("userAccessCache", Duration.ofSeconds(userAccessExpirySeconds), time, objectMapper) .clientCacheFor<StaffUserDetails>("staffDetailsCache", Duration.ofSeconds(staffDetailsExpirySeconds), time, objectMapper) .clientCacheFor<ManagingTeamsResponse>("teamsManagingCaseCache", Duration.ofSeconds(teamManagingCasesExpirySeconds), time, objectMapper) .clientCacheFor<CaseDetail>("crnGetCaseDetailCache", Duration.ofSeconds(crnGetCaseDetailExpirySeconds), time, objectMapper) .clientCacheFor<UKBankHolidays>("ukBankHolidaysCache", Duration.ofSeconds(ukBankHolidaysExpirySeconds), time, objectMapper) } } @Bean fun redisTemplate(connectionFactory: RedisConnectionFactory): RedisTemplate<*, *>? { val template: RedisTemplate<*, *> = RedisTemplate<Any, Any>() template.connectionFactory = connectionFactory template.keySerializer = StringRedisSerializer() return template } @Bean fun redLock( @Value("\${spring.redis.host}") host: String, @Value("\${spring.redis.port}") port: Int, @Value("\${spring.redis.password}") password: String, @Value("\${spring.redis.database}") database: Int, @Value("\${spring.redis.ssl}") ssl: Boolean, ): RedLock { val scheme = if (ssl) "rediss" else "redis" val passwordString = if (password.isNotEmpty()) ":$password@" else "" return RedLock(arrayOf("$scheme://$passwordString$host:$port/$database")) } private inline fun <reified T> RedisCacheManagerBuilder.clientCacheFor(cacheName: String, duration: Duration, version: String, objectMapper: ObjectMapper) = this.withCacheConfiguration( cacheName, RedisCacheConfiguration.defaultCacheConfig() .entryTtl(duration) .serializeValuesWith(SerializationPair.fromSerializer(ClientResultRedisSerializer(objectMapper, object : TypeReference<T>() {}))) .prefixCacheNameWith(version), ) } class ClientResultRedisSerializer( private val objectMapper: ObjectMapper, private val typeReference: TypeReference<*>, ) : RedisSerializer<ClientResult<*>> { override fun serialize(clientResult: ClientResult<*>?): ByteArray { val toSerialize = when (clientResult) { is ClientResult.Failure.StatusCode -> { SerializableClientResult( discriminator = ClientResultDiscriminator.STATUS_CODE_FAILURE, status = clientResult.status, body = clientResult.body, exceptionMessage = null, type = null, method = MarshallableHttpMethod.fromHttpMethod(clientResult.method), path = clientResult.path, ) } is ClientResult.Failure.Other -> { SerializableClientResult( discriminator = ClientResultDiscriminator.OTHER_FAILURE, status = null, body = null, exceptionMessage = clientResult.exception.message, type = null, method = MarshallableHttpMethod.fromHttpMethod(clientResult.method), path = clientResult.path, ) } is ClientResult.Failure.PreemptiveCacheTimeout -> throw RuntimeException("Preemptively cached requests should not be annotated with @Cacheable") is ClientResult.Success -> { SerializableClientResult( discriminator = ClientResultDiscriminator.SUCCESS, status = clientResult.status, body = objectMapper.writeValueAsString(clientResult.body), exceptionMessage = null, type = clientResult.body!!::class.java.typeName, method = null, path = null, ) } else -> null } return objectMapper.writeValueAsBytes(toSerialize) } override fun deserialize(bytes: ByteArray?): ClientResult<Any>? { val deserializedWrapper = objectMapper.readValue(bytes, SerializableClientResult::class.java) if (deserializedWrapper.discriminator == ClientResultDiscriminator.SUCCESS) { return ClientResult.Success( status = deserializedWrapper.status!!, body = objectMapper.readValue(deserializedWrapper.body, typeReference), ) } if (deserializedWrapper.discriminator == ClientResultDiscriminator.STATUS_CODE_FAILURE) { return ClientResult.Failure.StatusCode( method = deserializedWrapper.method!!.toHttpMethod(), path = deserializedWrapper.path!!, status = deserializedWrapper.status!!, body = deserializedWrapper.body, ) } if (deserializedWrapper.discriminator == ClientResultDiscriminator.OTHER_FAILURE) { return ClientResult.Failure.Other( method = deserializedWrapper.method!!.toHttpMethod(), path = deserializedWrapper.path!!, exception = RuntimeException(deserializedWrapper.exceptionMessage), ) } throw RuntimeException("Unhandled discriminator type: ${deserializedWrapper.discriminator}") } } data class SerializableClientResult( val discriminator: ClientResultDiscriminator, val type: String?, val status: HttpStatus?, val body: String?, val exceptionMessage: String?, val method: MarshallableHttpMethod?, val path: String?, ) enum class ClientResultDiscriminator { SUCCESS, STATUS_CODE_FAILURE, OTHER_FAILURE, } const val IS_NOT_SUCCESSFUL = "!(#result instanceof T(uk.gov.justice.digital.hmpps.approvedpremisesapi.client.ClientResult\$Success))"
30
null
2
5
5b02281acd56772dc5d587f8cd4678929a191ac0
8,325
hmpps-approved-premises-api
MIT License
app/src/main/java/droiddevelopers254/droidconke/models/SessionTimeModel.kt
droidconKE
132,411,780
false
null
package com.android254.droidconke19.models data class SessionTimeModel( val sessionHour: String, val amPm: String )
3
null
25
21
1c82965bf1fb0737ad1420ef4e4f0c96681f18a0
133
droidconKE
MIT License
src/main/java/org/mapdb/Store.kt
shabanovd
89,575,963
false
null
package org.mapdb /** * Stores records */ interface StoreImmutable { fun <R> get(recid: Long, serializer: Serializer<R>): R? fun getAllRecids(): LongIterator fun getAllRecidsSize():Long { val iter = getAllRecids() var c:Long = 0L while(iter.hasNext()){ iter.nextLong() c++ } return c } fun getAllFiles(): Iterable<String> } /** * Stores records, mutable version */ interface Store: StoreImmutable, Verifiable, ConcurrencyAware { fun preallocate():Long; fun <R> put(record: R?, serializer: Serializer<R>):Long fun <R> update(recid: Long, record: R?, serializer: Serializer<R>) fun <R> compareAndSwap(recid: Long, expectedOldRecord: R?, newRecord: R?, serializer: Serializer<R> ): Boolean fun <R> delete(recid: Long, serializer: Serializer<R>) fun commit(); fun compact() fun close(); val isClosed:Boolean; override fun verify() val isReadOnly: Boolean fun fileLoad(): Boolean; } /** * Stores records, transactional version */ interface StoreTx:Store{ fun rollback(); } interface StoreBinary:Store{ fun getBinaryLong(recid:Long, f: StoreBinaryGetLong):Long }
0
null
1
1
c5ff8a0388daf3ddef5872a4f3d58a6ebf3e3d06
1,334
mapdb
Apache License 2.0
core/src/main/java/com/fightpandemics/core/dagger/module/DataModule.kt
FightPandemics
261,618,622
false
null
package com.fightpandemics.core.dagger.module import com.fightpandemics.core.data.local.AuthTokenLocalDataSource import com.fightpandemics.core.data.local.AuthTokenLocalDataSourceImpl import com.fightpandemics.core.data.prefs.FightPandemicsPreferenceDataStore import com.fightpandemics.core.data.prefs.PreferenceStorage import com.fightpandemics.core.data.remote.location.LocationRemoteDataSource import com.fightpandemics.core.data.remote.login.LoginRemoteDataSource import com.fightpandemics.core.data.remote.posts.PostsRemoteDataSource import com.fightpandemics.core.data.remote.profile.ProfileRemoteDataSource import com.fightpandemics.core.data.repository.LocationRepositoryImpl import com.fightpandemics.core.data.repository.LoginRepositoryImpl import com.fightpandemics.core.data.repository.PostsRepositoryImpl import com.fightpandemics.core.data.repository.ProfileRepositoryImpl import com.fightpandemics.core.domain.repository.LocationRepository import com.fightpandemics.core.domain.repository.LoginRepository import com.fightpandemics.core.domain.repository.PostsRepository import com.fightpandemics.core.domain.repository.ProfileRepository import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import javax.inject.Singleton /** * created by <NAME> * * Dagger module to provide data functionalities. */ @FlowPreview @ExperimentalCoroutinesApi @Module class DataModule { @Singleton @Provides fun providePostsRepository( preferenceStorage: PreferenceStorage, postsRemoteDataSource: PostsRemoteDataSource ): PostsRepository = PostsRepositoryImpl(preferenceStorage, postsRemoteDataSource) @Singleton @Provides fun provideLoginRepository( moshi: Moshi, loginRemoteDataSource: LoginRemoteDataSource, authTokenLocalDataSource: AuthTokenLocalDataSource ): LoginRepository = LoginRepositoryImpl(moshi, loginRemoteDataSource, authTokenLocalDataSource) @Singleton @Provides fun provideLocationRepository( moshi: Moshi, locationRemoteDataSource: LocationRemoteDataSource, preferenceStorage: PreferenceStorage ): LocationRepository = LocationRepositoryImpl(moshi, locationRemoteDataSource, preferenceStorage) @Singleton @Provides fun provideAuthTokenLocalDataSource( preferenceDataStore: FightPandemicsPreferenceDataStore ): AuthTokenLocalDataSource = AuthTokenLocalDataSourceImpl(preferenceDataStore) @Singleton @Provides fun provideProfileRepository( moshi: Moshi, preferenceStorage: PreferenceStorage, profileRemoteDataSource: ProfileRemoteDataSource ): ProfileRepository = ProfileRepositoryImpl(moshi, preferenceStorage, profileRemoteDataSource) }
45
Kotlin
12
14
c054328e374cc6ffa38881165769bf0d84b417c4
2,889
FightPandemics-android
MIT License
checks/src/main/java/com/kozaxinan/android/checks/KtDeclarationKt.kt
kozaxinan
249,517,173
false
{"Kotlin": 94014}
package com.kozaxinan.android.checks import com.android.tools.lint.client.api.JavaEvaluator import com.intellij.psi.PsiMember import org.jetbrains.kotlin.asJava.LightClassGenerationSupport import org.jetbrains.kotlin.asJava.elements.KtLightMember import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueDescriptor import org.jetbrains.kotlin.js.descriptorUtils.getKotlinTypeFqName import org.jetbrains.kotlin.js.descriptorUtils.nameIfStandardType import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.uast.UClass import org.jetbrains.uast.UField import org.jetbrains.uast.toUElementOfType internal fun KtDeclaration.resolve(): DeclarationDescriptor? = LightClassGenerationSupport .getInstance(project) .resolveToDescriptor(this) internal fun KtDeclaration.getKotlinType(): KotlinType? { return try { when (val descriptor = resolve()) { is ValueDescriptor -> descriptor.type is CallableDescriptor -> if (descriptor is FunctionDescriptor && descriptor.isSuspend) descriptor.module.builtIns.nullableAnyType else descriptor.returnType else -> null } } catch (e: Exception) { null } } internal fun KtLightMember<PsiMember>.kotlinTypeName(): String? = kotlinOrigin ?.getKotlinType() ?.nameIfStandardType ?.asString() fun UField.isTypeMutable(evaluator: JavaEvaluator): Boolean { // Trivial check for Kotlin mutable collections. See its doc for details. // Note this doesn't work on typealiases, which unfortunately we can't really // do anything about if ( (sourcePsi as? KtParameter)?.text.matchesAnyOf(KnownMutableKotlinCollections) ) { return true } if ((sourcePsi as? KtParameter)?.getKotlinType()?.getKotlinTypeFqName(true) ?.matchesAnyOf(KnownMutableKotlinCollections) == true ) { return true } val uParamClass = type.let(evaluator::getTypeClass)?.toUElementOfType<UClass>() ?: return false return uParamClass.name in KnownMutableCommonTypesSimpleNames } /** Lint can't read "Mutable*" Kotlin collections that are compiler intrinsics. */ val KnownMutableKotlinCollections = sequenceOf( ".*MutableMap(\\s)?<.*,(\\s)?.*>\\??", ".*MutableSet(\\s)?<.*>\\??", ".*MutableList(\\s)?<.*>\\??", ".*MutableCollection(\\s)?<.*>\\??", ) .map(::Regex) val KnownMutableCommonTypesSimpleNames = setOf( // Set "MutableSet", "ArraySet", "HashSet", // List "MutableList", "ArrayList", // Array "SparseArray", "SparseArrayCompat", "LongSparseArray", "SparseBooleanArray", "SparseIntArray", // Map "MutableMap", "HashMap", "Hashtable", // Compose "MutableState", // Flow "MutableStateFlow", "MutableSharedFlow", // RxJava & RxRelay "PublishSubject", "BehaviorSubject", "ReplaySubject", "PublishRelay", "BehaviorRelay", "ReplayRelay", ) fun String?.matchesAnyOf(patterns: Sequence<Regex>): Boolean { if (isNullOrEmpty()) return false for (regex in patterns) { if (matches(regex)) return true } return false }
1
Kotlin
8
64
44be5497accf3cea91862ee052fa221cb0d2b459
3,658
android-lints
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/MainActivityViewModel.kt
HandFeet
343,118,543
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.example.androiddevchallenge.core.actions.GetAllDogsAction import com.example.androiddevchallenge.core.actions.GetDogAction import com.example.androiddevchallenge.core.types.Dog import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class MainActivityViewModel(app: Application) : AndroidViewModel(app) { private val coroutine = CoroutineScope(Dispatchers.IO) private val getAllDogs = GetAllDogsAction() private val getDog = GetDogAction() val dogs = MutableLiveData<List<Dog>>() val dog = MutableLiveData<Event<Dog>>() fun loadDogs() { coroutine.launch { delay(3000) // Pretend we're loading data dogs.postValue(getAllDogs.invoke()) } } fun getDog(id: Long) { coroutine.launch { delay(500) // Pretend we're loading data dog.postValue(Event(getDog.invoke(id))) } } }
0
Kotlin
0
0
d10eb062f2899946e04e59fb361605c151c38a2c
1,760
devchallenge
Apache License 2.0
composeApp/src/commonMain/kotlin/features/screen/main/EnterTagScreen.kt
MohammedAlsudani
776,718,001
false
{"Kotlin": 40334, "Swift": 594}
package features.screen.main import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import features.component.ProfileRow import features.theme.ScannerTheme import features.theme.colorLightBlack import features.theme.colorLightGreen /** * Composable function for the enter tag screen. * * @param mainViewModel The MainViewModel to handle interactions and data. */ @Composable fun EnterTagScreen(mainViewModel: MainViewModel) { var text by remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .fillMaxWidth() .padding(ScannerTheme.dimensions.dimension24) .weight(1f) ) { Column(modifier = Modifier .background(ScannerTheme.colors.secondary) .padding(ScannerTheme.dimensions.dimension16) .fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(ScannerTheme.dimensions.dimension16), horizontalAlignment = Alignment.CenterHorizontally) { Text(modifier = Modifier.fillMaxWidth(), text = "Enter Bag Tag # to search for", style = ScannerTheme.typography.labelMediumBold) TextField( modifier = Modifier.fillMaxWidth(), colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent, ), value = text, onValueChange = { text = it }, textStyle = ScannerTheme.typography.labelMediumBold, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done) ) Button(shape = RoundedCornerShape(0.dp), onClick = { mainViewModel.onStart() }, colors = ButtonDefaults.buttonColors(colorLightGreen), modifier = Modifier.fillMaxWidth()) { Text(text = "confirm", style = ScannerTheme.typography.bodySmallBold, color = colorLightBlack ) } } } Box(modifier = Modifier.fillMaxWidth()) { EnterTagBottom(mainViewModel) } } } /** * Composable function for the bottom section of the enter tag screen. * * @param mainViewModel The MainViewModel to handle interactions and data. */ @Composable fun EnterTagBottom(mainViewModel: MainViewModel) { Column(modifier = Modifier .fillMaxWidth() .padding(ScannerTheme.dimensions.dimension8), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(ScannerTheme.dimensions.dimension8) ) { ProfileRow(mainViewModel) } }
0
Kotlin
0
0
2ff6212dad2f3ffc29410b21e4c4fe63cb33bee1
4,072
Multiplatform-Compose-App
MIT License
protocol/src/main/kotlin/org/openrs2/protocol/create/downstream/CreateServerOfflineCodec.kt
openrs2
315,027,372
false
null
package org.openrs2.protocol.create.downstream import org.openrs2.protocol.EmptyPacketCodec import javax.inject.Singleton @Singleton public class CreateServerOfflineCodec : EmptyPacketCodec<CreateResponse.CreateServerOffline>( packet = CreateResponse.CreateServerOffline, opcode = 3 )
0
Kotlin
2
8
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
295
openrs2
ISC License
pages-gradle-plugin/src/main/kotlin/com/hendraanggrian/pages/minimal/MinimalPagesOptions.kt
hendraanggrian
501,364,144
false
null
package com.hendraanggrian.pages.minimal import com.hendraanggrian.pages.PageButton import com.hendraanggrian.pages.PagesConfigurationDsl /** * Minimal theme configuration See [minimal-theme](https://github.com/hendraanggrian/minimal-theme/) * for more information/. */ @PagesConfigurationDsl interface MinimalPagesOptions { /** Accent color of the webpage, used as button color. Default is material color `Blue A200`. */ var accentColor: String /** * Accent color of the webpage, used as button color when hovered in light theme. Default is * material color `Blue A200 Dark`. */ var accentLightHoverColor: String /** * Accent color of the webpage, used as button color when hovered in dark theme. Default is * material color `Blue A200 Light`. */ var accentDarkHoverColor: String /** * Author full name in title and footer. If left empty, corresponding tag in footer is removed * but title will still show project name. */ var authorName: String? /** * Author website url in footer. If left empty, author information in footer will not be * clickable. */ var authorUrl: String? /** Project full name in header. If left empty, module name will be used. */ var projectName: String /** Project description in header. If left empty, corresponding tag in header is removed. */ var projectDescription: String? /** Project website url in header. If left empty, corresponding tag in header is removed. */ var projectUrl: String? /** * Add header button, capped at 3. * * @param text button text. * @param url to redirect on button click. */ fun button(text: String, url: String) /** Small theme credit in footer. Enabled by default. */ var footerCredit: Boolean } internal class MinimalPagesOptionsImpl(override var projectName: String) : MinimalPagesOptions { override var accentColor: String = "#448aff" override var accentLightHoverColor: String = "#005ecb" override var accentDarkHoverColor: String = "#83b9ff" override var authorName: String? = null override var authorUrl: String? = null override var projectDescription: String? = null override var projectUrl: String? = null override var footerCredit: Boolean = true internal val buttons = mutableListOf<PageButton>() override fun button(text: String, url: String) { check(buttons.size < 3) { "Minimal buttons are capped at 3." } buttons += PageButton(text, url) } }
0
Kotlin
0
2
3788478bf55c6ffd22e4853c278fe79acf90af7e
2,558
pages-gradle-plugin
Apache License 2.0
app/src/unitTest/kotlin/batect/cli/commands/completion/GenerateShellTabCompletionScriptCommandSpec.kt
batect
102,647,061
false
null
/* Copyright 2017-2022 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.cli.commands.completion import batect.cli.CommandLineOptions import batect.cli.CommandLineOptionsParser import batect.cli.options.OptionDefinition import batect.cli.options.OptionParser import batect.os.HostEnvironmentVariables import batect.telemetry.TestTelemetryCaptor import batect.testutils.createForEachTest import batect.testutils.equalTo import batect.testutils.given import batect.testutils.runForEachTest import batect.testutils.withMessage import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.hasSize import com.natpryce.hamkrest.throws import kotlinx.serialization.json.JsonPrimitive import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.ByteArrayOutputStream import java.io.PrintStream // This class is tested primarily by the tests in the app/src/completionTest directory. object GenerateShellTabCompletionScriptCommandSpec : Spek({ describe("a 'generate shell tab completion script' command") { val option1 by createForEachTest { createMockOption() } val option2 by createForEachTest { createMockOption() } val hiddenOption by createForEachTest { createMockOption(isVisible = false) } val parser by createForEachTest { mock<OptionParser> { on { getOptions() } doReturn setOf(option1, option2, hiddenOption) } } val commandLineOptionsParser by createForEachTest { mock<CommandLineOptionsParser> { on { optionParser } doReturn parser } } val outputStream by createForEachTest { ByteArrayOutputStream() } val bashGenerator by createForEachTest { mock<BashShellTabCompletionScriptGenerator> { on { generate(any(), any()) } doReturn "bash-shell-completion-script" } } val fishGenerator by createForEachTest { mock<FishShellTabCompletionScriptGenerator> { on { generate(any(), any()) } doReturn "fish-shell-completion-script" } } val zshGenerator by createForEachTest { mock<ZshShellTabCompletionScriptGenerator> { on { generate(any(), any()) } doReturn "zsh-shell-completion-script" } } val telemetryCaptor by createForEachTest { TestTelemetryCaptor() } given("the 'BATECT_COMPLETION_PROXY_REGISTER_AS' environment variable is set") { val environmentVariables by createForEachTest { HostEnvironmentVariables( "BATECT_COMPLETION_PROXY_REGISTER_AS" to "batect-1.2.3", "BATECT_COMPLETION_PROXY_VERSION" to "4.5.6", ) } data class TestCase(val shell: Shell, val generator: () -> ShellTabCompletionScriptGenerator, val expectedOutput: String) setOf( TestCase(Shell.Bash, { bashGenerator }, "bash-shell-completion-script"), TestCase(Shell.Fish, { fishGenerator }, "fish-shell-completion-script"), TestCase(Shell.Zsh, { zshGenerator }, "zsh-shell-completion-script"), ).forEach { testCase -> given("the requested shell is ${testCase.shell}") { val commandLineOptions = CommandLineOptions(generateShellTabCompletionScript = testCase.shell) val command by createForEachTest { GenerateShellTabCompletionScriptCommand( commandLineOptions, commandLineOptionsParser, bashGenerator, fishGenerator, zshGenerator, PrintStream(outputStream), environmentVariables, telemetryCaptor, ) } val exitCode by runForEachTest { command.run() } it("returns a zero exit code") { assertThat(exitCode, equalTo(0)) } it("emits the completion script generated by the ${testCase.shell} generator") { assertThat(outputStream.toString(), equalTo(testCase.expectedOutput)) } it("passes only the visible options to the completion script generator") { verify(testCase.generator()).generate(setOf(option1, option2), "batect-1.2.3") } it("records an event in telemetry with the shell name and proxy completion script version") { assertThat(telemetryCaptor.allEvents, hasSize(equalTo(1))) val event = telemetryCaptor.allEvents.single() assertThat(event.type, equalTo("GeneratedShellTabCompletionScript")) assertThat(event.attributes["shell"], equalTo(JsonPrimitive(testCase.shell.name))) assertThat(event.attributes["proxyCompletionScriptVersion"], equalTo(JsonPrimitive("4.5.6"))) } } } } given("the 'BATECT_COMPLETION_PROXY_REGISTER_AS' environment variable is not set") { val environmentVariables by createForEachTest { HostEnvironmentVariables() } val commandLineOptions = CommandLineOptions(generateShellTabCompletionScript = Shell.Fish) val command by createForEachTest { GenerateShellTabCompletionScriptCommand( commandLineOptions, commandLineOptionsParser, bashGenerator, fishGenerator, zshGenerator, PrintStream(outputStream), environmentVariables, telemetryCaptor, ) } it("throws an appropriate exception") { assertThat({ command.run() }, throws(withMessage("'BATECT_COMPLETION_PROXY_REGISTER_AS' environment variable not set."))) } } } }) private fun createMockOption(isVisible: Boolean = true): OptionDefinition = mock { on { showInHelp } doReturn isVisible }
24
null
47
687
67c942241c7d52b057c5268278d6252301c48087
7,061
batect
Apache License 2.0
app/src/main/java/com/reot/remindme/Models/DataBase/TaskManager.kt
OthmaneRegragui
673,755,319
false
null
import android.annotation.SuppressLint import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.reot.remindme.Models.DataBase.OpenOrCreateDataBase import com.reot.remindme.Models.DataClasses.Task class TaskManager(context: Context) { private val dbHelper = OpenOrCreateDataBase(context) private val database: SQLiteDatabase = dbHelper.writableDatabase @SuppressLint("Range") fun getTasks(where:String=""): MutableList<Task> { val taskList = mutableListOf<Task>() val cursor: Cursor = database.rawQuery("select * from tasks $where", null) if (cursor.moveToFirst()) { while (!cursor.isAfterLast) { val id:Int=cursor.getInt(cursor.getColumnIndex("id")) val taskName:String = cursor.getString(cursor.getColumnIndex("taskName")) val taskDescription:String = cursor.getString(cursor.getColumnIndex("taskDescription")) val insertDate:String = cursor.getString(cursor.getColumnIndex("insertDate")) val finishDate:String = cursor.getString(cursor.getColumnIndex("finishDate")) val actuallyFinishDay:String = cursor.getString(cursor.getColumnIndex("actuallyFinishDay")) val isFinish:Boolean = cursor.getInt(cursor.getColumnIndex("isFinish"))==1 val task: Task = Task(id,taskName,taskDescription,insertDate,finishDate,actuallyFinishDay,isFinish) taskList.add(task) cursor.moveToNext() } } return taskList } private fun getContentValues(t: Task):ContentValues{ val contentValues:ContentValues = ContentValues().apply { put("taskName", t.taskName) put("taskDescription", t.taskDescription) put("insertDate", t.insertDate) put("finishDate", t.finishDate) put("actuallyFinishDay", t.actuallyFinishDay) put("isFinish", t.isFinish) } return contentValues } fun insert(t: Task){ val contentValues:ContentValues = getContentValues(t) database.insert("tasks",null,contentValues) } fun delete(id:Int){ var x: Int = database.delete("tasks", "id = '$id'", null) } fun update(t: Task) { val contentValues:ContentValues = getContentValues(t) database.update("tasks", contentValues, "id = '${t.id}'", null) } }
0
Kotlin
0
0
b2d0e51bb519fb535086cb0d2f227f72d52bd2a4
2,502
RemindMe
MIT License
kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetJobs.kt
awsdocs
66,023,605
false
null
//snippet-sourcedescription:[GetDatabases.kt demonstrates how to get databases.] //snippet-keyword:[AWS SDK for Kotlin] //snippet-keyword:[Code Sample] //snippet-keyword:[AWS Glue] //snippet-sourcetype:[full-example] //snippet-sourcedate:[11/04/2021] //snippet-sourceauthor:[scmacdon AWS] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.glue //snippet-start:[glue.kotlin.get_databases.import] import aws.sdk.kotlin.services.glue.GlueClient import aws.sdk.kotlin.services.glue.model.GetDatabasesRequest //snippet-end:[glue.kotlin.get_databases.import] /** To run this Kotlin code example, ensure that you have setup your development environment, including your credentials. For information, see this documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { getAllDatabases() } //snippet-start:[glue.kotlin.get_databases.main] suspend fun getAllDatabases() { val request = GetDatabasesRequest { maxResults = 10 } GlueClient { region = "us-east-1" }.use { glueClient -> val response = glueClient.getDatabases(request) response.databaseList?.forEach { database -> println("The database name is ${database.name}") } } } //snippet-end:[glue.kotlin.get_databases.main]
176
Java
3443
4,877
4022c702782e85f6258770b36d8b4b62b49db873
1,386
aws-doc-sdk-examples
Apache License 2.0
cform-data-cognito-client/src/main/kotlin/pl/wrzasq/cform/data/cognito/client/config/LambdaResourcesFactory.kt
rafalwrzeszcz-wrzasqpl
308,744,180
false
{"Kotlin": 209025}
/** * This file is part of the pl.wrzasq.cform. * * @license http://mit-license.org/ The MIT license * @copyright 2022 © by <NAME> - Wrzasq.pl. */ package pl.wrzasq.cform.data.cognito.client.config import com.fasterxml.jackson.core.type.TypeReference import pl.wrzasq.cform.commons.config.BaseLambdaResourcesFactory import pl.wrzasq.cform.data.cognito.client.action.CreateHandler import pl.wrzasq.cform.data.cognito.client.action.DeleteHandler import pl.wrzasq.cform.data.cognito.client.action.ReadHandler import pl.wrzasq.cform.data.cognito.client.model.ResourceModel import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient import software.amazon.cloudformation.Action import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy import software.amazon.cloudformation.proxy.HandlerRequest import software.amazon.cloudformation.proxy.ProxyClient import software.amazon.cloudformation.proxy.StdCallbackContext /** * Resources factory for AWS Lambda environment. */ class LambdaResourcesFactory : ResourcesFactory, BaseLambdaResourcesFactory<ResourceModel>() { private val createHandler by lazy { CreateHandler(readHandler) } private val deleteHandler by lazy { DeleteHandler() } private val readHandler by lazy { ReadHandler(this) } override fun getRequestTypeReference() = object : TypeReference<HandlerRequest<ResourceModel?, StdCallbackContext>>() {} override fun getResourceTypeReference() = object : TypeReference<ResourceModel?>() {} override fun buildHandlers() = mapOf( Action.CREATE to createHandler, Action.READ to readHandler, Action.DELETE to deleteHandler ) override fun getClient(proxy: AmazonWebServicesClientProxy): ProxyClient<CognitoIdentityProviderClient> = proxy.newProxy { CognitoIdentityProviderClient.builder().build() } }
5
Kotlin
0
1
1bba3b3f56c5016274ad848f903d274a191bfb64
1,882
pl.wrzasq.cform
MIT License
app/src/main/java/com/apaluk/wsplayer/di/AppModule.kt
apaluk
576,009,487
false
null
package com.apaluk.wsplayer.di import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.lifecycleScope import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import javax.inject.Qualifier @Module @InstallIn(SingletonComponent::class) object AppModule { @ApplicationScope @Provides fun provideApplicationScope(): CoroutineScope { return ProcessLifecycleOwner.get().lifecycleScope } } @Qualifier @Retention(AnnotationRetention.BINARY) annotation class ApplicationScope
0
Kotlin
0
0
42a06541f2860112cbe73cd94ebc90e0072017a9
620
ws-player-android
MIT License
src/main/kotlin/com/team4099/robot2021/commands/intake/PrepareClimbCommand.kt
team4099
302,452,784
false
null
package com.team4099.robot2021.commands.intake import com.team4099.lib.logging.Logger import com.team4099.robot2021.config.Constants import com.team4099.robot2021.subsystems.Intake import com.team4099.robot2021.subsystems.Shooter import edu.wpi.first.wpilibj2.command.CommandBase class PrepareClimbCommand : CommandBase() { init { addRequirements(Intake, Shooter) } override fun initialize() { Intake.intakeState = Constants.Intake.IntakeState.IDLE Intake.armState = Constants.Intake.ArmPosition.IN Shooter.hoodState = Shooter.HoodPosition.RETRACTED Logger.addEvent("Intake", "Intake lifted and idle") Logger.addEvent("Shooter", "Hood Retracted") } override fun execute() {} override fun isFinished(): Boolean { return true } }
2
Kotlin
0
0
6ba3f62011f292ca98646dc7c9f86b6dbf1e7357
773
InfiniteRecharge-2021
MIT License
app/src/main/java/at/markushi/checkmate/ui/GoalSettingsScreen.kt
markushi
543,017,728
false
null
@file:OptIn(ExperimentalMaterial3Api::class) package at.markushi.checkmate.ui import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import at.markushi.checkmate.AppViewModel import at.markushi.checkmate.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun GoalSettingsScreen(appViewModel: AppViewModel) { appViewModel.settingsGoal.value?.let { goal -> val goalName = remember { mutableStateOf(TextFieldValue(goal.name)) } val goalColor = remember { mutableStateOf(goal.color.asColor()) } val onBackClicked: () -> Unit = { val newGoal = goal .copy(name = goalName.value.text, color = goalColor.value.toArgb()) appViewModel.onSaveGoalSettingsClicked(newGoal) } Column(modifier = Modifier.padding(vertical = 24.dp)) { NavHeading( title = stringResource(id = R.string.goal_details_edit), onClick = onBackClicked ) Spacer(modifier = Modifier.size(24.dp)) Column(modifier = Modifier.padding(horizontal = 24.dp)) { Text( text = stringResource(R.string.goal_settings_label_name), style = MaterialTheme.typography.labelMedium ) OutlinedTextField(value = goalName.value, placeholder = { Text(text = stringResource(R.string.goal_detail_goal_name_hint)) }, onValueChange = { goalName.value = it }) Spacer(modifier = Modifier.size(24.dp)) Text( text = stringResource(R.string.goal_settings_label_color), style = MaterialTheme.typography.labelMedium ) Spacer(modifier = Modifier.size(8.dp)) Box(modifier = Modifier .size(60.dp) .background(color = goalColor.value, shape = CircleShape) .clip(CircleShape) .clickable { var idx = AppColors.Goals.indexOf(goalColor.value) idx = (idx + 1) % AppColors.Goals.size goalColor.value = AppColors.Goals[idx] }) Spacer(modifier = Modifier.size(24.dp)) Row() { Button(onClick = { val newGoal = goal.copy(name = goalName.value.text, color = goalColor.value.toArgb()) appViewModel.onSaveGoalSettingsClicked(newGoal) }) { Text(text = stringResource(R.string.goal_settings_button_save)) } Spacer(modifier = Modifier.size(8.dp)) if (appViewModel.settingsGoalShowDeleteOption.value) { DangerousButton( onClick = { appViewModel.onDeleteGoalSettingsClicked() }) { Text(text = stringResource(R.string.goal_settings_button_delete)) } } } } } if (appViewModel.settingsGoalShowDeletePrompt.value) { AlertDialog(onDismissRequest = { appViewModel.onDeleteGoalDismissed() }, confirmButton = { Button(onClick = { appViewModel.onDeleteGoalSettingsConfirmedClicked(goal) }) { Text(text = stringResource(R.string.goal_settings_button_delete)) } }, dismissButton = { NeutralButton( onClick = { appViewModel.onDeleteGoalDismissed() }) { Text(text = stringResource(R.string.goal_settings_delete_dialog_cancel)) } }, title = { Text(text = stringResource(R.string.goal_settings_delete_dialog_title)) }, text = { Text(text = stringResource(R.string.goal_settings_delete_dialog_description)) }) } } }
0
Kotlin
0
0
c84d794829b9df2898bc3a10e452ec5e891b11db
5,282
checkmate
Apache License 2.0
app/src/main/kotlin/dev/aaa1115910/bv/ui/theme/Theme.kt
aaa1115910
571,702,700
false
null
package dev.aaa1115910.bv.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.Indication import androidx.compose.foundation.IndicationInstance import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Typography import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import dev.aaa1115910.bv.component.FpsMonitor import dev.aaa1115910.bv.util.Prefs private val BiliColorScheme = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, //secondary = md_theme_dark_secondary, //onSecondary = md_theme_dark_onSecondary, //secondaryContainer = md_theme_dark_secondaryContainer, //onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, background = Color(0xFF121212) ) @Composable fun BVTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = BiliColorScheme val typography = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) android6AndBelowTypography else Typography() val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } val showFps by remember { mutableStateOf(if (!view.isInEditMode) Prefs.showFps else false) } MaterialTheme( colorScheme = colorScheme, typography = typography ) { CompositionLocalProvider( LocalIndication provides NoRippleIndication, ) { Surface { if (showFps) { FpsMonitor { content() } } else { content() } } } } } object NoRippleIndication : Indication { private object NoIndicationInstance : IndicationInstance { override fun ContentDrawScope.drawIndication() { drawContent() } } @Composable override fun rememberUpdatedInstance(interactionSource: InteractionSource): IndicationInstance { return NoIndicationInstance } }
27
Kotlin
63
655
9cb56b133981715d149329200c9f4c43920761e3
3,335
bv
MIT License
src/main/kotlin/me/fzzyhmstrs/amethyst_core/modifier_util/GcCompat.kt
fzzyhmstrs
507,177,454
false
null
package me.fzzyhmstrs.amethyst_core.modifier_util import me.fzzyhmstrs.fzzy_core.modifier_util.AbstractModifier import me.fzzyhmstrs.fzzy_core.trinket_util.TrinketChecker import me.fzzyhmstrs.fzzy_core.trinket_util.TrinketUtil import me.fzzyhmstrs.gear_core.interfaces.ModifierTracking import me.fzzyhmstrs.gear_core.modifier_util.EquipmentModifierHelper import net.minecraft.entity.EquipmentSlot import net.minecraft.entity.LivingEntity import net.minecraft.item.ItemStack import net.minecraft.util.Identifier import java.util.* object GcCompat { private val augmentMap: MutableMap<UUID, AbstractModifier.CompiledModifiers<AugmentModifier>> = mutableMapOf() fun registerAugmentModifierProcessor(){ EquipmentModifierHelper.registerModifierProcessor {stack, entity -> processEquipmentAugmentModifiers(stack, entity)} } fun modifyCompiledAugmentModifiers(original: AbstractModifier.CompiledModifiers<AugmentModifier>, uuid: UUID): AbstractModifier.CompiledModifiers<AugmentModifier>{ val augments = augmentMap[uuid]?:return original val list: MutableList<AugmentModifier> = mutableListOf() list.addAll(augments.modifiers) list.addAll(original.modifiers) return AbstractModifier.CompiledModifiers(list,AugmentModifier().plus(augments.compiledData).plus(original.compiledData)) } private fun processEquipmentAugmentModifiers(stack: ItemStack, entity: LivingEntity){ val item = stack.item if (item !is ModifierTracking) return val uuid = entity.uuid val list: MutableList<Identifier> = mutableListOf() if (TrinketChecker.trinketsLoaded) { val stacks = TrinketUtil.getTrinketStacks(entity) for (stack1 in stacks) { val chk = stack1.item if (chk is ModifierTracking) { list.addAll(chk.getModifiers(stack1)) } } } for(armor in entity.armorItems) { val chk = armor.item if (chk is ModifierTracking){ list.addAll(chk.getModifiers(armor)) } } if (list.isNotEmpty()){ val list2: MutableList<AugmentModifier> = mutableListOf() list.forEach { val chk = ModifierHelper.getModifierByType(it) if (chk != null) list2.add(chk) } val compiler = ModifierDefaults.BLANK_AUG_MOD.compiler() list2.forEach { compiler.add(it) } augmentMap[uuid] = compiler.compile() } } }
0
Kotlin
1
0
2322dc4e3b58ca58a88a1dc42358153024508f78
2,595
ac
MIT License
ui/src/test/kotlin/org/jetbrains/jewel/PainterHintTest.kt
JetBrains
440,164,967
false
{"Kotlin": 722792, "Java": 22778}
package org.jetbrains.jewel import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.state.ToggleableState import org.jetbrains.jewel.painter.PainterHint import org.jetbrains.jewel.painter.PainterPathHint import org.jetbrains.jewel.painter.PainterResourcePathHint import org.jetbrains.jewel.painter.PainterSvgPatchHint import org.jetbrains.jewel.painter.hints.Dark import org.jetbrains.jewel.painter.hints.HiDpi import org.jetbrains.jewel.painter.hints.Override import org.jetbrains.jewel.painter.hints.Palette import org.jetbrains.jewel.painter.hints.Selected import org.jetbrains.jewel.painter.hints.Size import org.jetbrains.jewel.painter.hints.Stateful import org.jetbrains.jewel.painter.hints.Stroke import org.jetbrains.jewel.painter.rememberResourcePainterProvider import org.jetbrains.jewel.painter.writeToString import org.junit.Assert import org.junit.Test import javax.xml.XMLConstants import javax.xml.parsers.DocumentBuilderFactory @Suppress("ImplicitUnitReturnType") class PainterHintTest : BasicJewelUiTest() { @Test fun `empty hint should be ignored`() = runComposeTest({ CompositionLocalProvider(LocalIsDarkTheme provides false) { val provider = rememberResourcePainterProvider("icons/github.svg", PainterHintTest::class.java) val painter1 by provider.getPainter() // must be ignored the None and hit cache val painter2 by provider.getPainter(PainterHint.None) // must be ignored the None and hit cache too val painter3 by provider.getPainter(PainterHint.None, PainterHint.None) Assert.assertEquals(painter1, painter2) Assert.assertEquals(painter3, painter2) } }) { awaitIdle() } private fun String.applyPathHints(vararg hints: PainterHint): String { var result = this val format = this.substringAfterLast('.').lowercase() hints.forEach { if (!it.canApplyTo(format)) return@forEach result = when (it) { is PainterResourcePathHint -> it.patch(result, emptyList()) is PainterPathHint -> it.patch(result) else -> return@forEach } } return result } private val documentBuilderFactory = DocumentBuilderFactory.newDefaultInstance() .apply { setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) } private fun String.applyPaletteHints(vararg hints: PainterHint): String { val doc = documentBuilderFactory.newDocumentBuilder().parse(this.toByteArray().inputStream()) hints.filterIsInstance<PainterSvgPatchHint>() .onEach { it.patch(doc.documentElement) } return doc.writeToString() } @Test fun `dark painter hint should append suffix when isDark is true`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Dark(true)) Assert.assertEquals("icons/github_dark.svg", patchedPath) } @Test fun `dark painter hint should not append suffix when isDark is false`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Dark(false)) Assert.assertEquals(basePath, patchedPath) } @Test fun `override painter hint should replace path entirely`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Override(mapOf("icons/github.svg" to "icons/search.svg"))) Assert.assertEquals("icons/search.svg", patchedPath) } @Test fun `override painter hint should not replace path when not matched`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Override(mapOf("icons/settings.svg" to "icons/search.svg"))) Assert.assertEquals(basePath, patchedPath) } @Test fun `selected painter hint should append suffix when selected is true`() { val basePath = "icons/checkbox.svg" val patchedPath = basePath.applyPathHints(Selected(true)) Assert.assertEquals("icons/checkboxSelected.svg", patchedPath) } @Test fun `selected painter hint should not append suffix when selected is false`() { val basePath = "icons/checkbox.svg" val patchedPath = basePath.applyPathHints(Selected(false)) Assert.assertEquals(basePath, patchedPath) } @Test fun `size painter hint should append suffix when size is not empty`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Size("20x20")) Assert.assertEquals("icons/[email protected]", patchedPath) } @Test fun `size painter hint should not append suffix when size is empty or null`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(Size("")) Assert.assertEquals(basePath, patchedPath) } @Test fun `highDpi painter hint should not append suffix for svg`() { val basePath = "icons/github.svg" val patchedPath = basePath.applyPathHints(HiDpi(true)) Assert.assertEquals(basePath, patchedPath) } @Test fun `highDpi painter hint should append suffix when isHiDpi is true`() { val basePath = "icons/github.png" val patchedPath = basePath.applyPathHints(HiDpi(true)) Assert.assertEquals("icons/[email protected]", patchedPath) } @Test fun `highDpi painter hint should not append suffix when isHiDpi is false`() { val basePath = "icons/github.png" val patchedPath = basePath.applyPathHints(HiDpi(false)) Assert.assertEquals(basePath, patchedPath) } @Test fun `size painter hint should not append suffix for bitmap`() { val basePath = "icons/github.png" val patchedPath = basePath.applyPathHints(Size(20)) Assert.assertEquals(basePath, patchedPath) } @Test fun `size painter hint should throw when size format incorrect`() { val basePath = "icons/github.svg" Assert.assertThrows(IllegalArgumentException::class.java) { basePath.applyPathHints(Size("wrongSizeString")) } } @Test fun `size painter hint should throw with wrong width or height`() { val basePath = "icons/github.svg" Assert.assertThrows(IllegalArgumentException::class.java) { basePath.applyPathHints(Size(-1, 20)) } Assert.assertThrows(IllegalArgumentException::class.java) { basePath.applyPathHints(Size(20, 0)) } } @Test fun `stateful painter hint should append Disabled suffix when enabled is false`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(enabled = false))) Assert.assertEquals("icons/checkboxDisabled.svg", patchedPath) basePath.applyPathHints(Stateful(state.copy(enabled = false, pressed = true, hovered = true, focused = true))) .let { Assert.assertEquals("icons/checkboxDisabled.svg", it) } } @Test fun `stateful painter hint disabled state takes higher priority over other states`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints( Stateful( state.copy( enabled = false, pressed = true, hovered = true, focused = true, ), ), ) Assert.assertEquals("icons/checkboxDisabled.svg", patchedPath) } @Test fun `stateful painter hint should append Focused suffix when focused is true`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(focused = true))) Assert.assertEquals("icons/checkboxFocused.svg", patchedPath) } @Test fun `stateful painter hint focused state takes higher priority over pressed and hovered states`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(pressed = true, hovered = true, focused = true))) Assert.assertEquals("icons/checkboxFocused.svg", patchedPath) } @Test fun `stateful painter hint should append Pressed suffix when pressed is true`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(pressed = true))) Assert.assertEquals("icons/checkboxPressed.svg", patchedPath) } @Test fun `stateful painter hint pressed state takes higher priority over hovered state`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(pressed = true, hovered = true))) Assert.assertEquals("icons/checkboxPressed.svg", patchedPath) } @Test fun `stateful painter hint should append Hovered suffix when hovered is true`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = basePath.applyPathHints(Stateful(state.copy(hovered = true))) Assert.assertEquals("icons/checkboxHovered.svg", patchedPath) } @Test fun `stroke painter hint should append suffix when stroked is true`() { val basePath = "icons/rerun.svg" val patchedPath = basePath.applyPathHints(Stroke(true)) Assert.assertEquals("icons/rerun_stroke.svg", patchedPath) } @Test fun `stroke painter hint should not append suffix when stroked is false`() { val basePath = "icons/rerun.svg" val patchedPath = basePath.applyPathHints(Stroke(false)) Assert.assertEquals(basePath, patchedPath) } @Test fun `palette painter hint should patch colors correctly in SVG`() { val baseSvg = """ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <rect fill="#000000" height="20" stroke="#000000" stroke-opacity="0.5" width="20" x="2" y="2"/> <rect fill="#00ff00" height="16" width="16" x="4" y="4"/> <rect fill="#123456" height="12" width="12" x="6" y="6"/> </svg> """.trimIndent() val patchedSvg = baseSvg.applyPaletteHints( Palette( mapOf( Color(0x80000000) to Color(0xFF123456), Color.Black to Color.White, Color.Green to Color.Red, ), ), ) Assert.assertEquals( """ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <rect fill="#ffffff" height="20" stroke="#123456" stroke-opacity="1.0" width="20" x="2" y="2"/> <rect fill="#ff0000" height="16" width="16" x="4" y="4"/> <rect fill="#123456" height="12" width="12" x="6" y="6"/> </svg> """.trimIndent(), patchedSvg, ) } }
42
Kotlin
15
432
8ee340226eb8c046cb0a14c6013520aa20f1fb02
11,651
jewel
Apache License 2.0
app/src/main/java/com/mmdub/katalogkopipaktib/data/firebase/FirebaseSource.kt
fahmigutawan
648,655,600
false
null
package com.mmdub.katalogkopipaktib.data.firebase import javax.inject.Inject class FirebaseSource @Inject constructor( ) { }
0
Kotlin
0
0
02c7ff52949e3e911f6c705a319f2b294be9bb7c
127
Jetpack-KatalogKopiPakTib
MIT License
android-app/app/src/androidTest/java/org/dit113group3/androidapp/MainMenuActivityTest.kt
DIT113-V22
471,134,970
false
{"Kotlin": 40714, "C++": 7537, "Java": 5308, "GDScript": 829}
package org.dit113group3.androidapp import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import org.dit113group3.androidapp.ScreenOrientationChange.Companion.orientationLandscape import org.junit.Test import org.junit.runner.RunWith @RunWith (AndroidJUnit4ClassRunner::class) class MainMenuActivityTest { val sleep = Thread.sleep(2000) @Test //Checks if Main Menu activity is launching fun test_isMainMenuActivityInView() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.mainMenu)).check(matches(isDisplayed())) sleep } @Test //Checks if Welcome title is present on Main Menu screen fun test_visibility_welcome_title() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.welcomeText)).check(matches(isDisplayed())) sleep } @Test //Checks if PLAY button is present on Main Menu screen fun test_visibility_play_button() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.playButton)).check(matches(isDisplayed())) sleep } @Test //Checks if RULES button is present on Main Menu screen fun test_visibility_rules_button() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.rulesButton)).check(matches(isDisplayed())) sleep } @Test //Checks if CREDITS button is present on Credits Menu screen fun test_visibility_credits_button() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.creditsButton)).check(matches(isDisplayed())) sleep } @Test //Checks if button PLAY has correct navigation fun test_play_button_navigation() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.playButton)).perform(click()) onView(withId(R.id.mainLayout)).check(matches(isDisplayed())) sleep } @Test //Checks if button RULES has correct navigation fun test_rules_button_navigation() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.rulesButton)).perform(click()) onView(withId(R.id.rulesLayout)).check(matches(isDisplayed())) sleep } @Test //Checks if button CREDITS has correct navigation fun test_credits_button_navigation() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.creditsButton)).perform(click()) onView(withId(R.id.creditsLayout)).check(matches(isDisplayed())) sleep } @Test //Checks if button EXIT on RULES screen leads to Main Menu screen fun test_rules_screen_exit_button_navigation() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.rulesButton)).perform(click()) onView(withId(R.id.rulesLayout)).check(matches(isDisplayed())) onView(withId(R.id.exit)).perform(click()) onView(withId(R.id.mainMenu)).check(matches(isDisplayed())) sleep } @Test //Checks if button EXIT on CREDITS screen leads to Main Menu screen fun test_credits_screen_exit_button_navigation() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.creditsButton)).perform(click()) onView(withId(R.id.creditsLayout)).check(matches(isDisplayed())) onView(withId(R.id.creditsExit)).perform(click()) onView(withId(R.id.mainMenu)).check(matches(isDisplayed())) sleep } @Test //Checks if game logo is present on Main Menu screen fun test_isLogoVisible() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(withId(R.id.logo)).check(matches(isDisplayed())) sleep } @Test //Checks if rotation from portrait mode changes to landscape fun test_landscapeMode() { val activityScenario = ActivityScenario.launch(MainMenuActivity::class.java) onView(isRoot()).perform(orientationLandscape()) sleep onView(withId(R.id.mainMenu)).check(matches(isDisplayed())) sleep } }
0
Kotlin
0
0
a0459c62a52047e62ffba072c97d41560757c1e1
4,719
group-03
MIT License
benchmark/src/main/kotlin/com/skydoves/balloon/benchmark/BaselineProfileGenerator.kt
skydoves
196,805,860
false
null
package com.skydoves.balloon.benchmark import androidx.benchmark.macro.ExperimentalBaselineProfilesApi import androidx.benchmark.macro.junit4.BaselineProfileRule import org.junit.Rule import org.junit.Test @ExperimentalBaselineProfilesApi class BaselineProfileGenerator { @get:Rule val baselineProfileRule = BaselineProfileRule() @Test fun startup() = baselineProfileRule.collectBaselineProfile( packageName = "com.skydoves.balloon.benchmark.app" ) { pressHome() // This block defines the app's critical user journey. Here we are interested in // optimizing for app startup. But you can also navigate and scroll // through your most important UI. startActivityAndWait() device.waitForIdle() } }
6
Kotlin
213
2,562
51690205a8332c434dd1eda0ae0ecf4e22e49023
760
Balloon
Apache License 2.0
src/main/kotlin/com/dwolla/resource/businessclassifications/BusinessClassification.kt
Dwolla
189,449,029
false
null
package com.dwolla.resource.businessclassifications import com.dwolla.resource.HalResource import com.dwolla.resource.Links data class BusinessClassification( @JvmField val _links: Links, @JvmField val _embedded: EmbeddedIndustryClassifications, @JvmField val id: String, @JvmField val name: String ) : HalResource() { override fun getLinks(): Links { return _links } }
7
Kotlin
5
9
013d9d5cbf963c85224c0fd9c68f84044046ed17
404
dwolla-v2-kotlin
MIT License
src/me/anno/input/ActionManager.kt
won21kr
351,713,352
true
{"Kotlin": 1983578, "Java": 301507, "C": 75596, "GLSL": 9436}
package me.anno.input import me.anno.config.DefaultConfig import me.anno.gpu.GFX.gameTime import me.anno.gpu.GFX.inFocus import me.anno.io.utils.StringMap import me.anno.studio.StudioBase import me.anno.studio.rems.RemsStudio import me.anno.ui.base.Panel import org.apache.logging.log4j.LogManager object ActionManager { private val LOGGER = LogManager.getLogger(ActionManager::class) private val keyDragDelay = DefaultConfig["ui.keyDragDelay", 0.5f] private val localActions = HashMap<Pair<String, KeyCombination>, List<String>>() private val globalKeyCombinations = HashMap<KeyCombination, List<String>>() private val globalActions = HashMap<String, () -> Boolean>() private lateinit var keyMap: StringMap fun init(){ keyMap = DefaultConfig["ui.keyMap", { createDefaultKeymap() }] parseConfig(keyMap) } var createDefaultKeymap = { LOGGER.warn("Using default keymap... this should not happen!") StringMap() } fun parseConfig(config: StringMap){ for((key, value) in config.entries){ val keys = key.split('.') val namespace = keys[0] val button = keys.getOrNull(1) if(button == null){ LOGGER.warn("KeyCombination $key needs button!") continue } val buttonEvent = keys.getOrNull(2) if(buttonEvent == null){ LOGGER.warn("[WARN] KeyCombination $key needs type!") continue } val modifiers = keys.getOrElse(3){ "" } val keyComb = KeyCombination.parse(button, buttonEvent, modifiers) if(keyComb != null){ val values = value.toString().split('|') if(namespace.equals("global", true)){ globalKeyCombinations[keyComb] = values } else { localActions[namespace to keyComb] = values } } } } fun onKeyTyped(key: Int){ onEvent(0f, 0f, KeyCombination(key, Input.keyModState, KeyCombination.Type.TYPED), false) } fun onKeyUp(key: Int){ onEvent(0f, 0f, KeyCombination(key, Input.keyModState, KeyCombination.Type.UP), false) } fun onKeyDown(key: Int){ onEvent(0f, 0f, KeyCombination(key, Input.keyModState, KeyCombination.Type.DOWN), false) } fun onKeyDoubleClick(key: Int){ onEvent(0f, 0f, KeyCombination(key, Input.keyModState, KeyCombination.Type.DOUBLE), false) } fun onKeyHoldDown(dx: Float, dy: Float, key: Int, save: Boolean){ onEvent(dx, dy, KeyCombination(key, Input.keyModState, if(save) KeyCombination.Type.PRESS else KeyCombination.Type.PRESS_UNSAFE), true) } fun onMouseIdle() = onMouseMoved(0f, 0f) fun onMouseMoved(dx: Float, dy: Float){ Input.keysDown.forEach { (key, downTime) -> onKeyHoldDown(dx, dy, key, false) val deltaTime = (gameTime - downTime) * 1e-9f if(deltaTime >= keyDragDelay){ onKeyHoldDown(dx, dy, key, true) } } } fun onEvent(dx: Float, dy: Float, combination: KeyCombination, isContinuous: Boolean){ var panel = inFocus.firstOrNull() // filter action keys, if they are typing keys and a typing field is in focus val isWriting = combination.isWritingKey && (panel?.isKeyInput() == true) if(!isWriting){ executeGlobally(0f, 0f, false, globalKeyCombinations[combination]) } val x = Input.mouseX val y = Input.mouseY targetSearch@ while(panel != null){ val clazz = panel.getClassName() val actions = localActions[clazz to combination] ?: localActions["*" to combination] if(actions != null){ for(action in actions){ if(panel.onGotAction(x, y, dx, dy, action, isContinuous)){ break@targetSearch } } } panel = panel.parent } } fun executeLocally(dx: Float, dy: Float, isContinuous: Boolean, panel: Panel, actions: List<String>?){ if(actions == null) return for(action in actions){ if(panel.onGotAction(Input.mouseX, Input.mouseY, dx, dy, action, isContinuous)){ break } } } fun executeGlobally(dx: Float, dy: Float, isContinuous: Boolean, actions: List<String>?){ if(actions == null) return for(action in actions){ if(globalActions[action]?.invoke() == true){ return } } for(window in StudioBase.instance.windowStack){ for(panel in window.panel.listOfAll){ executeLocally(dx, dy, isContinuous, panel, actions) } } } fun registerGlobalAction(name:String, action: () -> Boolean){ globalActions[name] = action } }
0
null
0
0
b85295f59ddfa9fc613a384d439fd1b30b06a5a4
5,032
RemsStudio
Apache License 2.0
rest-api/internal/weather/api/src/main/kotlin/github/makeitvsolo/kweather/weather/api/datasource/location/operation/RemoveFavourite.kt
makeitvsolo
743,151,452
false
{"Kotlin": 294456, "TypeScript": 606, "JavaScript": 469, "HTML": 354}
package github.makeitvsolo.kweather.weather.api.datasource.location.operation import github.makeitvsolo.kweather.core.error.handling.Result import github.makeitvsolo.kweather.weather.api.datasource.location.error.RemoveFavouriteError import java.math.BigDecimal interface RemoveFavourite { fun removeFavourite( accountId: String, latitude: BigDecimal, longitude: BigDecimal ): Result<Unit, RemoveFavouriteError> }
1
Kotlin
0
0
2664ab660be3047a27e32b0f56e7cc8da7df13cd
450
kweather
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/KeyboardDoubleArrowLeftTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/KeyboardDoubleArrowLeftTwoTone") package mui.icons.material @JsName("default") external val KeyboardDoubleArrowLeftTwoTone: SvgIconComponent
10
null
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
224
kotlin-wrappers
Apache License 2.0
app/src/main/java/br/com/otaviolms/tabnews/utils/DateUtils.kt
otaviolms
650,890,216
false
null
package br.com.otaviolms.tabnews.utils import android.content.Context import br.com.otaviolms.tabnews.R import java.time.Duration import java.time.LocalDateTime import java.time.ZonedDateTime import java.time.format.DateTimeFormatter fun calcularHorasPassadas(data: String): Long { val formato = DateTimeFormatter.ISO_DATE_TIME val dataFornecida = ZonedDateTime.parse(data, formato) val dataAtual = LocalDateTime.now().atZone(dataFornecida.zone) val diferenca = Duration.between(dataFornecida, dataAtual) val resultado = diferenca.toHours().toInt() return if(resultado == 0 || resultado <= 0) 0 else diferenca.toHours() } fun calcularDiasPassados(data: String): Int { val formato = DateTimeFormatter.ISO_DATE_TIME val dataFornecida = ZonedDateTime.parse(data, formato) val dataAtual = LocalDateTime.now().atZone(dataFornecida.zone) val diferenca = Duration.between(dataFornecida, dataAtual) val resultado = diferenca.toDays().toInt() return if(resultado == 0 || resultado <= 0) 0 else diferenca.toDays().toInt() } fun montarStringTempoPassado(context: Context, data: String): String { val horasPassadas = calcularHorasPassadas(data) return when{ horasPassadas < 1.0 -> context.resources.getQuantityString(R.plurals.horasPlural, 0, 0) horasPassadas < 24.0 -> context.resources.getQuantityString(R.plurals.horasPlural, horasPassadas.toInt(), horasPassadas.toInt()) else -> { val diasPassados = calcularDiasPassados(data) context.resources.getQuantityString(R.plurals.diasPlural, diasPassados, diasPassados) } } }
0
Kotlin
0
0
67b78bdece3095cba0992f856177157e34fd872d
1,638
TabNews-Android
MIT License
app/src/main/java/com/nsromapa/frenzapp/saytalk/activities/EditProfile.kt
saytoonz
198,504,153
false
null
package ca.scooter.talkufy.activities import android.app.Activity import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.util.Log import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import ca.scooter.talkufy.R import ca.scooter.talkufy.models.Models import com.google.android.gms.tasks.Continuation import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.UserProfileChangeRequest import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask import ca.scooter.talkufy.utils.FirebaseUtils import ca.scooter.talkufy.utils.utils import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageView import kotlinx.android.synthetic.main.activity_edit_profile.* import kotlinx.android.synthetic.main.layout_profile_image_picker.* import me.shaohui.advancedluban.Luban import me.shaohui.advancedluban.OnCompressListener import org.jetbrains.anko.selector import org.jetbrains.anko.toast import java.io.File class EditProfile : AppCompatActivity() { var myUID = FirebaseUtils.getUid() val context = this var isProfileChanged = false lateinit var bitmap:Bitmap lateinit var imageFile:File var isForAccountCreation = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_profile) isForAccountCreation = intent.getBooleanExtra(utils.constants.KEY_IS_ON_ACCOUNT_CREATION, false) if(supportActionBar!=null && !isForAccountCreation) supportActionBar!!.setDisplayHomeAsUpEnabled(true) title = "My Profile" myUID = FirebaseUtils.getUid() FirebaseUtils.loadProfilePic(this, myUID, profile_circleimageview) ///Pick Profile Image Button profile_pick_btn.setOnClickListener { // ImagePicker.pickImage(context) selector("Edit profile picture", listOf("Change picture", "Remove picture")) { _, pos -> if(pos == 0){ CropImage.activity() .setGuidelines(CropImageView.Guidelines.ON) .setCropShape(CropImageView.CropShape.RECTANGLE) .setAspectRatio(1,1) .start(this) } else{ //delete pic FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_PROFILE_PIC_URL).setValue("").addOnSuccessListener { toast("Profile pic removed") } } } } ///Fill TextEdits with user info if user // already logged in if(FirebaseUtils.isLoggedIn()) { FirebaseUtils.ref.user(myUID) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(p0: DataSnapshot) { var profileURL = "" var name = "" var full_name = "" var city = "" var bio = "Hey there, I am using Talkafy!" if(p0.exists()){ try { profileURL=p0.getValue(Models.User::class.java)?.profile_pic_url!! name = p0.getValue(Models.User::class.java)?.name!! full_name= p0.getValue(Models.User::class.java)?.full_name!! bio = p0.getValue(Models.User::class.java)?.bio!! city = p0.getValue(Models.User::class.java)?.city!! } catch (e: Exception) { } } profile_name.setText(name) profile_bio.setText(bio) profile_location.setText(city) profile_full_name.setText(full_name) } }) } ///Update user Info updateProfileBtn.setOnClickListener { /// Check if username is empty if(profile_name.text.isEmpty()){ profile_name.error = "Username cannot be empty" return@setOnClickListener } /// Check if full name is empty if(profile_full_name.text.isEmpty()){ profile_full_name.error = "Enter your full name" return@setOnClickListener } /// Check if city is empty if(profile_location.text.isEmpty()){ profile_location.error = "Tell us your current city" return@setOnClickListener } /// Check if bio is empty if(profile_bio.text.isEmpty()){ profile_bio.error = "Write your current status" return@setOnClickListener } if(isProfileChanged) { val storageRef = FirebaseUtils.ref.profilePicStorageRef(myUID) val dbRef = FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_PROFILE_PIC_URL) uploadProfilePic(context, imageFile, storageRef, dbRef, "Profile updated") // uploadImage(imageFile) isProfileChanged = false } //Update Username FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_NAME) .setValue(profile_name.text.toString()) //Update full name FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_FULL_NAME) .setValue(profile_full_name.text.toString()) //Update current City FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_CITY) .setValue(profile_location.text.toString()) //Update current BIO FirebaseUtils.ref.user(myUID) .child(FirebaseUtils.KEY_BIO) .setValue(profile_bio.text.toString()) if(profile_name.text.isNotEmpty()){ if(FirebaseUtils.isLoggedIn()) { FirebaseAuth.getInstance().currentUser!!.updateProfile( UserProfileChangeRequest.Builder() .setDisplayName(profile_name.text.toString().trim()).build()) } } if(intent.getBooleanExtra(utils.constants.KEY_IS_ON_ACCOUNT_CREATION, false) and !isProfileChanged){ startActivity(Intent(context, HomeActivity::class.java)) finish() } } //load profile name FirebaseUtils.ref.user(FirebaseUtils.getUid()) .child(FirebaseUtils.KEY_NAME) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(p0: DataSnapshot) { profile_name.setText( p0.value.toString().trim() ) } }) } private fun uploadProfilePic(context: Context, file: File, storageRef: StorageReference, dbRef: DatabaseReference, toastAfterUploadIfAny: String){ val dialog = ProgressDialog(context) dialog.setMessage("Please wait a moment...") dialog.setCancelable(false) dialog.show() Log.d("EditProfile", "uploadImage: File size = "+file.length()/1024) val uploadTask = storageRef.putFile(utils.getUriFromFile(context, file)) uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task -> if (!task.isSuccessful) { task.exception?.let { throw it } } Log.d("FirebaseUtils", "uploadedImage: size = "+task.result!!.bytesTransferred/1024) return@Continuation storageRef.downloadUrl }) .addOnCompleteListener { task -> try { dialog.dismiss() }catch (e:Exception){} if(task.isSuccessful) { val link = task.result dbRef.setValue(link.toString()) .addOnSuccessListener { // isProfileChanged = false if(toastAfterUploadIfAny.isNotEmpty()) utils.toast(context, toastAfterUploadIfAny) } if(FirebaseUtils.isLoggedIn()) { FirebaseAuth.getInstance().currentUser!! .updateProfile( UserProfileChangeRequest.Builder() .setPhotoUri(link).build() ) } if(intent.getBooleanExtra(utils.constants.KEY_IS_ON_ACCOUNT_CREATION, false)){ startActivity(Intent(context, HomeActivity::class.java)) finish() } } else utils.toast(context, task.exception!!.message.toString()) } .addOnSuccessListener { dialog.dismiss() } .addOnFailureListener{ dialog.dismiss() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when(resultCode){ Activity.RESULT_OK -> { utils.printIntentKeyValues(data!!) val result = CropImage.getActivityResult(data) val filePath = result.uri.path Log.d("EditProfile", "onActivityResult: $filePath") //utils.getRealPathFromURI(context, result.uri) //ImagePicker.getImagePathFromResult(context, requestCode, resultCode, data) Luban.compress(context, File(filePath)) .putGear(Luban.THIRD_GEAR) .launch(object : OnCompressListener { override fun onStart() { } override fun onSuccess(file: File?) { imageFile = file!! bitmap = BitmapFactory.decodeFile(file.path) profile_circleimageview.setImageBitmap(bitmap) isProfileChanged = true } override fun onError(e: Throwable?) { utils.toast(context, e!!.message.toString()) } }) } } super.onActivityResult(requestCode, resultCode, data) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if(item!!.itemId == android.R.id.home) finish() return super.onOptionsItemSelected(item) } }
13
Java
6
9
1f038906591448325d5976622a81283750ea81a4
11,589
SAY-Talk
MIT License
app/src/main/java/com/wl/accountbook/ui/common/components/CustomDivider.kt
LiuWei339
726,117,960
false
{"Kotlin": 194634}
package com.wl.accountbook.ui.common.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.wl.accountbook.extensions.toPx import com.wl.accountbook.ui.theme.LineGray @Composable fun HorizontalDivider( thickness: Float = 1f, color: Color = LineGray, modifier: Modifier = Modifier ) { Box( modifier = modifier .fillMaxWidth() .height(0.5.dp) .drawWithContent { drawRect( color = color, size = size.copy(height = thickness) ) } ) } @Composable fun VerticalDivider( thickness: Float = 1f, color: Color = LineGray, modifier: Modifier = Modifier ) { Box( modifier = modifier .fillMaxHeight() .width(0.5.dp) .drawWithContent { drawRect( color = color, size = size.copy(width = thickness) ) } ) } @Composable fun HorizontalDivider( thickness: Dp, color: Color = LineGray, modifier: Modifier = Modifier ) { val thicknessInPx = thickness.toPx() HorizontalDivider( thicknessInPx, color, modifier ) } @Composable fun VerticalDivider( thickness: Dp, color: Color = LineGray, modifier: Modifier = Modifier ) { val thicknessInPx = thickness.toPx() VerticalDivider( thicknessInPx, color, modifier ) }
0
Kotlin
0
0
724782478f661fb6c07bce01c853d1680bcd5433
1,942
Account-Book
Apache License 2.0
app/src/main/java/com/droid47/petpot/base/widgets/anim/ScrollAwareFABBehavior.kt
AndroidKiran
247,345,176
false
null
package com.droid47.petpot.base.widgets.anim import android.content.Context import android.util.AttributeSet import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.floatingactionbutton.FloatingActionButton.OnVisibilityChangedListener class ScrollAwareFABBehavior @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FloatingActionButton.Behavior() { override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { return (axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll( coordinatorLayout, child, directTargetChild, target, axes, type )) } override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, 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 > 0 && child.visibility == View.VISIBLE) { // User scrolled down and the FAB is currently visible -> hide the FAB child.hide(object : OnVisibilityChangedListener() { override fun onHidden(fab: FloatingActionButton) { super.onHidden(fab) fab.visibility = View.INVISIBLE } }) } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { // User scrolled up and the FAB is currently not visible -> show the FAB child.show() } } }
1
null
1
2
07d9c0c4f0d5bef32d9705f6bb49f938ecc456e3
2,176
PetPot
Apache License 2.0
guides/micronaut-oracle-autonomous-db/kotlin/src/test/kotlin/example/micronaut/repository/ThingRepositoryTest.kt
micronaut-projects
326,986,278
false
null
/* * Copyright 2017-2024 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.micronaut.repository import example.micronaut.domain.Thing import io.micronaut.context.ApplicationContext import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.UUID import java.util.stream.Collectors class ThingRepositoryTest { private lateinit var applicationContext: ApplicationContext private lateinit var thingRepository: ThingRepository @BeforeEach fun setup() { applicationContext = ApplicationContext.run() thingRepository = applicationContext.getBean(ThingRepository::class.java) } @Test fun testFindAll() { // clear out existing data; safe because each // test runs in a transaction that's rolled back thingRepository.deleteAll() assertEquals(0, thingRepository.count()) thingRepository.saveAll(listOf( Thing("t1"), Thing("t2"), Thing("t3")) ) val things = thingRepository.findAll() assertEquals(3, things.size) assertEquals( listOf("t1", "t2", "t3"), things.stream() .map(Thing::name) .sorted() .collect(Collectors.toList())) } @Test fun testFindByName() { val name = UUID.randomUUID().toString() var thing = thingRepository.findByName(name).orElse(null) assertNull(thing) thingRepository.save(Thing(name)) thing = thingRepository.findByName(name).orElse(null) assertNotNull(thing) assertEquals(name, thing.name) } @AfterEach fun cleanup() { applicationContext.close() } }
209
null
31
36
f40e50dc8f68cdb3080cb3802d8082ada9ca6787
2,508
micronaut-guides
Creative Commons Attribution 4.0 International
app/src/main/java/com/imagefinder/storage/local/repository/image/ImageRepository.kt
maxchn
310,660,738
false
null
package com.imagefinder.storage.local.repository.image import com.imagefinder.domain.entity.ImageItem import com.imagefinder.storage.local.data.ImageItemDto import io.reactivex.Observable interface ImageRepository { fun getAll(): Observable<List<ImageItem>> fun upsert(newItem: ImageItemDto) fun removeAll() }
0
Kotlin
0
0
b31a10a5f1265dfd19769ad2ab98a5e7e7aac17e
324
ImageFinder
MIT License
simplified-ui-accounts/src/main/java/org/nypl/simplified/ui/accounts/ekirjasto/EkirjastoAccountViewModel.kt
NatLibFi
730,988,035
false
{"Kotlin": 3589739, "JavaScript": 853788, "Java": 403841, "CSS": 65407, "HTML": 49894, "Shell": 18611, "Ruby": 7554}
package org.nypl.simplified.ui.accounts.ekirjasto import android.app.Application import android.content.pm.PackageManager import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import org.librarysimplified.documents.DocumentStoreType import org.librarysimplified.documents.DocumentType import org.librarysimplified.documents.internal.SimpleDocument import org.librarysimplified.services.api.Services import org.nypl.simplified.accounts.api.AccountEvent import org.nypl.simplified.accounts.api.AccountEventLoginStateChanged import org.nypl.simplified.accounts.api.AccountEventUpdated import org.nypl.simplified.accounts.api.AccountID import org.nypl.simplified.accounts.api.AccountLoginState import org.nypl.simplified.accounts.api.AccountProviderAuthenticationDescription import org.nypl.simplified.accounts.database.api.AccountType import org.nypl.simplified.bookmarks.api.BookmarkEvent import org.nypl.simplified.bookmarks.api.BookmarkServiceType import org.nypl.simplified.bookmarks.api.BookmarkSyncEnableStatus import org.nypl.simplified.buildconfig.api.BuildConfigurationServiceType import org.nypl.simplified.listeners.api.FragmentListenerType import org.nypl.simplified.profiles.controller.api.ProfileAccountLoginRequest import org.nypl.simplified.profiles.controller.api.ProfilesControllerType import org.nypl.simplified.taskrecorder.api.TaskStep import org.nypl.simplified.ui.accounts.AccountDetailEvent import org.nypl.simplified.ui.errorpage.ErrorPageParameters import org.slf4j.LoggerFactory class EkirjastoAccountViewModel( private val accountId: AccountID, private val listener: FragmentListenerType<AccountDetailEvent>, private val application: Application, ) : AndroidViewModel(application) { private val services = Services.serviceDirectory() private val profilesController = services.requireService(ProfilesControllerType::class.java) private val bookmarkService = services.requireService(BookmarkServiceType::class.java) private val logger = LoggerFactory.getLogger(EkirjastoAccountViewModel::class.java) val documents = services.requireService(DocumentStoreType::class.java) /** * Logging in was explicitly requested. This is tracked in order to allow for optionally * closing the account fragment on successful logins. */ @Volatile private var loginExplicitlyRequested: Boolean = false private val subscriptions = CompositeDisposable() private val accountLiveMutable: MutableLiveData<AccountType> = MutableLiveData( this.profilesController .profileCurrent() .account(this.accountId) ) val accountLive: LiveData<AccountType> = this.accountLiveMutable val account: AccountType = this.accountLive.value!! val authenticationDescription: AccountProviderAuthenticationDescription.Ekirjasto get() = this.account.provider.authentication as AccountProviderAuthenticationDescription.Ekirjasto /** * A live data element that tracks the status of the bookmark syncing switch for the * current account. */ private val accountSyncingSwitchStatusMutable: MutableLiveData<BookmarkSyncEnableStatus> = MutableLiveData(this.bookmarkService.bookmarkSyncStatus(account.id)) val accountSyncingSwitchStatus: LiveData<BookmarkSyncEnableStatus> = this.accountSyncingSwitchStatusMutable val appVersion: String by lazy { try { val context = this.getApplication<Application>() val pkgManager = context.packageManager val pkgInfo = pkgManager.getPackageInfo(context.packageName, 0) val versionName = pkgInfo.versionName val versionCode = pkgInfo.versionCode "$versionName (${versionCode})" } catch (e: PackageManager.NameNotFoundException) { "Unknown" } } init { this.subscriptions.add( this.profilesController.accountEvents() .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onAccountEvent) ) this.subscriptions.add( this.bookmarkService.bookmarkEvents .ofType(BookmarkEvent.BookmarkSyncSettingChanged::class.java) .filter { event -> event.accountID == this.accountId } .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onBookmarkEvent) ) } private fun onBookmarkEvent(event: BookmarkEvent.BookmarkSyncSettingChanged) { this.accountSyncingSwitchStatusMutable.postValue(event.status) } private fun onAccountEvent(accountEvent: AccountEvent) { when (accountEvent) { is AccountEventUpdated -> { logger.debug("Account Updated") if (accountEvent.accountID == this.accountId) { this.handleAccountUpdated(accountEvent) } } is AccountEventLoginStateChanged -> { logger.debug("Login State Updated: {}",accountEvent.state) if (accountEvent.accountID == this.accountId) { this.handleLoginStateChanged(accountEvent) } } } } private fun handleAccountUpdated(event: AccountEventUpdated) { this.accountLiveMutable.value = this.account /* * Synthesize a bookmark event so that we fetch up-to-date values if the account * logs in or out. */ this.onBookmarkEvent( BookmarkEvent.BookmarkSyncSettingChanged( accountID = event.accountID, status = this.bookmarkService.bookmarkSyncStatus(event.accountID) ) ) } private fun handleLoginStateChanged(event: AccountEventLoginStateChanged) { this.accountLiveMutable.value = this.account if (this.loginExplicitlyRequested) { when (event.state) { is AccountLoginState.AccountLoggedIn -> { // Scheduling explicit close of account fragment this.loginExplicitlyRequested = false this.listener.post(AccountDetailEvent.LoginSucceeded) } is AccountLoginState.AccountLoginFailed -> { this.loginExplicitlyRequested = false } else -> { // Doing nothing } } } } override fun onCleared() { super.onCleared() this.subscriptions.clear() } val buildConfig = services.requireService(BuildConfigurationServiceType::class.java) val eula: DocumentType? = this.account.provider.eula?.let { SimpleDocument(it.toURL()) } val privacyPolicy: DocumentType? = this.account.provider.privacyPolicy?.let { SimpleDocument(it.toURL()) } val licenses: DocumentType? = this.account.provider.license?.let { SimpleDocument(it.toURL()) } /** * Logging out was requested. This is tracked in order to allow for * clearing the Barcode and PIN fields after the request has completed. */ var pendingLogout: Boolean = false /** * Enable/disable bookmark syncing. */ fun enableBookmarkSyncing(enabled: Boolean) { this.logger.debug("EnableBookmarkSyncing: $enabled") this.bookmarkService.bookmarkSyncEnable(this.accountId, enabled) } fun tryLogin(request: ProfileAccountLoginRequest) { this.loginExplicitlyRequested = true this.profilesController.profileAccountLogin(request) } fun tryLogout() { this.pendingLogout = true // update the login state here so the UI is changed and the user is aware // that something's happening if (this.account.loginState is AccountLoginState.AccountLoggedIn || this.account.loginState is AccountLoginState.AccountLogoutFailed ) { this.logger.debug("Account Logging Out") this.account.setLoginState( AccountLoginState.AccountLoggingOut( this.account.loginState.credentials!!, "" ) ) } else { this.logger.warn("Invalid AccountLoginState for logout: {}",this.account.loginState) } this.profilesController.profileAccountLogout(this.accountId) } fun openErrorPage(taskSteps: List<TaskStep>) { val parameters = ErrorPageParameters( emailAddress = this.buildConfig.supportErrorReportEmailAddress, body = "", subject = "[simplye-error-report]", attributes = sortedMapOf(), taskSteps = taskSteps, popPrevious = true ) this.listener.post(AccountDetailEvent.OpenErrorPage(parameters)) } }
1
Kotlin
0
0
e4fc752f3cba3427d3822ccae259c57983488e46
8,329
ekirjasto-android-core
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Scale.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Scale: ImageVector get() { if (_scale != null) { return _scale!! } _scale = Builder(name = "Scale", 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) { moveToRelative(21.0f, 2.0f) horizontalLineToRelative(-4.54f) arcToRelative(5.973f, 5.973f, 0.0f, false, false, -8.92f, 0.0f) horizontalLineToRelative(-4.54f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, 3.0f) verticalLineToRelative(19.0f) horizontalLineToRelative(24.0f) verticalLineToRelative(-19.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, -3.0f, -3.0f) close() moveTo(12.0f, 2.0f) arcToRelative(4.0f, 4.0f, 0.0f, false, true, 4.0f, 4.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(-3.382f) lineToRelative(1.282f, -2.553f) lineToRelative(-1.79f, -0.894f) lineToRelative(-1.728f, 3.447f) horizontalLineToRelative(-2.382f) verticalLineToRelative(-1.0f) arcToRelative(4.0f, 4.0f, 0.0f, false, true, 4.0f, -4.0f) close() moveTo(22.0f, 22.0f) horizontalLineToRelative(-20.0f) verticalLineToRelative(-17.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) horizontalLineToRelative(3.35f) arcToRelative(5.976f, 5.976f, 0.0f, false, false, -0.35f, 2.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(12.0f) verticalLineToRelative(-3.0f) arcToRelative(5.976f, 5.976f, 0.0f, false, false, -0.35f, -2.0f) horizontalLineToRelative(3.35f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) close() } } .build() return _scale!! } private var _scale: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,971
icons
MIT License
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/autofill/AutofillManager.kt
androidx
256,589,781
false
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.autofill import androidx.compose.ui.ExperimentalComposeUiApi /** * Autofill API. * * This interface is available to all composables via a CompositionLocal. The composable can then * notify the Autofill framework that user values have been committed as required. */ @ExperimentalComposeUiApi interface AutofillManager { /** * Indicate the autofill context should be committed. * * Call this function to notify the Autofill framework that the current context should be * committed. After calling this function, the framework considers the form submitted, and the * credentials entered will be processed. */ fun commit() /** * Indicate the autofill context should be canceled. * * Call this function to notify the Autofill framework that the current context should be * canceled. After calling this function, the framework will stop the current autofill session * without processing any information entered in the autofillable field. */ fun cancel() }
29
Kotlin
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
1,679
androidx
Apache License 2.0
app/src/main/java/xyz/hetula/dragonair/weather/WeatherManager.kt
hetula
185,856,171
false
null
package xyz.hetula.dragonair.weather import android.content.Context import android.util.Log import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.VolleyError import com.android.volley.toolbox.Volley import xyz.hetula.dragonair.Constants import xyz.hetula.dragonair.R import xyz.hetula.dragonair.util.GsonRequest import java.util.* class WeatherManager { private var mInitialized = false private lateinit var mApiKey: String private lateinit var mReqQueue: RequestQueue fun initialize(context: Context) { if (!mInitialized) { mApiKey = context.getString(R.string.api_key) mReqQueue = Volley.newRequestQueue(context.applicationContext) mInitialized = true } } fun close() { if (mInitialized) { mReqQueue.stop() mInitialized = false } } fun fetchCurrentWeather(cityId: Long, callback: (Weather) -> Unit) { if (!mInitialized) { Log.e(TAG, "Not initialized, no weather") return } mReqQueue.add( GsonRequest( currentWeatherUrl(mApiKey, cityId), Weather::class.java, HashMap(), callback, Err() ) ) } private fun currentWeatherUrl(apiKey: String, cityId: Long): String { return String.format(Locale.ROOT, Constants.Api.CURRENT_WEATHER_API_URL, cityId, apiKey) } private class Err : Response.ErrorListener { override fun onErrorResponse(error: VolleyError?) { Log.e("Dragonair", "VolleyErr: $error") } } companion object { private const val TAG = "WeatherManager" } }
0
Kotlin
0
0
7ce1fba3fcb73621efbbc0d2794e151e83f1da2a
1,769
wforweather
Apache License 2.0
src/main/kotlin/io/github/rhdunn/ktor/Parameters.kt
rhdunn
738,613,487
false
{"Kotlin": 26507, "CSS": 551, "JavaScript": 204}
// Copyright (C) 2024 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0 package io.github.rhdunn.ktor import io.ktor.http.* import io.ktor.server.plugins.* import io.ktor.util.converters.* import io.ktor.util.reflect.* @Suppress("NOTHING_TO_INLINE", "unused") inline fun Parameters.getOrNull(name: String): String? { return get(name)?.takeIf { it.isNotEmpty() } } @Suppress("unused") inline fun <reified R : Any> Parameters.getOrNull(name: String): R? { return getOrNullImpl(name, typeInfo<R>()) } @PublishedApi internal fun <R : Any> Parameters.getOrNullImpl(name: String, typeInfo: TypeInfo): R? { val values = getAll(name) ?.filter { it.isNotEmpty() } ?.takeIf { it.isNotEmpty() } ?: return null return try { @Suppress("UNCHECKED_CAST") DefaultConversionService.fromValues(values, typeInfo) as R } catch (cause: Exception) { throw ParameterConversionException(name, typeInfo.type.simpleName ?: typeInfo.type.toString(), cause) } }
0
Kotlin
0
0
fc7226f028b72e300106e3a5136ade2e28d73f39
1,003
ktor-template
Apache License 2.0
compiler/fir/analysis-tests/testData/resolve/smartcasts/lambdas/smartcastOnLambda.kt
JetBrains
3,432,266
false
null
// !DUMP_CFG fun test(func: (() -> Unit)?) { if (func != null) { func() } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
92
kotlin
Apache License 2.0
src/main/kotlin/com/github/kerubistan/kerub/model/dynamic/VirtualStorageBlockDeviceAllocation.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.model.dynamic import com.fasterxml.jackson.annotation.JsonIgnore import com.github.kerubistan.kerub.model.io.VirtualDiskFormat interface VirtualStorageBlockDeviceAllocation : VirtualStorageAllocation { @get:JsonIgnore override val type: VirtualDiskFormat get() = VirtualDiskFormat.raw }
109
Kotlin
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
328
kerub
Apache License 2.0